repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
Elfansoer/dota-2-lua-abilities
4,563
scripts/vscripts/lua_abilities/tinker_laser_lua/tinker_laser_lua.lua
tinker_laser_lua = class({}) LinkLuaModifier( "modifier_tinker_laser_lua", "lua_abilities/tinker_laser_lua/modifier_tinker_laser_lua", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- -- Ability Phase Start function tinker_laser_lua:OnAbilityPhaseStart() -- effects local sound_cast = "Hero_Tinker.LaserAnim" EmitSoundOn( sound_cast, self:GetCaster() ) return true -- if success end -------------------------------------------------------------------------------- -- Ability Start function tinker_laser_lua:OnSpellStart() -- unit identifier local caster = self:GetCaster() local target = self:GetCursorTarget() -- cancel if Linken if target:TriggerSpellAbsorb( self ) then return end -- load data local duration_hero = self:GetSpecialValueFor("duration_hero") local duration_creep = self:GetSpecialValueFor("duration_creep") local damage = self:GetSpecialValueFor("laser_damage") -- get targets local targets = {} table.insert( targets, target ) if caster:HasScepter() then self:Refract( targets, 1 ) end -- precache damage local damage = { -- victim = hTarget, attacker = caster, damage = damage, damage_type = DAMAGE_TYPE_PURE, ability = self } for _,enemy in pairs(targets) do -- apply damage damage.victim = enemy ApplyDamage( damage ) -- add modifier local duration = duration_hero if enemy:IsCreep() then duration = duration_creep end enemy:AddNewModifier( caster, -- player source self, -- ability source "modifier_tinker_laser_lua", -- modifier name { duration = duration } -- kv ) end -- effects self:PlayEffects( targets ) end function tinker_laser_lua:Refract( targets, jumps ) -- load data local scepter_range = self:GetSpecialValueFor("scepter_bounce_range") -- Find Units in Radius local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), -- int, your team number targets[jumps]:GetOrigin(), -- point, center point nil, -- handle, cacheUnit. (not known) scepter_range, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO, -- int, type filter DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE + DOTA_UNIT_TARGET_FLAG_NO_INVIS, -- int, flag filter FIND_CLOSEST, -- int, order filter false -- bool, can grow cache ) -- check for valid closest not-yet-affected next target local next_target = nil for _,enemy in pairs(enemies) do local candidate = true for _,target in pairs(targets) do if enemy==target then candidate = false break end end if candidate then next_target = enemy break end end -- recursive if next_target then table.insert( targets, next_target ) self:Refract( targets, jumps+1 ) end end -------------------------------------------------------------------------------- function tinker_laser_lua:PlayEffects( targets ) -- Get Resources local particle_cast = "particles/units/heroes/hero_tinker/tinker_laser.vpcf" local sound_cast = "Hero_Tinker.Laser" local sound_target = "Hero_Tinker.LaserImpact" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() ) local attach = "attach_attack1" if self:GetCaster():ScriptLookupAttachment( "attach_attack2" )~=0 then attach = "attach_attack2" end ParticleManager:SetParticleControlEnt( effect_cast, 9, self:GetCaster(), PATTACH_POINT_FOLLOW, attach, Vector(0,0,0), -- unknown true -- unknown, true ) ParticleManager:SetParticleControlEnt( effect_cast, 1, targets[1], PATTACH_POINT_FOLLOW, "attach_hitloc", Vector(0,0,0), -- unknown true -- unknown, true ) ParticleManager:ReleaseParticleIndex( effect_cast ) -- Create Sound EmitSoundOn( sound_cast, self:GetCaster() ) EmitSoundOn( sound_target, targets[1] ) if #targets>1 then for i=2,#targets do -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() ) ParticleManager:SetParticleControlEnt( effect_cast, 9, targets[i-1], PATTACH_POINT_FOLLOW, "attach_hitloc", Vector(0,0,0), -- unknown true -- unknown, true ) ParticleManager:SetParticleControlEnt( effect_cast, 1, targets[i], PATTACH_POINT_FOLLOW, "attach_hitloc", Vector(0,0,0), -- unknown true -- unknown, true ) ParticleManager:ReleaseParticleIndex( effect_cast ) -- create sound EmitSoundOn( sound_target, targets[i] ) end end end
412
0.945829
1
0.945829
game-dev
MEDIA
0.995364
game-dev
0.98206
1
0.98206
amethyst/amethyst
31,742
amethyst_input/src/bindings.rs
//! Defines binding structure used for saving and loading input settings. use std::{ borrow::{Borrow, Cow}, error::Error, fmt::{Debug, Display, Formatter, Result as FmtResult}, hash::Hash, }; use fnv::FnvHashMap as HashMap; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; use super::{axis, Axis, Button}; use crate::bindings; /// Used for saving and loading input settings. /// /// An action can either be a single button or a combination of them. /// /// # Examples /// /// Example Ron config file: /// ```ron /// ( /// axes: { /// "updown": Emulated( /// pos: Key(Up), /// neg: Key(Down) /// ), /// "leftright": Multiple([ // Multiple bindings for one axis /// Emulated( /// pos: Key(Right), /// neg: Key(Left) /// ), /// Emulated( /// pos: Key(D), /// neg: Key(A) /// ) /// ]) /// }, /// actions: { /// "fire": [ [Mouse(Left)], [Key(X)] ], // Multiple bindings for one action /// "reload": [ [Key(LControl), Key(R)] ] // Combinations of multiple bindings possible /// } /// ) /// ``` #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct Bindings { pub(super) axes: HashMap<Cow<'static, str>, Axis>, /// The inner array here is for button combinations, the other is for different possibilities. /// /// So for example if you want to quit by either "Esc" or "Ctrl+q" you would have /// `[[Esc], [Ctrl, Q]]`. pub(super) actions: HashMap<Cow<'static, str>, SmallVec<[SmallVec<[Button; 2]>; 4]>>, } /// An enum of possible errors that can occur when binding an action or axis. #[derive(Clone, Debug, PartialEq)] pub enum BindingError { /// Axis buttons have overlap with an action combo of length one. AxisButtonAlreadyBoundToAction(Cow<'static, str>, Button), /// Axis buttons provided have overlap with an existing axis. AxisButtonAlreadyBoundToAxis(Cow<'static, str>, Axis), /// A combo of length one was provided, and it overlaps with an axis binding. ButtonBoundToAxis(Cow<'static, str>, Axis), /// Combo provided was already bound to the contained action. ComboAlreadyBound(Cow<'static, str>), /// Combo provided for action binding has two (or more) of the same button. ComboContainsDuplicates(Cow<'static, str>), /// That specific axis on that specific controller is already in use for an /// axis binding. ControllerAxisAlreadyBound(Cow<'static, str>), /// The given axis was already bound for use MouseAxisAlreadyBound(Cow<'static, str>), /// You attempted to bind a mousewheel axis twice. MouseWheelAxisAlreadyBound(Cow<'static, str>), } impl Display for BindingError { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match *self { BindingError::ComboContainsDuplicates(ref id) => { write!( f, "Combo provided contained two (or more) of the same button: {}", id ) } BindingError::ComboAlreadyBound(ref action) => { write!(f, "Combo provided was already bound to action {}", action) } BindingError::ButtonBoundToAxis(ref id, ref _axis) => { write!(f, "Button provided was a button in use by axis {}", id) } BindingError::AxisButtonAlreadyBoundToAxis(ref id, ref _axis) => { write!( f, "Axis provided contained a button that's already in use by axis {}", id ) } BindingError::AxisButtonAlreadyBoundToAction(ref id, ref _action) => { write!( f, "Axis provided contained a button that's already in use by single button action {}", id ) } BindingError::ControllerAxisAlreadyBound(ref id) => { write!(f, "Controller axis provided is already in use by {}", id) } BindingError::MouseAxisAlreadyBound(ref id) => { write!(f, "Mouse axis provided is already in use by {}", id) } BindingError::MouseWheelAxisAlreadyBound(ref id) => { write!(f, "Mouse wheel axis provided is already in use by {}", id) } } } } impl Error for BindingError {} /// An enum of possible errors that can occur when removing an action binding. #[derive(Debug, Clone, PartialEq)] pub enum ActionRemovedError { /// The action has bindings, but this isn't one of them. ActionExistsButBindingDoesnt, /// The action provided doesn't exist. ActionNotFound, /// Combo provided for action binding has two (or more) of the same button. BindingContainsDuplicates, } impl Display for ActionRemovedError { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match *self { ActionRemovedError::ActionExistsButBindingDoesnt => { write!(f, "Action found, but binding isn't present") } ActionRemovedError::ActionNotFound => write!(f, "Action not found"), ActionRemovedError::BindingContainsDuplicates => { write!(f, "Binding removal requested contains duplicate buttons") } } } } impl Error for ActionRemovedError {} impl Bindings { /// Creates a new empty Bindings structure #[must_use] pub fn new() -> Self { bindings::Bindings::default() } } impl Bindings { /// Assign an axis to an ID value /// /// This will insert a new axis if no entry for this id exists. /// If one does exist this will replace the axis at that id and return it. pub fn insert_axis<A: Into<Cow<'static, str>>>( &mut self, id: A, axis: Axis, ) -> Result<Option<Axis>, BindingError> { let id = id.into(); self.check_axis_invariants(&id, &axis)?; Ok(self.axes.insert(id, axis)) } /// Removes an axis, this will return the removed axis if successful. pub fn remove_axis<A>(&mut self, id: &A) -> Option<Axis> where Cow<'static, str>: Borrow<A>, A: Hash + Eq + ?Sized, { self.axes.remove(id) } /// Returns a reference to an axis. pub fn axis<A>(&self, id: &A) -> Option<&Axis> where Cow<'static, str>: Borrow<A>, A: Hash + Eq + ?Sized, { self.axes.get(id) } /// Gets a list of all axes pub fn axes(&self) -> impl Iterator<Item = &Cow<'static, str>> { self.axes.keys() } /// Add a button or button combination to an action. /// /// This will attempt to insert a new binding between this action and the button(s). pub fn insert_action_binding<B: IntoIterator<Item = Button>>( &mut self, id: Cow<'static, str>, binding: B, ) -> Result<(), BindingError> { let bind: SmallVec<[Button; 2]> = binding.into_iter().collect(); self.check_action_invariants(&id, bind.as_slice())?; let mut make_new = false; match self.actions.get_mut(&id) { Some(action_bindings) => { action_bindings.push(bind.clone()); } None => { make_new = true; } } if make_new { let mut bindings = SmallVec::new(); bindings.push(bind); self.actions.insert(id, bindings); } Ok(()) } /// Removes an action binding that was assigned previously. pub fn remove_action_binding<A>( &mut self, id: &A, binding: &[Button], ) -> Result<(), ActionRemovedError> where Cow<'static, str>: Borrow<A>, A: Hash + Eq + ?Sized, { for i in 0..binding.len() { for j in (i + 1)..binding.len() { if binding[i] == binding[j] { return Err(ActionRemovedError::BindingContainsDuplicates); } } } let kill_it; if let Some(action_bindings) = self.actions.get_mut(id) { let index = action_bindings.iter().position(|b| { b.len() == binding.len() // The bindings can be provided in any order, but they must all // be the same bindings. && b.iter().all(|b| binding.iter().any(|binding| b == binding)) }); if let Some(index) = index { action_bindings.swap_remove(index); } else { return Err(ActionRemovedError::ActionExistsButBindingDoesnt); } kill_it = action_bindings.is_empty(); } else { return Err(ActionRemovedError::ActionNotFound); } if kill_it { self.actions.remove(id); } Ok(()) } /// Returns an action's bindings. pub fn action_bindings<A>(&self, id: &A) -> impl Iterator<Item = &[Button]> where Cow<'static, str>: Borrow<A>, A: Hash + Eq + ?Sized, { self.actions .get(id) .map(SmallVec::as_slice) .unwrap_or(&[]) .iter() .map(SmallVec::as_slice) } /// Gets a list of all action bindings pub fn actions(&self) -> impl Iterator<Item = &Cow<'static, str>> { self.actions.keys() } /// Check that this structure upholds its guarantees. Should only be necessary when serializing or deserializing the bindings. pub fn check_invariants(&mut self) -> Result<(), BindingError> { // The easiest way to do this is to use the existing code that checks for invariants when adding bindings. // So we'll just remove and then re-add all of the bindings. let action_bindings = self .actions .iter() .map(|(k, v)| (k.clone(), v.clone())) .collect::<Vec<_>>(); for (k, v) in action_bindings { for c in v { self.remove_action_binding(&k, &c) .expect("Unreachable: We just cloned the bindings, they can't be incorrect."); self.insert_action_binding(k.clone(), c)?; } } let axis_bindings = self .axes .iter() .map(|(k, v)| (k.clone(), v.clone())) .collect::<Vec<_>>(); for (k, a) in axis_bindings { self.remove_axis(&k); self.insert_axis(k, a)?; } Ok(()) } fn check_action_invariants(&self, id: &str, bind: &[Button]) -> Result<(), BindingError> { // Guarantee each button is unique. for i in 0..bind.len() { for j in (i + 1)..bind.len() { if bind[i] == bind[j] { return Err(BindingError::ComboContainsDuplicates(id.to_owned().into())); } } } if bind.len() == 1 { for (k, a) in &self.axes { if a.conflicts_with_button(bind[0]) { return Err(BindingError::ButtonBoundToAxis(k.clone(), a.clone())); } } } for (k, a) in &self.actions { for c in a { if c.len() == bind.len() && bind.iter().all(|bind| c.iter().any(|c| c == bind)) { return Err(BindingError::ComboAlreadyBound(k.clone())); } } } Ok(()) } fn check_axis_invariants(&self, id: &str, axis: &Axis) -> Result<(), BindingError> { for (k, a) in self.axes.iter().filter(|(k, _a)| *k != id) { if let Some(conflict_type) = axis.conflicts_with_axis(a) { return Err(match conflict_type { axis::Conflict::Button => { BindingError::AxisButtonAlreadyBoundToAxis(k.clone(), a.clone()) } axis::Conflict::ControllerAxis => { BindingError::ControllerAxisAlreadyBound(k.clone()) } axis::Conflict::MouseAxis => BindingError::MouseAxisAlreadyBound(k.clone()), axis::Conflict::MouseWheelAxis => { BindingError::MouseWheelAxisAlreadyBound(k.clone()) } }); } } for (k, a) in &self.actions { for c in a { // Since you can't bind combos to an axis we only need to check combos with length 1. if c.len() == 1 && axis.conflicts_with_button(c[0]) { return Err(BindingError::AxisButtonAlreadyBoundToAction( k.clone(), c[0], )); } } } Ok(()) } } #[cfg(test)] mod tests { use winit::event::{MouseButton, VirtualKeyCode}; use super::*; use crate::{button::*, controller::ControllerAxis}; #[test] fn add_and_remove_actions() { const TEST_ACTION: Cow<'static, str> = Cow::Borrowed("test_action"); let mut bindings = Bindings::new(); assert_eq!(bindings.actions().next(), None); assert_eq!(bindings.action_bindings(&TEST_ACTION).next(), None); bindings .insert_action_binding( TEST_ACTION, [Button::Mouse(MouseButton::Left)].iter().cloned(), ) .unwrap(); assert_eq!(bindings.actions().collect::<Vec<_>>(), vec![&TEST_ACTION]); let action_bindings = bindings.action_bindings(&TEST_ACTION).collect::<Vec<_>>(); assert_eq!(action_bindings, vec![[Button::Mouse(MouseButton::Left)]]); bindings .remove_action_binding(&TEST_ACTION, &[Button::Mouse(MouseButton::Left)]) .unwrap(); assert_eq!(bindings.actions().next(), None); assert_eq!(bindings.action_bindings(&TEST_ACTION).next(), None); bindings .insert_action_binding( TEST_ACTION, [ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right), ] .iter() .cloned(), ) .unwrap(); assert_eq!(bindings.actions().collect::<Vec<_>>(), vec![&TEST_ACTION],); let action_bindings = bindings.action_bindings(&TEST_ACTION).collect::<Vec<_>>(); assert_eq!( action_bindings, vec![[ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right) ]] ); bindings .remove_action_binding( &TEST_ACTION, &[ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right), ], ) .unwrap(); assert_eq!(bindings.actions().next(), None); assert_eq!(bindings.action_bindings(&TEST_ACTION).next(), None); bindings .insert_action_binding( TEST_ACTION, [ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right), ] .iter() .cloned(), ) .unwrap(); assert_eq!( bindings .remove_action_binding( &TEST_ACTION, &[ Button::Mouse(MouseButton::Right), Button::Mouse(MouseButton::Right), ], ) .unwrap_err(), ActionRemovedError::BindingContainsDuplicates ); assert_eq!( bindings .remove_action_binding(&TEST_ACTION, &[Button::Mouse(MouseButton::Left),],) .unwrap_err(), ActionRemovedError::ActionExistsButBindingDoesnt ); assert_eq!( bindings .remove_action_binding("nonsense_action", &[Button::Mouse(MouseButton::Left),],) .unwrap_err(), ActionRemovedError::ActionNotFound ); let actions = bindings.actions().collect::<Vec<_>>(); assert_eq!(actions, vec![&TEST_ACTION]); let action_bindings = bindings.action_bindings(&TEST_ACTION).collect::<Vec<_>>(); assert_eq!( action_bindings, vec![[ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right) ]] ); bindings .remove_action_binding( &TEST_ACTION, &[ Button::Mouse(MouseButton::Right), Button::Mouse(MouseButton::Left), ], ) .unwrap(); assert_eq!(bindings.actions().next(), None); assert_eq!(bindings.action_bindings(&TEST_ACTION).next(), None); } #[test] fn insert_errors() { const TEST_ACTION: Cow<'static, str> = Cow::Borrowed("test_action"); const TEST_ACTION_2: Cow<'static, str> = Cow::Borrowed("test_action_2"); const TEST_AXIS: Cow<'static, str> = Cow::Borrowed("test_axis"); const TEST_AXIS_2: Cow<'static, str> = Cow::Borrowed("test_axis_2"); const TEST_CONTROLLER_AXIS: Cow<'static, str> = Cow::Borrowed("test_controller_axis"); const TEST_CONTROLLER_AXIS_2: Cow<'static, str> = Cow::Borrowed("test_controller_axis_2"); const TEST_MOUSEWHEEL_AXIS: Cow<'static, str> = Cow::Borrowed("test_mousewheel_axis"); const TEST_MOUSEWHEEL_AXIS_2: Cow<'static, str> = Cow::Borrowed("test_mousewheel_axis_2"); let mut bindings = Bindings::new(); assert_eq!( bindings .insert_action_binding( TEST_ACTION, [ Button::Mouse(MouseButton::Left), Button::Mouse(MouseButton::Right), Button::Mouse(MouseButton::Left), ] .iter() .cloned(), ) .unwrap_err(), BindingError::ComboContainsDuplicates(TEST_ACTION) ); bindings .insert_action_binding( TEST_ACTION, [Button::Mouse(MouseButton::Left)].iter().cloned(), ) .unwrap(); assert_eq!( bindings .insert_action_binding( TEST_ACTION, [Button::Mouse(MouseButton::Left),].iter().cloned(), ) .unwrap_err(), BindingError::ComboAlreadyBound(TEST_ACTION) ); assert_eq!( bindings .insert_action_binding( TEST_ACTION_2, [Button::Mouse(MouseButton::Left),].iter().cloned(), ) .unwrap_err(), BindingError::ComboAlreadyBound(TEST_ACTION) ); assert_eq!( bindings .insert_axis( TEST_AXIS, Axis::Emulated { pos: Button::Mouse(MouseButton::Left), neg: Button::Mouse(MouseButton::Right), }, ) .unwrap_err(), BindingError::AxisButtonAlreadyBoundToAction( TEST_ACTION, Button::Mouse(MouseButton::Left) ) ); assert_eq!( bindings .insert_axis( TEST_AXIS, Axis::Multiple(vec![Axis::Emulated { pos: Button::Mouse(MouseButton::Left), neg: Button::Mouse(MouseButton::Right), }]) ) .unwrap_err(), BindingError::AxisButtonAlreadyBoundToAction( TEST_ACTION, Button::Mouse(MouseButton::Left) ) ); assert_eq!( bindings .insert_axis( TEST_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), }, ) .unwrap(), None ); assert_eq!( bindings .insert_action_binding( TEST_ACTION_2, [Button::Key(VirtualKeyCode::Left),].iter().cloned(), ) .unwrap_err(), BindingError::ButtonBoundToAxis( TEST_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), } ) ); assert_eq!( bindings .insert_action_binding( TEST_AXIS_2, [Button::Key(VirtualKeyCode::Left),].iter().cloned(), ) .unwrap_err(), BindingError::ButtonBoundToAxis( TEST_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), } ) ); assert_eq!( bindings .insert_axis( TEST_AXIS_2, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Up), }, ) .unwrap_err(), BindingError::AxisButtonAlreadyBoundToAxis( TEST_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), } ) ); assert_eq!( bindings .insert_axis( TEST_CONTROLLER_AXIS, Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, }, ) .unwrap(), None ); assert_eq!( bindings .insert_axis( TEST_CONTROLLER_AXIS, Axis::Controller { controller_id: 0, axis: ControllerAxis::LeftX, invert: false, dead_zone: 0.25, }, ) .unwrap(), Some(Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, }) ); assert_eq!( bindings .insert_axis( TEST_CONTROLLER_AXIS_2, Axis::Controller { controller_id: 0, axis: ControllerAxis::LeftX, invert: true, dead_zone: 0.1, }, ) .unwrap_err(), BindingError::ControllerAxisAlreadyBound(TEST_CONTROLLER_AXIS) ); assert_eq!( bindings .insert_axis(TEST_MOUSEWHEEL_AXIS, Axis::MouseWheel { horizontal: true },) .unwrap(), None ); assert_eq!( bindings .insert_axis(TEST_MOUSEWHEEL_AXIS, Axis::MouseWheel { horizontal: false },) .unwrap(), Some(Axis::MouseWheel { horizontal: true }) ); assert_eq!( bindings .insert_axis( TEST_MOUSEWHEEL_AXIS_2, Axis::MouseWheel { horizontal: false }, ) .unwrap_err(), BindingError::MouseWheelAxisAlreadyBound(TEST_MOUSEWHEEL_AXIS) ); } #[test] fn multiple_axis_conflicts() { const TEST_ACTION: Cow<'static, str> = Cow::Borrowed("test_action"); const NORMAL_AXIS: Cow<'static, str> = Cow::Borrowed("normal_axis"); const MULTIPLE_AXIS: Cow<'static, str> = Cow::Borrowed("multiple_axis"); const NORMAL_CONTROLLER_AXIS: Cow<'static, str> = Cow::Borrowed("normal_controller_axis"); const MULTIPLE_CONTROLLER_AXIS: Cow<'static, str> = Cow::Borrowed("multiple_controller_axis"); const MULTIPLE_CONTROLLER_AXIS_2: Cow<'static, str> = Cow::Borrowed("multiple_controller_axis_2"); let mut bindings = Bindings::new(); assert_eq!( bindings .insert_axis( NORMAL_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::A), neg: Button::Key(VirtualKeyCode::B) }, ) .unwrap(), None ); assert_eq!( bindings .insert_axis( MULTIPLE_AXIS, Axis::Multiple(vec![ Axis::Emulated { pos: Button::Key(VirtualKeyCode::C), neg: Button::Key(VirtualKeyCode::D) }, Axis::Emulated { pos: Button::Key(VirtualKeyCode::A), neg: Button::Key(VirtualKeyCode::E) } ]) ) .unwrap_err(), BindingError::AxisButtonAlreadyBoundToAxis( NORMAL_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::A), neg: Button::Key(VirtualKeyCode::B) } ) ); assert_eq!( bindings .insert_axis( MULTIPLE_AXIS, Axis::Multiple(vec![ Axis::Emulated { pos: Button::Key(VirtualKeyCode::C), neg: Button::Key(VirtualKeyCode::D) }, Axis::Emulated { pos: Button::Key(VirtualKeyCode::E), neg: Button::Key(VirtualKeyCode::F) } ]) ) .unwrap(), None ); assert_eq!( bindings .insert_action_binding( TEST_ACTION, [Button::Key(VirtualKeyCode::C),].iter().copied(), ) .unwrap_err(), BindingError::ButtonBoundToAxis( MULTIPLE_AXIS, Axis::Multiple(vec![ Axis::Emulated { pos: Button::Key(VirtualKeyCode::C), neg: Button::Key(VirtualKeyCode::D) }, Axis::Emulated { pos: Button::Key(VirtualKeyCode::E), neg: Button::Key(VirtualKeyCode::F) } ]) ) ); assert_eq!( bindings .insert_axis( NORMAL_CONTROLLER_AXIS, Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, } ) .unwrap(), None ); assert_eq!( bindings .insert_axis( MULTIPLE_CONTROLLER_AXIS, Axis::Multiple(vec![Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, }]) ) .unwrap_err(), BindingError::ControllerAxisAlreadyBound(NORMAL_CONTROLLER_AXIS) ); assert_eq!( bindings .insert_axis( MULTIPLE_CONTROLLER_AXIS, Axis::Multiple(vec![Axis::Controller { controller_id: 0, axis: ControllerAxis::LeftX, invert: false, dead_zone: 0.25, }]) ) .unwrap(), None ); assert_eq!( bindings .insert_axis( MULTIPLE_CONTROLLER_AXIS_2, Axis::Multiple(vec![Axis::Controller { controller_id: 0, axis: ControllerAxis::LeftX, invert: false, dead_zone: 0.25, }]) ) .unwrap_err(), BindingError::ControllerAxisAlreadyBound(MULTIPLE_CONTROLLER_AXIS) ); } #[test] fn add_and_remove_axes() { const TEST_AXIS: Cow<'static, str> = Cow::Borrowed("test_axis"); const TEST_CONTROLLER_AXIS: Cow<'static, str> = Cow::Borrowed("test_controller_axis"); const TEST_MOUSEWHEEL_AXIS: Cow<'static, str> = Cow::Borrowed("test_mousewheel_axis"); let mut bindings = Bindings::new(); assert_eq!( bindings .insert_axis( TEST_AXIS, Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), }, ) .unwrap(), None ); assert_eq!( bindings.remove_axis("test_axis"), Some(Axis::Emulated { pos: Button::Key(VirtualKeyCode::Left), neg: Button::Key(VirtualKeyCode::Right), }) ); assert_eq!( bindings .insert_axis( TEST_CONTROLLER_AXIS, Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, }, ) .unwrap(), None ); assert_eq!( bindings.remove_axis(&TEST_CONTROLLER_AXIS), Some(Axis::Controller { controller_id: 0, axis: ControllerAxis::RightX, invert: false, dead_zone: 0.25, }) ); assert_eq!( bindings .insert_axis(TEST_MOUSEWHEEL_AXIS, Axis::MouseWheel { horizontal: false },) .unwrap(), None ); assert_eq!( bindings.remove_axis(&TEST_MOUSEWHEEL_AXIS), Some(Axis::MouseWheel { horizontal: false }) ); } }
412
0.886215
1
0.886215
game-dev
MEDIA
0.498659
game-dev
0.912905
1
0.912905
gameplay3d/gameplay-deps
9,798
bullet-2.82-r2704/Extras/Serialize/BulletWorldImporter/btWorldImporter.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2012 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_WORLD_IMPORTER_H #define BT_WORLD_IMPORTER_H #include "LinearMath/btTransform.h" #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedObjectArray.h" #include "LinearMath/btHashMap.h" class btCollisionShape; class btCollisionObject; class btRigidBody; class btTypedConstraint; class btDynamicsWorld; struct ConstraintInput; class btRigidBodyColladaInfo; struct btCollisionShapeData; class btTriangleIndexVertexArray; class btStridingMeshInterface; struct btStridingMeshInterfaceData; class btGImpactMeshShape; class btOptimizedBvh; struct btTriangleInfoMap; class btBvhTriangleMeshShape; class btPoint2PointConstraint; class btHingeConstraint; class btConeTwistConstraint; class btGeneric6DofConstraint; class btGeneric6DofSpringConstraint; class btSliderConstraint; class btGearConstraint; struct btContactSolverInfo; struct btTypedConstraintData; struct btTypedConstraintFloatData; struct btTypedConstraintDoubleData; struct btRigidBodyDoubleData; struct btRigidBodyFloatData; #ifdef BT_USE_DOUBLE_PRECISION #define btRigidBodyData btRigidBodyDoubleData #else #define btRigidBodyData btRigidBodyFloatData #endif//BT_USE_DOUBLE_PRECISION class btWorldImporter { protected: btDynamicsWorld* m_dynamicsWorld; int m_verboseMode; btAlignedObjectArray<btCollisionShape*> m_allocatedCollisionShapes; btAlignedObjectArray<btCollisionObject*> m_allocatedRigidBodies; btAlignedObjectArray<btTypedConstraint*> m_allocatedConstraints; btAlignedObjectArray<btOptimizedBvh*> m_allocatedBvhs; btAlignedObjectArray<btTriangleInfoMap*> m_allocatedTriangleInfoMaps; btAlignedObjectArray<btTriangleIndexVertexArray*> m_allocatedTriangleIndexArrays; btAlignedObjectArray<btStridingMeshInterfaceData*> m_allocatedbtStridingMeshInterfaceDatas; btAlignedObjectArray<char*> m_allocatedNames; btAlignedObjectArray<int*> m_indexArrays; btAlignedObjectArray<short int*> m_shortIndexArrays; btAlignedObjectArray<unsigned char*> m_charIndexArrays; btAlignedObjectArray<btVector3FloatData*> m_floatVertexArrays; btAlignedObjectArray<btVector3DoubleData*> m_doubleVertexArrays; btHashMap<btHashPtr,btOptimizedBvh*> m_bvhMap; btHashMap<btHashPtr,btTriangleInfoMap*> m_timMap; btHashMap<btHashString,btCollisionShape*> m_nameShapeMap; btHashMap<btHashString,btRigidBody*> m_nameBodyMap; btHashMap<btHashString,btTypedConstraint*> m_nameConstraintMap; btHashMap<btHashPtr,const char*> m_objectNameMap; btHashMap<btHashPtr,btCollisionShape*> m_shapeMap; btHashMap<btHashPtr,btCollisionObject*> m_bodyMap; //methods static btRigidBody& getFixedBody(); char* duplicateName(const char* name); btCollisionShape* convertCollisionShape( btCollisionShapeData* shapeData ); void convertConstraintBackwardsCompatible281(btTypedConstraintData* constraintData, btRigidBody* rbA, btRigidBody* rbB, int fileVersion); void convertConstraintFloat(btTypedConstraintFloatData* constraintData, btRigidBody* rbA, btRigidBody* rbB, int fileVersion); void convertConstraintDouble(btTypedConstraintDoubleData* constraintData, btRigidBody* rbA, btRigidBody* rbB, int fileVersion); void convertRigidBodyFloat(btRigidBodyFloatData* colObjData); void convertRigidBodyDouble( btRigidBodyDoubleData* colObjData); public: btWorldImporter(btDynamicsWorld* world); virtual ~btWorldImporter(); ///delete all memory collision shapes, rigid bodies, constraints etc. allocated during the load. ///make sure you don't use the dynamics world containing objects after you call this method virtual void deleteAllData(); void setVerboseMode(int verboseMode) { m_verboseMode = verboseMode; } int getVerboseMode() const { return m_verboseMode; } // query for data int getNumCollisionShapes() const; btCollisionShape* getCollisionShapeByIndex(int index); int getNumRigidBodies() const; btCollisionObject* getRigidBodyByIndex(int index) const; int getNumConstraints() const; btTypedConstraint* getConstraintByIndex(int index) const; int getNumBvhs() const; btOptimizedBvh* getBvhByIndex(int index) const; int getNumTriangleInfoMaps() const; btTriangleInfoMap* getTriangleInfoMapByIndex(int index) const; // queris involving named objects btCollisionShape* getCollisionShapeByName(const char* name); btRigidBody* getRigidBodyByName(const char* name); btTypedConstraint* getConstraintByName(const char* name); const char* getNameForPointer(const void* ptr) const; ///those virtuals are called by load and can be overridden by the user virtual void setDynamicsWorldInfo(const btVector3& gravity, const btContactSolverInfo& solverInfo); //bodies virtual btRigidBody* createRigidBody(bool isDynamic, btScalar mass, const btTransform& startTransform, btCollisionShape* shape,const char* bodyName); virtual btCollisionObject* createCollisionObject( const btTransform& startTransform, btCollisionShape* shape,const char* bodyName); ///shapes virtual btCollisionShape* createPlaneShape(const btVector3& planeNormal,btScalar planeConstant); virtual btCollisionShape* createBoxShape(const btVector3& halfExtents); virtual btCollisionShape* createSphereShape(btScalar radius); virtual btCollisionShape* createCapsuleShapeX(btScalar radius, btScalar height); virtual btCollisionShape* createCapsuleShapeY(btScalar radius, btScalar height); virtual btCollisionShape* createCapsuleShapeZ(btScalar radius, btScalar height); virtual btCollisionShape* createCylinderShapeX(btScalar radius,btScalar height); virtual btCollisionShape* createCylinderShapeY(btScalar radius,btScalar height); virtual btCollisionShape* createCylinderShapeZ(btScalar radius,btScalar height); virtual btCollisionShape* createConeShapeX(btScalar radius,btScalar height); virtual btCollisionShape* createConeShapeY(btScalar radius,btScalar height); virtual btCollisionShape* createConeShapeZ(btScalar radius,btScalar height); virtual class btTriangleIndexVertexArray* createTriangleMeshContainer(); virtual btBvhTriangleMeshShape* createBvhTriangleMeshShape(btStridingMeshInterface* trimesh, btOptimizedBvh* bvh); virtual btCollisionShape* createConvexTriangleMeshShape(btStridingMeshInterface* trimesh); virtual btGImpactMeshShape* createGimpactShape(btStridingMeshInterface* trimesh); virtual btStridingMeshInterfaceData* createStridingMeshInterfaceData(btStridingMeshInterfaceData* interfaceData); virtual class btConvexHullShape* createConvexHullShape(); virtual class btCompoundShape* createCompoundShape(); virtual class btScaledBvhTriangleMeshShape* createScaledTrangleMeshShape(btBvhTriangleMeshShape* meshShape,const btVector3& localScalingbtBvhTriangleMeshShape); virtual class btMultiSphereShape* createMultiSphereShape(const btVector3* positions,const btScalar* radi,int numSpheres); virtual btTriangleIndexVertexArray* createMeshInterface(btStridingMeshInterfaceData& meshData); ///acceleration and connectivity structures virtual btOptimizedBvh* createOptimizedBvh(); virtual btTriangleInfoMap* createTriangleInfoMap(); ///constraints virtual btPoint2PointConstraint* createPoint2PointConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB); virtual btPoint2PointConstraint* createPoint2PointConstraint(btRigidBody& rbA,const btVector3& pivotInA); virtual btHingeConstraint* createHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame, const btTransform& rbBFrame, bool useReferenceFrameA=false); virtual btHingeConstraint* createHingeConstraint(btRigidBody& rbA,const btTransform& rbAFrame, bool useReferenceFrameA=false); virtual btConeTwistConstraint* createConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB,const btTransform& rbAFrame, const btTransform& rbBFrame); virtual btConeTwistConstraint* createConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame); virtual btGeneric6DofConstraint* createGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); virtual btGeneric6DofConstraint* createGeneric6DofConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameB); virtual btGeneric6DofSpringConstraint* createGeneric6DofSpringConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); virtual btSliderConstraint* createSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); virtual btSliderConstraint* createSliderConstraint(btRigidBody& rbB, const btTransform& frameInB, bool useLinearReferenceFrameA); virtual btGearConstraint* createGearConstraint(btRigidBody& rbA, btRigidBody& rbB, const btVector3& axisInA,const btVector3& axisInB, btScalar ratio); }; #endif //BT_WORLD_IMPORTER_H
412
0.631017
1
0.631017
game-dev
MEDIA
0.962838
game-dev
0.65646
1
0.65646
opentibiabr/canary
14,016
data-otservbr-global/npc/hjaern.lua
local internalNpcName = "Hjaern" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 154, lookHead = 0, lookBody = 94, lookLegs = 95, lookFeet = 114, lookAddons = 3, } npcConfig.flags = { floorchange = false, } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end local function creatureSayCallback(npc, creature, type, message) local player = Player(creature) local playerId = player:getId() if not npcHandler:checkInteraction(npc, creature) then return false end if MsgContains(message, "mission") then if player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 3 then if player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission02) < 1 then npcHandler:say({ "We could indeed need some help. These are very cold times. The ice is growing and becoming thicker everywhere ...", "The problem is that the chakoyas may use the ice for a passage to the west and attack Svargrond ...", "We need you to get a pick and to destroy the ice at certain places to the east. You will quickly recognise those spots by their unstable look ...", "Use the pickaxe on at least three of these places and the chakoyas probably won't be able to pass the ice. Once you are done, return here and report about your mission.", }, npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission02, 1) -- Questlog The Ice Islands Quest, Nibelor 1: Breaking the Ice npcHandler:setTopic(playerId, 0) end elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 4 then npcHandler:say("The spirits are at peace now. The threat of the chakoyas is averted for now. I thank you for your help. Perhaps you should ask Silfind if you can help her in some matters. ", npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 5) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission02, 5) -- Questlog The Ice Islands Quest, Nibelor 1: Breaking the Ice npcHandler:setTopic(playerId, 0) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 29 then npcHandler:say({ "There is indeed an important mission. For a long time, the spirits have been worried and have called us for help. It seems that some of our dead have not reached the happy hunting grounds of after life ...", "Everything we were able to find out leads to a place where none of our people is allowed to go. Just like we would never allow a stranger to go to that place ...", "But you, you are different. You are not one of our people, yet you have proven worthy to be one us. You are special, the child of two worlds ...", "We will grant you permission to travel to that isle of Helheim. Our legends say that this is the entrance to the dark world. The dark world is the place where the evil and lost souls roam in eternal torment ...", "There you find for sure the cause for the unrest of the spirits. Find someone in Svargrond who can give you a passage to Helheim and seek for the cause. Are you willing to do that?", }, npc, creature) npcHandler:setTopic(playerId, 1) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 31 then npcHandler:say({ "There is no need to report about your mission. To be honest, Ive sent a divination spirit with you as well as a couple of destruction spirits that were unleashed when you approached the altar ...", "Forgive me my secrecy but you are not familiar with the spirits and you might have get frightened. The spirits are at work now, destroying the magic with that those evil creatures have polluted Helheim ...", "I cant thank you enough for what you have done for the spirits of my people. Still I have to ask: Would you do us another favour?", }, npc, creature) npcHandler:setTopic(playerId, 2) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 38 then npcHandler:say({ "These are alarming news and we have to act immediately. Take this spirit charm of cold. Travel to the mines and find four special obelisks to mark them with the charm ...", "I can feel their resonance in the spirits world but we cant reach them with our magic yet. They have to get into contact with us in a spiritual way first ...", "This will help us to concentrate all our frost magic on this place. I am sure this will prevent to melt any significant number of demons from the ice ...", "Report about your mission when you are done. Then we can begin with the great ritual of summoning the children of Chyll ...", "I will also inform Lurik about the events. Now go, fast!", }, npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 39) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission11, 2) -- Questlog The Ice Islands Quest, Formorgar Mines 3: The Secret player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission12, 1) -- Questlog The Ice Islands Quest, Formorgar Mines 4: Retaliation player:addItem(7289, 1) npcHandler:setTopic(playerId, 0) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 39 and player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Obelisk01) == 5 and player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Obelisk02) == 5 and player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Obelisk03) == 5 and player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Obelisk04) == 5 then if player:removeItem(7289, 1) then player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 40) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.yakchalDoor, 1) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission12, 6) -- Questlog The Ice Islands Quest, Formorgar Mines 4: Retaliation player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.NorsemanOutfit, 1) -- Questlog Norseman Outfit Quest player:setStorageValue(Storage.OutfitQuest.DefaultStart, 1) --this for default start of Outfit and Addon Quests player:addOutfit(251, 0) player:addOutfit(252, 0) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) npcHandler:say({ "Yes, I can feel it! The spirits are in touch with the obelisks. We will begin to channel a spell of ice on the caves. That will prevent the melting of the ice there ...", "If you would like to help us, you can turn in frostheart shards from now on. We use them to fuel our spell with the power of ice. ...", "Oh, and before I forget it - since you have done a lot to help us and spent such a long time in this everlasting winter, I have a special present for you. ...", "Take this outfit to keep your warm during your travels in this frozen realm!", }, npc, creature) end npcHandler:setTopic(playerId, 0) else npcHandler:say("I have now no mission for you.", npc, creature) npcHandler:setTopic(playerId, 0) end elseif MsgContains(message, "shard") then if player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 40 then npcHandler:say("Do you bring frostheart shards for our spell?", npc, creature) npcHandler:setTopic(playerId, 3) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 42 then npcHandler:say("Do you bring frostheart shards for our spell? ", npc, creature) npcHandler:setTopic(playerId, 4) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 44 then npcHandler:say("Do you want to sell all your shards for 2000 gold coins per each? ", npc, creature) npcHandler:setTopic(playerId, 5) end elseif MsgContains(message, "reward") then if player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 41 then npcHandler:say("Take this. It might suit your Nordic outfit fine. ", npc, creature) player:addOutfitAddon(252, 1) player:addOutfitAddon(251, 1) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 42) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.NorsemanOutfit, 2) -- Questlog Norseman Outfit Quest npcHandler:setTopic(playerId, 3) elseif player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 43 then player:addOutfitAddon(252, 2) player:addOutfitAddon(251, 2) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) npcHandler:say("Take this. It might suit your Nordic outfit fine. From now on we only can give you 2000 gold pieces for each shard. ", npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 44) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.NorsemanOutfit, 3) -- Questlog Norseman Outfit Quest npcHandler:setTopic(playerId, 4) end elseif MsgContains(message, "tylaf") then if player:getStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline) == 36 then npcHandler:say({ "You encountered the restless ghost of my apprentice Tylaf in the old mines? We must find out what has happened to him. I enable you to talk to his spirit ...", "Talk to him and then report to me about your mission.", }, npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 37) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission10, 1) -- Questlog The Ice Islands Quest, Formorgar Mines 2: Ghostwhisperer npcHandler:setTopic(playerId, 0) end elseif MsgContains(message, "cookie") then if player:getStorageValue(Storage.Quest.U8_1.WhatAFoolishQuest.Questline) == 31 and player:getStorageValue(Storage.Quest.U8_1.WhatAFoolishQuest.CookieDelivery.Hjaern) ~= 1 then npcHandler:say("You want to sacrifice a cookie to the spirits?", npc, creature) npcHandler:setTopic(playerId, 6) end elseif MsgContains(message, "yes") then if npcHandler:getTopic(playerId) == 1 then npcHandler:say("This is good news. As I explained, travel to Helheim, seek the reason for the unrest there and then report to me about your mission. ", npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 30) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission07, 2) -- Questlog The Ice Islands Quest, The Secret of Helheim npcHandler:setTopic(playerId, 0) elseif npcHandler:getTopic(playerId) == 2 then npcHandler:say({ "Thank you my friend. The local representative of the explorers society has asked for our help ...", "You know their ways better than my people do and are probably best suited to represent us in this matter.", "Search for Lurik and talk to him about aprobable mission he might have for you.", }, npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 32) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Mission08, 1) -- Questlog The Ice Islands Quest, The Contact npcHandler:setTopic(playerId, 0) elseif npcHandler:getTopic(playerId) == 3 then if player:removeItem(7290, 5) then npcHandler:say("Excellent, you collected 5 of them. If you have collected 5 or more, talk to me about your {reward}. ", npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 41) npcHandler:setTopic(playerId, 0) end elseif npcHandler:getTopic(playerId) == 4 then if player:removeItem(7290, 10) then npcHandler:say("Excellent, you collected 10 of them. If you have collected 15 or more, talk to me about your {reward}. ", npc, creature) player:setStorageValue(Storage.Quest.U8_0.TheIceIslands.Questline, 43) npcHandler:setTopic(playerId, 0) end elseif npcHandler:getTopic(playerId) == 5 then if player:getItemCount(7290) > 0 then local count = player:getItemCount(7290) player:addMoney(count * 2000) player:removeItem(7290, count) npcHandler:say("Here your are. " .. count * 2000 .. " gold coins for " .. count .. " shards.", npc, creature) npcHandler:setTopic(playerId, 0) end elseif npcHandler:getTopic(playerId) == 6 then if not player:removeItem(130, 1) then npcHandler:say("You have no cookie that I'd like.", npc, creature) npcHandler:setTopic(playerId, 0) return true end player:setStorageValue(Storage.Quest.U8_1.WhatAFoolishQuest.CookieDelivery.Hjaern, 1) if player:getCookiesDelivered() == 10 then player:addAchievement("Allow Cookies?") end npc:getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS) npcHandler:say("In the name of the spirits I accept this offer ... UHNGH ... The spirits are not amused!", npc, creature) npcHandler:removeInteraction(npc, creature) npcHandler:resetNpc(creature) end elseif MsgContains(message, "no") then if npcHandler:getTopic(playerId) == 6 then npcHandler:say("I see.", npc, creature) npcHandler:setTopic(playerId, 0) end end return true end npcHandler:setMessage(MESSAGE_GREET, "Be greeted, |PLAYERNAME|. The {spiritual} world looks upon you and your deeds.") npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) -- npcType registering the npcConfig table npcType:register(npcConfig)
412
0.939683
1
0.939683
game-dev
MEDIA
0.912279
game-dev
0.955429
1
0.955429
harfang3d/harfang3d
9,563
extern/bullet3/BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h
/*! \file btGImpactShape.h \author Francisco Leon Najera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H #define BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H #include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "LinearMath/btAlignedObjectArray.h" #include "btGImpactShape.h" #include "BulletCollision/CollisionShapes/btStaticPlaneShape.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" //! Collision Algorithm for GImpact Shapes /*! For register this algorithm in Bullet, proceed as following: \code btCollisionDispatcher * dispatcher = static_cast<btCollisionDispatcher *>(m_dynamicsWorld ->getDispatcher()); btGImpactCollisionAlgorithm::registerAlgorithm(dispatcher); \endcode */ class btGImpactCollisionAlgorithm : public btActivatingCollisionAlgorithm { protected: btCollisionAlgorithm* m_convex_algorithm; btPersistentManifold* m_manifoldPtr; btManifoldResult* m_resultOut; const btDispatcherInfo* m_dispatchInfo; int m_triface0; int m_part0; int m_triface1; int m_part1; //! Creates a new contact point SIMD_FORCE_INLINE btPersistentManifold* newContactManifold(const btCollisionObject* body0, const btCollisionObject* body1) { m_manifoldPtr = m_dispatcher->getNewManifold(body0, body1); return m_manifoldPtr; } SIMD_FORCE_INLINE void destroyConvexAlgorithm() { if (m_convex_algorithm) { m_convex_algorithm->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm(m_convex_algorithm); m_convex_algorithm = NULL; } } SIMD_FORCE_INLINE void destroyContactManifolds() { if (m_manifoldPtr == NULL) return; m_dispatcher->releaseManifold(m_manifoldPtr); m_manifoldPtr = NULL; } SIMD_FORCE_INLINE void clearCache() { destroyContactManifolds(); destroyConvexAlgorithm(); m_triface0 = -1; m_part0 = -1; m_triface1 = -1; m_part1 = -1; } SIMD_FORCE_INLINE btPersistentManifold* getLastManifold() { return m_manifoldPtr; } // Call before process collision SIMD_FORCE_INLINE void checkManifold(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap) { if (getLastManifold() == 0) { newContactManifold(body0Wrap->getCollisionObject(), body1Wrap->getCollisionObject()); } m_resultOut->setPersistentManifold(getLastManifold()); } // Call before process collision SIMD_FORCE_INLINE btCollisionAlgorithm* newAlgorithm(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap) { checkManifold(body0Wrap, body1Wrap); btCollisionAlgorithm* convex_algorithm = m_dispatcher->findAlgorithm( body0Wrap, body1Wrap, getLastManifold(), BT_CONTACT_POINT_ALGORITHMS); return convex_algorithm; } // Call before process collision SIMD_FORCE_INLINE void checkConvexAlgorithm(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap) { if (m_convex_algorithm) return; m_convex_algorithm = newAlgorithm(body0Wrap, body1Wrap); } void addContactPoint(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btVector3& point, const btVector3& normal, btScalar distance); //! Collision routines //!@{ void collide_gjk_triangles(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactMeshShapePart* shape0, const btGImpactMeshShapePart* shape1, const int* pairs, int pair_count); void collide_sat_triangles(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactMeshShapePart* shape0, const btGImpactMeshShapePart* shape1, const int* pairs, int pair_count); void shape_vs_shape_collision( const btCollisionObjectWrapper* body0, const btCollisionObjectWrapper* body1, const btCollisionShape* shape0, const btCollisionShape* shape1); void convex_vs_convex_collision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btCollisionShape* shape0, const btCollisionShape* shape1); void gimpact_vs_gimpact_find_pairs( const btTransform& trans0, const btTransform& trans1, const btGImpactShapeInterface* shape0, const btGImpactShapeInterface* shape1, btPairSet& pairset); void gimpact_vs_shape_find_pairs( const btTransform& trans0, const btTransform& trans1, const btGImpactShapeInterface* shape0, const btCollisionShape* shape1, btAlignedObjectArray<int>& collided_primitives); void gimpacttrimeshpart_vs_plane_collision( const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactMeshShapePart* shape0, const btStaticPlaneShape* shape1, bool swapped); public: btGImpactCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap); virtual ~btGImpactCollisionAlgorithm(); virtual void processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { if (m_manifoldPtr) manifoldArray.push_back(m_manifoldPtr); } btManifoldResult* internalGetResultOut() { return m_resultOut; } struct CreateFunc : public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btGImpactCollisionAlgorithm)); return new (mem) btGImpactCollisionAlgorithm(ci, body0Wrap, body1Wrap); } }; //! Use this function for register the algorithm externally static void registerAlgorithm(btCollisionDispatcher* dispatcher); #ifdef TRI_COLLISION_PROFILING //! Gets the average time in miliseconds of tree collisions static float getAverageTreeCollisionTime(); //! Gets the average time in miliseconds of triangle collisions static float getAverageTriangleCollisionTime(); #endif //TRI_COLLISION_PROFILING //! Collides two gimpact shapes /*! \pre shape0 and shape1 couldn't be btGImpactMeshShape objects */ void gimpact_vs_gimpact(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactShapeInterface* shape0, const btGImpactShapeInterface* shape1); void gimpact_vs_shape(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactShapeInterface* shape0, const btCollisionShape* shape1, bool swapped); void gimpact_vs_compoundshape(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactShapeInterface* shape0, const btCompoundShape* shape1, bool swapped); void gimpact_vs_concave( const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btGImpactShapeInterface* shape0, const btConcaveShape* shape1, bool swapped); /// Accessor/Mutator pairs for Part and triangleID void setFace0(int value) { m_triface0 = value; } int getFace0() { return m_triface0; } void setFace1(int value) { m_triface1 = value; } int getFace1() { return m_triface1; } void setPart0(int value) { m_part0 = value; } int getPart0() { return m_part0; } void setPart1(int value) { m_part1 = value; } int getPart1() { return m_part1; } }; //algorithm details //#define BULLET_TRIANGLE_COLLISION 1 #define GIMPACT_VS_PLANE_COLLISION 1 #endif //BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H
412
0.958467
1
0.958467
game-dev
MEDIA
0.979355
game-dev
0.876781
1
0.876781
PSAppDeployToolkit/PSAppDeployToolkit
18,965
lib/iNKORE.UI.WPF.Modern/source/iNKORE.UI.WPF.Modern.Controls/Controls/Windows/PersonPicture/InitialsGenerator.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Linq; using iNKORE.UI.WPF.Modern.Common; namespace iNKORE.UI.WPF.Modern.Controls { /// <summary> /// Value indicating the general character set for a given character. /// </summary> enum CharacterType { /// <summary> /// Indicates we could not match the character set. /// </summary> Other = 0, /// <summary> /// Member of the Latin character set. /// </summary> Standard = 1, /// <summary> /// Member of a symbolic character set. /// </summary> Symbolic = 2, /// <summary> /// Member of a character set which supports glyphs. /// </summary> Glyph = 3 }; /// <summary> /// PersonPicture Control. Displays the Profile Picture, or in its absence Initials, /// for a given Contact. /// </summary> class InitialsGenerator { /// <summary> /// Helper function which takes a DisplayName, as generated by /// Windows.ApplicationModel.Contacts, and returns a initials representation. /// </summary> /// <param name="contactDisplayName">The DisplayName of the person</param> /// <returns> /// String containing the initials representation of the given DisplayName. /// </returns> public static string InitialsFromDisplayName(string contactDisplayName) { CharacterType type = GetCharacterType(contactDisplayName); // We'll attempt to make initials only if we recognize a name in the Standard character set. if (type == CharacterType.Standard) { string displayName = contactDisplayName; StripTrailingBrackets(ref displayName); string[] words = Split(displayName, ' '); if (words.Length == 1) { // If there's only a single long word, we'll show one initial. string firstWord = words.First(); string result = GetFirstFullCharacter(firstWord); return result.ToUpper(); } else if (words.Length > 1) { // If there's at least two words, we'll show two initials. // // NOTE: Based on current implementation, we could be showing punctuation. // For example, "John -Smith" would be "J-". string firstWord = words.First(); string lastWord = words.Last(); string result = GetFirstFullCharacter(firstWord); result += GetFirstFullCharacter(lastWord); return result.ToUpper(); } else { // If there's only spaces in the name, we'll get a Vector size of 0. return string.Empty; } } else { // Return empty string. In our code-behind we will produce a generic glyph as a result. return string.Empty; } } /// <summary> /// Helper function which indicates the type of characters in a given string /// </summary> /// <param name="str">String from which to detect character-set.</param> /// <returns> /// Character set of the string: Latin, Symbolic, Glyph, or other. /// </returns> public static CharacterType GetCharacterType(string str) { // Since we're doing initials, we're really only interested in the first // few characters. If the first three characters aren't a glyph then // we don't need to count it as such because we won't be changing meaning // by truncating to one or two. CharacterType result = CharacterType.Other; for (int i = 0; i < 3; i++) { // Break on null character. 0xFEFF is a terminating character which appears as null. if ((i >= str.Length) || (str[i] == '\0') || (str[i] == 0xFEFF)) { break; } char character = str[i]; CharacterType evaluationResult = GetCharacterType(character); // In mix-match scenarios, we'll want to follow this order of precedence: // Glyph > Symbolic > Roman switch (evaluationResult) { case CharacterType.Glyph: result = CharacterType.Glyph; break; case CharacterType.Symbolic: // Don't override a Glyph state with a Symbolic State. if (result != CharacterType.Glyph) { result = CharacterType.Symbolic; } break; case CharacterType.Standard: // Don't override a Glyph or Symbolic state with a Latin state. if ((result != CharacterType.Glyph) && (result != CharacterType.Symbolic)) { result = CharacterType.Standard; } break; default: // Preserve result's current state (if we never got data other // than "Other", it'll be set to other anyway). break; } } return result; } /// <summary> /// Helper function which indicates the character-set of a given character. /// </summary> /// <param name="character">Character for which to detect character-set.</param> /// <returns> /// Character set of the string: Latin, Symbolic, Glyph, or other. /// </returns> public static CharacterType GetCharacterType(char character) { // To ensure predictable behavior, we're currently operating on an allowed list of character sets. // // Each block below is a HEX range in the official Unicode spec, which defines a set // of Unicode characters. Changes to the character sets would only be made by Unicode, and // are highly unlikely (as it would break virtually every modern text parser). // Definitions available here: http://www.unicode.org/charts/ // // GLYPH // // IPA Extensions if ((character >= 0x0250) && (character <= 0x02AF)) { return CharacterType.Glyph; } // Arabic if ((character >= 0x0600) && (character <= 0x06FF)) { return CharacterType.Glyph; } // Arabic Supplement if ((character >= 0x0750) && (character <= 0x077F)) { return CharacterType.Glyph; } // Arabic Extended-A if ((character >= 0x08A0) && (character <= 0x08FF)) { return CharacterType.Glyph; } // Arabic Presentation Forms-A if ((character >= 0xFB50) && (character <= 0xFDFF)) { return CharacterType.Glyph; } // Arabic Presentation Forms-B if ((character >= 0xFE70) && (character <= 0xFEFF)) { return CharacterType.Glyph; } // Devanagari if ((character >= 0x0900) && (character <= 0x097F)) { return CharacterType.Glyph; } // Devanagari Extended if ((character >= 0xA8E0) && (character <= 0xA8FF)) { return CharacterType.Glyph; } // Bengali if ((character >= 0x0980) && (character <= 0x09FF)) { return CharacterType.Glyph; } // Gurmukhi if ((character >= 0x0A00) && (character <= 0x0A7F)) { return CharacterType.Glyph; } // Gujarati if ((character >= 0x0A80) && (character <= 0x0AFF)) { return CharacterType.Glyph; } // Oriya if ((character >= 0x0B00) && (character <= 0x0B7F)) { return CharacterType.Glyph; } // Tamil if ((character >= 0x0B80) && (character <= 0x0BFF)) { return CharacterType.Glyph; } // Telugu if ((character >= 0x0C00) && (character <= 0x0C7F)) { return CharacterType.Glyph; } // Kannada if ((character >= 0x0C80) && (character <= 0x0CFF)) { return CharacterType.Glyph; } // Malayalam if ((character >= 0x0D00) && (character <= 0x0D7F)) { return CharacterType.Glyph; } // Sinhala if ((character >= 0x0D80) && (character <= 0x0DFF)) { return CharacterType.Glyph; } // Thai if ((character >= 0x0E00) && (character <= 0x0E7F)) { return CharacterType.Glyph; } // Lao if ((character >= 0x0E80) && (character <= 0x0EFF)) { return CharacterType.Glyph; } // SYMBOLIC // // CJK Unified Ideographs if ((character >= 0x4E00) && (character <= 0x9FFF)) { return CharacterType.Symbolic; } // CJK Unified Ideographs Extension if ((character >= 0x3400) && (character <= 0x4DBF)) { return CharacterType.Symbolic; } // CJK Unified Ideographs Extension B if ((character >= 0x20000) && (character <= 0x2A6DF)) { return CharacterType.Symbolic; } // CJK Unified Ideographs Extension C if ((character >= 0x2A700) && (character <= 0x2B73F)) { return CharacterType.Symbolic; } // CJK Unified Ideographs Extension D if ((character >= 0x2B740) && (character <= 0x2B81F)) { return CharacterType.Symbolic; } // CJK Radicals Supplement if ((character >= 0x2E80) && (character <= 0x2EFF)) { return CharacterType.Symbolic; } // CJK Symbols and Punctuation if ((character >= 0x3000) && (character <= 0x303F)) { return CharacterType.Symbolic; } // CJK Strokes if ((character >= 0x31C0) && (character <= 0x31EF)) { return CharacterType.Symbolic; } // Enclosed CJK Letters and Months if ((character >= 0x3200) && (character <= 0x32FF)) { return CharacterType.Symbolic; } // CJK Compatibility if ((character >= 0x3300) && (character <= 0x33FF)) { return CharacterType.Symbolic; } // CJK Compatibility Ideographs if ((character >= 0xF900) && (character <= 0xFAFF)) { return CharacterType.Symbolic; } // CJK Compatibility Forms if ((character >= 0xFE30) && (character <= 0xFE4F)) { return CharacterType.Symbolic; } // CJK Compatibility Ideographs Supplement if ((character >= 0x2F800) && (character <= 0x2FA1F)) { return CharacterType.Symbolic; } // Greek and Coptic if ((character >= 0x0370) && (character <= 0x03FF)) { return CharacterType.Symbolic; } // Hebrew if ((character >= 0x0590) && (character <= 0x05FF)) { return CharacterType.Symbolic; } // Armenian if ((character >= 0x0530) && (character <= 0x058F)) { return CharacterType.Symbolic; } // LATIN // // Basic Latin if ((character > 0x0000) && (character <= 0x007F)) { return CharacterType.Standard; } // Latin-1 Supplement if ((character >= 0x0080) && (character <= 0x00FF)) { return CharacterType.Standard; } // Latin Extended-A if ((character >= 0x0100) && (character <= 0x017F)) { return CharacterType.Standard; } // Latin Extended-B if ((character >= 0x0180) && (character <= 0x024F)) { return CharacterType.Standard; } // Latin Extended-C if ((character >= 0x2C60) && (character <= 0x2C7F)) { return CharacterType.Standard; } // Latin Extended-D if ((character >= 0xA720) && (character <= 0xA7FF)) { return CharacterType.Standard; } // Latin Extended-E if ((character >= 0xAB30) && (character <= 0xAB6F)) { return CharacterType.Standard; } // Latin Extended Additional if ((character >= 0x1E00) && (character <= 0x1EFF)) { return CharacterType.Standard; } // Cyrillic if ((character >= 0x0400) && (character <= 0x04FF)) { return CharacterType.Standard; } // Cyrillic Supplement if ((character >= 0x0500) && (character <= 0x052F)) { return CharacterType.Standard; } // Combining Diacritical Marks if ((character >= 0x0300) && (character <= 0x036F)) { return CharacterType.Standard; } return CharacterType.Other; } /// <summary> /// Helper function which takes in a string and returns a vector of pieces, separated by delimiter. /// </summary> /// <param name="source">String on which to perform the split operation.</param> /// <param name="delim">String on which to perform the split operation.</param> /// <param name="maxIterations">Maximum number of times to perform a <code>getline</code> loop.</param> /// <returns>A vector of pieces from the source string, separated by delimiter</returns> static string[] Split(string source, char delim, int maxIterations = 25) { return source.Split(new[] { delim }, maxIterations); } /// <summary> /// Helper function to remove bracket qualifier from the end of a display name if present. /// </summary> /// <param name="source">String on which to perform the operation.</param> /// <returns>A string with the content within brackets removed.</returns> static void StripTrailingBrackets(ref string source) { // Guidance from the world readiness team is that text within a final set of brackets // can be removed for the purposes of calculating initials. ex. John Smith (OSG) string[] delimiters = { "{}", "()", "[]" }; if (source.Length == 0) { return; } foreach (var delimiter in delimiters) { if (source[source.Length - 1] != delimiter[1]) { continue; } var start = source.LastIndexOf(delimiter[0]); if (start == -1) { continue; } source = source.Remove(start); return; } } /// <summary> /// Extracts the first full character from a given string, including any diacritics or combining characters. /// </summary> /// <param name="str">String from which to extract the character.</param> /// <returns>A wstring which represents a given character.</returns> static string GetFirstFullCharacter(string str) { // Index should begin at the first desireable character. int start = 0; while (start < str.Length) { char character = str[start]; // Omit ! " # $ % & ' ( ) * + , - . / if ((character >= 0x0021) && (character <= 0x002F)) { start++; continue; } // Omit : ; < = > ? @ if ((character >= 0x003A) && (character <= 0x0040)) { start++; continue; } // Omit { | } ~ if ((character >= 0x007B) && (character <= 0x007E)) { start++; continue; } break; } // If no desireable characters exist, we'll start at index 1, as combining // characters begin only after the first character. if (start >= str.Length) { start = 0; } // Combining characters begin only after the first character, so we should start // looking 1 after the start character. int index = start + 1; while (index < str.Length) { char character = str[index]; // Combining Diacritical Marks -- Official Unicode character block if ((character < 0x0300) || (character > 0x036F)) { break; } index++; } // Determine number of diacritics by adjusting for our initial offset. int strLength = index - start; string result = str.SafeSubstring(start, strLength); return result; } }; }
412
0.825955
1
0.825955
game-dev
MEDIA
0.386624
game-dev
0.905411
1
0.905411
AdaEngine/AdaEngine
3,997
Modules/box2d/include/box2d/id.h
// SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "base.h" #include <stdint.h> /** * @defgroup id Ids * These ids serve as handles to internal Box2D objects. * These should be considered opaque data and passed by value. * Include this header if you need the id types and not the whole Box2D API. * All ids are considered null if initialized to zero. * * For example in C++: * * @code{.cxx} * b2WorldId worldId = {}; * @endcode * * Or in C: * * @code{.c} * b2WorldId worldId = {0}; * @endcode * * These are both considered null. * * @warning Do not use the internals of these ids. They are subject to change. Ids should be treated as opaque objects. * @warning You should use ids to access objects in Box2D. Do not access files within the src folder. Such usage is unsupported. * @{ */ /// World id references a world instance. This should be treated as an opaque handle. typedef struct b2WorldId { uint16_t index1; uint16_t generation; } b2WorldId; /// Body id references a body instance. This should be treated as an opaque handle. typedef struct b2BodyId { int32_t index1; uint16_t world0; uint16_t generation; } b2BodyId; /// Shape id references a shape instance. This should be treated as an opaque handle. typedef struct b2ShapeId { int32_t index1; uint16_t world0; uint16_t generation; } b2ShapeId; /// Chain id references a chain instances. This should be treated as an opaque handle. typedef struct b2ChainId { int32_t index1; uint16_t world0; uint16_t generation; } b2ChainId; /// Joint id references a joint instance. This should be treated as an opaque handle. typedef struct b2JointId { int32_t index1; uint16_t world0; uint16_t generation; } b2JointId; /// Use these to make your identifiers null. /// You may also use zero initialization to get null. static const b2WorldId b2_nullWorldId = B2_ZERO_INIT; static const b2BodyId b2_nullBodyId = B2_ZERO_INIT; static const b2ShapeId b2_nullShapeId = B2_ZERO_INIT; static const b2ChainId b2_nullChainId = B2_ZERO_INIT; static const b2JointId b2_nullJointId = B2_ZERO_INIT; /// Macro to determine if any id is null. #define B2_IS_NULL( id ) ( id.index1 == 0 ) /// Macro to determine if any id is non-null. #define B2_IS_NON_NULL( id ) ( id.index1 != 0 ) /// Compare two ids for equality. Doesn't work for b2WorldId. #define B2_ID_EQUALS( id1, id2 ) ( id1.index1 == id2.index1 && id1.world0 == id2.world0 && id1.generation == id2.generation ) /// Store a body id into a uint64_t. B2_INLINE uint64_t b2StoreBodyId( b2BodyId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a body id. B2_INLINE b2BodyId b2LoadBodyId( uint64_t x ) { b2BodyId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a shape id into a uint64_t. B2_INLINE uint64_t b2StoreShapeId( b2ShapeId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a shape id. B2_INLINE b2ShapeId b2LoadShapeId( uint64_t x ) { b2ShapeId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a chain id into a uint64_t. B2_INLINE uint64_t b2StoreChainId( b2ChainId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a chain id. B2_INLINE b2ChainId b2LoadChainId( uint64_t x ) { b2ChainId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /// Store a joint id into a uint64_t. B2_INLINE uint64_t b2StoreJointId( b2JointId id ) { return ( (uint64_t)id.index1 << 32 ) | ( (uint64_t)id.world0 ) << 16 | (uint64_t)id.generation; } /// Load a uint64_t into a joint id. B2_INLINE b2JointId b2LoadJointId( uint64_t x ) { b2JointId id = { (int32_t)( x >> 32 ), (uint16_t)( x >> 16 ), (uint16_t)( x ) }; return id; } /**@}*/
412
0.905447
1
0.905447
game-dev
MEDIA
0.504112
game-dev
0.568893
1
0.568893
sculove/xing-plus
1,617
xing/res/t1964_2.res
BEGIN_FUNCTION_MAP .Func,ELW(t1964),t1964,attr,block,headtype=A; BEGIN_DATA_MAP t1964InBlock,⺻Է,input; begin ڻڵ,item,item,char,12; ,issuercd,issuercd,char,12; ,lastmonth,lastmonth,char,6; Dz,elwopt,elwopt,char,1; Ӵϱ,atmgubun,atmgubun,char,1; Ǹ,elwtype,elwtype,char,2; ,settletype,settletype,char,2; ڻ걸,elwexecgubun,elwexecgubun,char,1; ۺ,fromrat,fromrat,char,5; ,torat,torat,char,5; ŷ,volume,volume,char,12; end t1964OutBlock1,1,output,occurs; begin ELWڵ,shcode,shcode,char,6; ,hname,hname,char,40; ڻڵ,item1,item1,char,6; ڻ,itemnm,itemnm,char,20; ,issuernmk,issuernmk,char,40; Dz,elwopt,elwopt,char,4; 簡,price,price,long,8; ϴ񱸺,sign,sign,char,1; ϴ,change,change,long,8; ,diff,diff,float,6.2; ŷ,volume,volume,long,12; 簡,elwexec,elwexec,float,10.2; ϼ,jandatecnt,jandatecnt,long,8; ȯ,convrate,convrate,float,8.4; ŷ,lastdate,lastdate,char,8; 簳,mmsdate,mmsdate,char,8; ,payday,payday,char,8; ,listing,listing,long,8; Ӵϱ,atmgbnm,atmgbnm,char,10; иƼ,parity,parity,float,6.2; ̾,preminum,preminum,float,10.2; ,spread,spread,float,3.2; ͺб,berate,berate,float,6.2; ں,capt,capt,float,6.2; ,gearing,gearing,float,6.2; e,egearing,egearing,float,6.2; ڻ簡,itemprice,itemprice,long,8; ڻϴ񱸺,itemsign,itemsign,char,1; ڻϴ,itemchange,itemchange,long,8; ڻ,itemdiff,itemdiff,float,6.2; ڻŷ,itemvolume,itemvolume,long,12; ϰŷ,jnilvolume,jnilvolume,long,12; ̷а,theoryprice,theoryprice,float,10.2; LP,lp_rate,lp_rate,float,5.2; 纯,impv,impv,float,6.2; Ÿ,delta,delta,float,10.6; Ÿ,theta,theta,float,10.6; end END_DATA_MAP END_FUNCTION_MAP t1964
412
0.741667
1
0.741667
game-dev
MEDIA
0.352033
game-dev
0.863357
1
0.863357
stride3d/stride
4,794
sources/engine/Stride.Physics.Tests/CharacterTest.cs
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Linq; using System.Collections.Generic; using Xunit; using Stride.Core.Mathematics; using Stride.Engine; namespace Stride.Physics.Tests { public class CharacterTest : GameTest { public CharacterTest() : base("CharacterTest") { } public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation) { var invViewProj = Matrix.Invert(camera.ViewProjectionMatrix); Vector3 sPos; sPos.X = screenPos.X * 2f - 1f; sPos.Y = 1f - screenPos.Y * 2f; sPos.Z = 0f; var vectorNear = Vector3.Transform(sPos, invViewProj); vectorNear /= vectorNear.W; sPos.Z = 1f; var vectorFar = Vector3.Transform(sPos, invViewProj); vectorFar /= vectorFar.W; var result = new List<HitResult>(); simulation.RaycastPenetrating(vectorNear.XYZ(), vectorFar.XYZ(), result); foreach (var hitResult in result) { if (hitResult.Succeeded) { return true; } } return false; } [Fact] public void CharacterTest1() { var game = new CharacterTest(); game.Script.AddTask(async () => { game.ScreenShotAutomationEnabled = false; await game.Script.NextFrame(); await game.Script.NextFrame(); var character = game.SceneSystem.SceneInstance.RootScene.Entities.First(ent => ent.Name == "Character"); var controller = character.Get<CharacterComponent>(); var simulation = controller.Simulation; //let the controller land var twoSeconds = 120; while (twoSeconds-- > 0) { await game.Script.NextFrame(); } Assert.True(controller.IsGrounded); controller.Jump(); await game.Script.NextFrame(); Assert.False(controller.IsGrounded); //let the controller land twoSeconds = 120; while (twoSeconds-- > 0) { await game.Script.NextFrame(); } Assert.True(controller.IsGrounded); var currentPos = character.Transform.Position; controller.SetVelocity(Vector3.UnitX * 3); await game.Script.NextFrame(); Assert.NotEqual(currentPos, character.Transform.Position); var target = currentPos + Vector3.UnitX*3*simulation.FixedTimeStep; Assert.Equal(character.Transform.Position.X, target.X, 15f); Assert.Equal(character.Transform.Position.Y, target.Y, 15f); Assert.Equal(character.Transform.Position.Z, target.Z, 15f); currentPos = character.Transform.Position; await game.Script.NextFrame(); Assert.NotEqual(currentPos, character.Transform.Position); target = currentPos + Vector3.UnitX * 3 * simulation.FixedTimeStep; Assert.Equal(character.Transform.Position.X, target.X, 15f); Assert.Equal(character.Transform.Position.Y, target.Y, 15f); Assert.Equal(character.Transform.Position.Z, target.Z, 15f); controller.SetVelocity(Vector3.Zero); await game.Script.NextFrame(); currentPos = character.Transform.Position; await game.Script.NextFrame(); Assert.Equal(currentPos, character.Transform.Position); var collider = game.SceneSystem.SceneInstance.RootScene.Entities.First(ent => ent.Name == "Collider").Get<StaticColliderComponent>(); game.Script.AddTask(async () => { var fourSeconds = 240; while (fourSeconds-- > 0) { await game.Script.NextFrame(); } Assert.Fail("Character controller never collided with test collider."); }); controller.SetVelocity(Vector3.UnitX * 2.5f); await collider.NewCollision(); game.Exit(); }); RunGameTest(game); } } }
412
0.877508
1
0.877508
game-dev
MEDIA
0.724982
game-dev,testing-qa,graphics-rendering
0.899152
1
0.899152
midibox/mios32
10,728
apps/synthesizers/midibox_sid_v3/juce/JuceLibraryCode/modules/juce_gui_basics/layout/juce_ComponentAnimator.cpp
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ class ComponentAnimator::AnimationTask { public: AnimationTask (Component* const comp) : component (comp) { } void reset (const Rectangle<int>& finalBounds, float finalAlpha, int millisecondsToSpendMoving, bool useProxyComponent, double startSpeed_, double endSpeed_) { msElapsed = 0; msTotal = jmax (1, millisecondsToSpendMoving); lastProgress = 0; destination = finalBounds; destAlpha = finalAlpha; isMoving = (finalBounds != component->getBounds()); isChangingAlpha = (finalAlpha != component->getAlpha()); left = component->getX(); top = component->getY(); right = component->getRight(); bottom = component->getBottom(); alpha = component->getAlpha(); const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0); startSpeed = jmax (0.0, startSpeed_ * invTotalDistance); midSpeed = invTotalDistance; endSpeed = jmax (0.0, endSpeed_ * invTotalDistance); if (useProxyComponent) proxy = new ProxyComponent (*component); else proxy = nullptr; component->setVisible (! useProxyComponent); } bool useTimeslice (const int elapsed) { if (Component* const c = proxy != nullptr ? static_cast <Component*> (proxy) : static_cast <Component*> (component)) { msElapsed += elapsed; double newProgress = msElapsed / (double) msTotal; if (newProgress >= 0 && newProgress < 1.0) { newProgress = timeToDistance (newProgress); const double delta = (newProgress - lastProgress) / (1.0 - lastProgress); jassert (newProgress >= lastProgress); lastProgress = newProgress; if (delta < 1.0) { bool stillBusy = false; if (isMoving) { left += (destination.getX() - left) * delta; top += (destination.getY() - top) * delta; right += (destination.getRight() - right) * delta; bottom += (destination.getBottom() - bottom) * delta; const Rectangle<int> newBounds (roundToInt (left), roundToInt (top), roundToInt (right - left), roundToInt (bottom - top)); if (newBounds != destination) { c->setBounds (newBounds); stillBusy = true; } } if (isChangingAlpha) { alpha += (destAlpha - alpha) * delta; c->setAlpha ((float) alpha); stillBusy = true; } if (stillBusy) return true; } } } moveToFinalDestination(); return false; } void moveToFinalDestination() { if (component != nullptr) { component->setAlpha ((float) destAlpha); component->setBounds (destination); if (proxy != nullptr) component->setVisible (destAlpha > 0); } } //============================================================================== class ProxyComponent : public Component { public: ProxyComponent (Component& c) { setWantsKeyboardFocus (false); setBounds (c.getBounds()); setTransform (c.getTransform()); setAlpha (c.getAlpha()); setInterceptsMouseClicks (false, false); if (Component* const parent = c.getParentComponent()) parent->addAndMakeVisible (this); else if (c.isOnDesktop() && c.getPeer() != nullptr) addToDesktop (c.getPeer()->getStyleFlags() | ComponentPeer::windowIgnoresKeyPresses); else jassertfalse; // seem to be trying to animate a component that's not visible.. image = c.createComponentSnapshot (c.getLocalBounds(), false, getDesktopScaleFactor()); setVisible (true); toBehind (&c); } void paint (Graphics& g) override { g.setOpacity (1.0f); g.drawImageTransformed (image, AffineTransform::scale (getWidth() / (float) image.getWidth(), getHeight() / (float) image.getHeight()), false); } private: Image image; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent) }; WeakReference<Component> component; ScopedPointer<Component> proxy; Rectangle<int> destination; double destAlpha; int msElapsed, msTotal; double startSpeed, midSpeed, endSpeed, lastProgress; double left, top, right, bottom, alpha; bool isMoving, isChangingAlpha; private: double timeToDistance (const double time) const noexcept { return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed)) : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed)) + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed)); } }; //============================================================================== ComponentAnimator::ComponentAnimator() : lastTime (0) { } ComponentAnimator::~ComponentAnimator() { } //============================================================================== ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const noexcept { for (int i = tasks.size(); --i >= 0;) if (component == tasks.getUnchecked(i)->component.get()) return tasks.getUnchecked(i); return nullptr; } void ComponentAnimator::animateComponent (Component* const component, const Rectangle<int>& finalBounds, const float finalAlpha, const int millisecondsToSpendMoving, const bool useProxyComponent, const double startSpeed, const double endSpeed) { // the speeds must be 0 or greater! jassert (startSpeed >= 0 && endSpeed >= 0) if (component != nullptr) { AnimationTask* at = findTaskFor (component); if (at == nullptr) { at = new AnimationTask (component); tasks.add (at); sendChangeMessage(); } at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving, useProxyComponent, startSpeed, endSpeed); if (! isTimerRunning()) { lastTime = Time::getMillisecondCounter(); startTimer (1000 / 50); } } } void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake) { if (component != nullptr) { if (component->isShowing() && millisecondsToTake > 0) animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0); component->setVisible (false); } } void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake) { if (component != nullptr && ! (component->isVisible() && component->getAlpha() == 1.0f)) { component->setAlpha (0.0f); component->setVisible (true); animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0); } } void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions) { if (tasks.size() > 0) { if (moveComponentsToTheirFinalPositions) for (int i = tasks.size(); --i >= 0;) tasks.getUnchecked(i)->moveToFinalDestination(); tasks.clear(); sendChangeMessage(); } } void ComponentAnimator::cancelAnimation (Component* const component, const bool moveComponentToItsFinalPosition) { if (AnimationTask* const at = findTaskFor (component)) { if (moveComponentToItsFinalPosition) at->moveToFinalDestination(); tasks.removeObject (at); sendChangeMessage(); } } Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component) { jassert (component != nullptr); if (AnimationTask* const at = findTaskFor (component)) return at->destination; return component->getBounds(); } bool ComponentAnimator::isAnimating (Component* component) const noexcept { return findTaskFor (component) != nullptr; } bool ComponentAnimator::isAnimating() const noexcept { return tasks.size() != 0; } void ComponentAnimator::timerCallback() { const uint32 timeNow = Time::getMillisecondCounter(); if (lastTime == 0 || lastTime == timeNow) lastTime = timeNow; const int elapsed = (int) (timeNow - lastTime); for (int i = tasks.size(); --i >= 0;) { if (! tasks.getUnchecked(i)->useTimeslice (elapsed)) { tasks.remove (i); sendChangeMessage(); } } lastTime = timeNow; if (tasks.size() == 0) stopTimer(); }
412
0.954803
1
0.954803
game-dev
MEDIA
0.647636
game-dev,graphics-rendering
0.996667
1
0.996667
SlimeKnights/TinkersConstruct
2,444
src/main/java/slimeknights/tconstruct/library/tools/definition/module/interaction/ToggleableSetInteraction.java
package slimeknights.tconstruct.library.tools.definition.module.interaction; import slimeknights.mantle.data.loadable.record.RecordLoadable; import slimeknights.mantle.data.predicate.IJsonPredicate; import slimeknights.tconstruct.library.json.predicate.modifier.ModifierPredicate; import slimeknights.tconstruct.library.modifiers.ModifierId; import slimeknights.tconstruct.library.modifiers.hook.interaction.InteractionSource; import slimeknights.tconstruct.library.module.HookProvider; import slimeknights.tconstruct.library.module.ModuleHook; import slimeknights.tconstruct.library.recipe.worktable.ModifierSetWorktableRecipe; import slimeknights.tconstruct.library.tools.definition.module.ToolHooks; import slimeknights.tconstruct.library.tools.definition.module.ToolModule; import slimeknights.tconstruct.library.tools.nbt.IToolStackView; import java.util.List; /** * Variant of {@link PreferenceSetInteraction} that supports toggling modifiers into the other set like {@link DualOptionInteraction} */ public record ToggleableSetInteraction(IJsonPredicate<ModifierId> interactModifiers) implements InteractionToolModule, ToolModule { private static final List<ModuleHook<?>> DEFAULT_HOOKS = HookProvider.<PreferenceSetInteraction>defaultHooks(ToolHooks.INTERACTION); public static final RecordLoadable<ToggleableSetInteraction> LOADER = RecordLoadable.create( ModifierPredicate.LOADER.requiredField("interact_modifiers", ToggleableSetInteraction::interactModifiers), ToggleableSetInteraction::new); @Override public boolean canInteract(IToolStackView tool, ModifierId modifier, InteractionSource source) { // no usecase for mixing armor and not armor if (source == InteractionSource.ARMOR) { return false; } // interaction modifiers toggle to left click, otherwise they toggle to right click InteractionSource toggled = interactModifiers.matches(modifier) ? InteractionSource.LEFT_CLICK : InteractionSource.RIGHT_CLICK; // if the source is the toggled target, must be in the toggled set // if the source is not the toggled target, must not be in the toggled set return (source == toggled) == ModifierSetWorktableRecipe.isInSet(tool.getPersistentData(), toggled.getKey(), modifier); } @Override public List<ModuleHook<?>> getDefaultHooks() { return DEFAULT_HOOKS; } @Override public RecordLoadable<ToggleableSetInteraction> getLoader() { return LOADER; } }
412
0.902484
1
0.902484
game-dev
MEDIA
0.288511
game-dev
0.659942
1
0.659942
followingthefasciaplane/source-engine-diff-check
1,403
misc/game/client/timedevent.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef TIMEDEVENT_H #define TIMEDEVENT_H #ifdef _WIN32 #pragma once #endif // This class triggers events at a specified rate. Just call NextEvent() and do an event until it // returns false. For example, if you want to spawn particles 10 times per second, do this: // pTimer->SetRate(10); // float tempDelta = fTimeDelta; // while(pTimer->NextEvent(tempDelta)) // spawn a particle class TimedEvent { public: TimedEvent() { m_TimeBetweenEvents = -1; m_fNextEvent = 0; } // Rate is in events per second (ie: rate of 15 will trigger 15 events per second). inline void Init(float rate) { m_TimeBetweenEvents = 1.0f / rate; m_fNextEvent = 0; } inline void ResetRate(float rate) { m_TimeBetweenEvents = 1.0f / rate; } inline bool NextEvent(float &curDelta) { // If this goes off, you didn't call Init(). Assert( m_TimeBetweenEvents != -1 ); if(curDelta >= m_fNextEvent) { curDelta -= m_fNextEvent; m_fNextEvent = m_TimeBetweenEvents; return true; } else { m_fNextEvent -= curDelta; return false; } } private: float m_TimeBetweenEvents; float m_fNextEvent; // When the next event should be triggered. }; #endif // TIMEDEVENT_H
412
0.811138
1
0.811138
game-dev
MEDIA
0.734956
game-dev
0.833145
1
0.833145
hoohack/read-php-src
4,921
php-7.1.9/ext/intl/tests/locale_parse_locale.phpt
--TEST-- locale_parse_locale() icu <= 4.2 --SKIPIF-- <?php if( !extension_loaded( 'intl' ) ) print 'skip'; ?> <?php if(version_compare(INTL_ICU_VERSION, '4.3', '<') != 1) print 'skip'; ?> --FILE-- <?php /* * Try parsing different Locales * with Procedural and Object methods. */ function ut_main() { $res_str = ''; $locales = array( 'uk-ua_CALIFORNIA@currency=;currency=GRN', 'root', 'uk@currency=EURO', 'Hindi', //Simple language subtag 'de', 'fr', 'ja', 'i-enochian', //(example of a grandfathered tag) //Language subtag plus Script subtag: 'zh-Hant', 'zh-Hans', 'sr-Cyrl', 'sr-Latn', //Language-Script-Region 'zh-Hans-CN', 'sr-Latn-CS', //Language-Variant 'sl-rozaj', 'sl-nedis', //Language-Region-Variant 'de-CH-1901', 'sl-IT-nedis', //Language-Script-Region-Variant 'sl-Latn-IT-nedis', //Language-Region: 'de-DE', 'en-US', 'es-419', //Private use subtags: 'de-CH-x-phonebk', 'az-Arab-x-AZE-derbend', //Extended language subtags 'zh-min', 'zh-min-nan-Hant-CN', //Private use registry values 'qaa-Qaaa-QM-x-southern', 'sr-Latn-QM', 'sr-Qaaa-CS', /*Tags that use extensions (examples ONLY: extensions MUST be defined by revision or update to this document or by RFC): */ 'en-US-u-islamCal', 'zh-CN-a-myExt-x-private', 'en-a-myExt-b-another', //Some Invalid Tags: 'de-419-DE', 'a-DE', 'ar-a-aaa-b-bbb-a-ccc' ); $res_str = ''; foreach( $locales as $locale ) { $arr = ut_loc_locale_parse( $locale); $res_str .= "---------------------\n"; $res_str .= "$locale:\n"; if( $arr){ foreach( $arr as $key => $value){ $res_str .= "$key : '$value' , "; } $res_str = rtrim($res_str); } else{ $res_str .= "No values found from Locale parsing."; } $res_str .= "\n"; } $res_str .= "\n"; return $res_str; } include_once( 'ut_common.inc' ); ut_run(); ?> --EXPECTF-- --------------------- uk-ua_CALIFORNIA@currency=;currency=GRN: language : 'uk' , region : 'UA' , variant0 : 'CALIFORNIA' , --------------------- root: language : 'root' , --------------------- uk@currency=EURO: language : 'uk' , --------------------- Hindi: language : 'hindi' , --------------------- de: language : 'de' , --------------------- fr: language : 'fr' , --------------------- ja: language : 'ja' , --------------------- i-enochian: grandfathered : 'i-enochian' , --------------------- zh-Hant: language : 'zh' , script : 'Hant' , --------------------- zh-Hans: language : 'zh' , script : 'Hans' , --------------------- sr-Cyrl: language : 'sr' , script : 'Cyrl' , --------------------- sr-Latn: language : 'sr' , script : 'Latn' , --------------------- zh-Hans-CN: language : 'zh' , script : 'Hans' , region : 'CN' , --------------------- sr-Latn-CS: language : 'sr' , script : 'Latn' , region : 'CS' , --------------------- sl-rozaj: language : 'sl' ,%r( region : 'ROZAJ' ,)?%r --------------------- sl-nedis: language : 'sl' ,%r( region : 'NEDIS' ,)?%r --------------------- de-CH-1901: language : 'de' , region : 'CH' , variant0 : '1901' , --------------------- sl-IT-nedis: language : 'sl' , region : 'IT' , variant0 : 'NEDIS' , --------------------- sl-Latn-IT-nedis: language : 'sl' , script : 'Latn' , region : 'IT' , variant0 : 'NEDIS' , --------------------- de-DE: language : 'de' , region : 'DE' , --------------------- en-US: language : 'en' , region : 'US' , --------------------- es-419: language : 'es' , region : '419' , --------------------- de-CH-x-phonebk: language : 'de' , region : 'CH' , private0 : 'phonebk' , --------------------- az-Arab-x-AZE-derbend: language : 'az' , script : 'Arab' , private0 : 'AZE' , private1 : 'derbend' , --------------------- zh-min: grandfathered : 'zh-min' , --------------------- zh-min-nan-Hant-CN: language : 'zh' , region : 'MIN' , variant0 : 'NAN' , variant1 : 'HANT' , variant2 : 'CN' , --------------------- qaa-Qaaa-QM-x-southern: language : 'qaa' , script : 'Qaaa' , region : 'QM' , private0 : 'southern' , --------------------- sr-Latn-QM: language : 'sr' , script : 'Latn' , region : 'QM' , --------------------- sr-Qaaa-CS: language : 'sr' , script : 'Qaaa' , region : 'CS' , --------------------- en-US-u-islamCal: language : 'en' , region : 'US' , --------------------- zh-CN-a-myExt-x-private: language : 'zh' , region : 'CN' , private0 : 'private' , --------------------- en-a-myExt-b-another: language : 'en' , --------------------- de-419-DE: language : 'de' , region : '419' , variant0 : 'DE' , --------------------- a-DE: No values found from Locale parsing. --------------------- ar-a-aaa-b-bbb-a-ccc: language : 'ar' ,
412
0.731149
1
0.731149
game-dev
MEDIA
0.57136
game-dev
0.685697
1
0.685697
MachineMuse/MachineMusePowersuits
9,870
src/main/java/net/machinemuse/general/gui/frame/ColourPickerFrame.java
package net.machinemuse.general.gui.frame; import net.machinemuse.general.gui.clickable.ClickableSlider; import net.machinemuse.numina.general.MuseLogger; import net.machinemuse.numina.geometry.Colour; import net.machinemuse.numina.geometry.DrawableMuseRect; import net.machinemuse.numina.geometry.MusePoint2D; import net.machinemuse.numina.geometry.MuseRect; import net.machinemuse.numina.network.PacketSender; import net.machinemuse.powersuits.item.ItemPowerArmor; import net.machinemuse.powersuits.network.packets.MusePacketColourInfo; import net.machinemuse.utils.MuseItemUtils; import net.machinemuse.utils.render.GuiIcons; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagIntArray; import org.apache.commons.lang3.ArrayUtils; import java.util.ArrayList; import java.util.List; /** * Author: MachineMuse (Claire Semple) * Created: 4:19 AM, 03/05/13 * * Ported to Java by lehjr on 11/2/16. */ public class ColourPickerFrame implements IGuiFrame { public ItemSelectionFrame itemSelector; public DrawableMuseRect border; public ClickableSlider rslider; public ClickableSlider gslider; public ClickableSlider bslider; public ClickableSlider selectedSlider; public int selectedColour; public int decrAbove; public ColourPickerFrame(MuseRect borderRef, Colour insideColour, Colour borderColour, ItemSelectionFrame itemSelector) { this.itemSelector = itemSelector; this.border = new DrawableMuseRect(borderRef, insideColour, borderColour); this.rslider = new ClickableSlider(new MusePoint2D(this.border.centerx(), this.border.top() + 8), this.border.width() - 10, I18n.format("gui.red")); this.gslider = new ClickableSlider(new MusePoint2D(this.border.centerx(), this.border.top() + 24), this.border.width() - 10, I18n.format("gui.green")); this.bslider = new ClickableSlider(new MusePoint2D(this.border.centerx(), this.border.top() + 40), this.border.width() - 10, I18n.format("gui.blue")); this.selectedSlider = null; this.selectedColour = 0; this.decrAbove = -1; } public int[] colours() { return (getOrCreateColourTag() != null) ? getOrCreateColourTag().getIntArray() : new int[0]; } public NBTTagIntArray getOrCreateColourTag() { if (this.itemSelector.getSelectedItem() == null) { return null; } NBTTagCompound renderSpec = MuseItemUtils.getMuseRenderTag(this.itemSelector.getSelectedItem().getItem()); if (renderSpec.hasKey("colours") && renderSpec.getTag("colours") instanceof NBTTagIntArray) { return (NBTTagIntArray) renderSpec.getTag("colours"); } else { Item item = this.itemSelector.getSelectedItem().getItem().getItem(); if (item instanceof ItemPowerArmor) { ItemPowerArmor itemPowerArmor = (ItemPowerArmor)item; int[] intArray = { itemPowerArmor.getColorFromItemStack(this.itemSelector.getSelectedItem().getItem()).getInt(), itemPowerArmor.getGlowFromItemStack(this.itemSelector.getSelectedItem().getItem()).getInt() }; renderSpec.setIntArray("colours", intArray); } else { int[] intArray2 = new int[0]; renderSpec.setIntArray("colours", intArray2); } EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; if (player.worldObj.isRemote) { PacketSender.sendToServer(new MusePacketColourInfo((EntityPlayer)player, this.itemSelector.getSelectedItem().inventorySlot, this.colours())); } return (NBTTagIntArray) renderSpec.getTag("colours"); } } public NBTTagIntArray setColourTagMaybe(int[] newarray) { if (this.itemSelector.getSelectedItem() == null) { return null; } NBTTagCompound renderSpec = MuseItemUtils.getMuseRenderTag(this.itemSelector.getSelectedItem().getItem()); renderSpec.setTag("colours", (NBTBase)new NBTTagIntArray(newarray)); EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; if (player.worldObj.isRemote) { PacketSender.sendToServer(new MusePacketColourInfo((EntityPlayer)player, this.itemSelector.getSelectedItem().inventorySlot, this.colours())); } return (NBTTagIntArray) renderSpec.getTag("colours"); } public ArrayList<Integer> importColours() { return new ArrayList<Integer>(); } public void refreshColours() { // getOrCreateColourTag.map(coloursTag => { // val colourints: Array[Int] = coloursTag.intArray // val colourset: HashSet[Int] = HashSet.empty ++ colours ++ colourints // val colourarray = colourset.toArray // coloursTag.intArray = colourarray // }) } @Override public void onMouseUp(double x, double y, int button) { this.selectedSlider = null; } @Override public void update(double mousex, double mousey) { if (this.selectedSlider != null) { this.selectedSlider.setValueByX(mousex); if (colours().length > selectedColour) { colours()[selectedColour] = Colour.getInt(rslider.value(), gslider.value(), bslider.value(), 1.0); EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; if (player.worldObj.isRemote) PacketSender.sendToServer(new MusePacketColourInfo(player, itemSelector.getSelectedItem().inventorySlot, colours())); } } } @Override public void draw() { this.border.draw(); this.rslider.draw(); this.gslider.draw(); this.bslider.draw(); for (int i = 0; i < colours().length; i++) { new GuiIcons.ArmourColourPatch(border.left() + 8 + i * 8, border.bottom() - 16, new Colour(colours()[i]), null, null, null, null); } new GuiIcons.ArmourColourPatch(this.border.left() + 8 + this.colours().length * 8, this.border.bottom() - 16, Colour.WHITE, null, null, null, null); new GuiIcons.SelectedArmorOverlay(this.border.left() + 8 + this.selectedColour * 8, this.border.bottom() - 16, Colour.WHITE, null, null, null, null); new GuiIcons.MinusSign(this.border.left() + 8 + this.selectedColour * 8, this.border.bottom() - 24, Colour.RED, null, null, null, null); new GuiIcons.PlusSign(this.border.left() + 8 + this.colours().length * 8, this.border.bottom() - 16, Colour.GREEN, null, null, null, null); } @Override public List<String> getToolTip(int x, int y) { return null; } public void onSelectColour(int i) { Colour c = new Colour(this.colours()[i]); this.rslider.setValue(c.r); this.gslider.setValue(c.g); this.bslider.setValue(c.b); this.selectedColour = i; } @Override public void onMouseDown(double x, double y, int button) { if (this.rslider.hitBox(x, y)) this.selectedSlider = this.rslider; else if (this.gslider.hitBox(x, y)) this.selectedSlider = this.gslider; else if (this.bslider.hitBox(x, y)) this.selectedSlider = this.bslider; else this.selectedSlider = null; // add if (y > this.border.bottom() - 16 && y < this.border.bottom() - 8) { int colourCol = (int)(x - this.border.left() - 8.0) / 8; if (colourCol >= 0 && colourCol < colours().length) { this.onSelectColour(colourCol); } else if (colourCol == this.colours().length) { MuseLogger.logDebug("Adding"); setColourTagMaybe(ArrayUtils.add(getIntArray(getOrCreateColourTag()), Colour.WHITE.getInt())); } } // remove if (y > border.bottom() - 24 && y < border.bottom() - 16 && x > border.left() + 8 + selectedColour * 8 && x < border.left() + 16 + selectedColour * 8) { NBTTagIntArray nbtTagIntArray = getOrCreateColourTag(); int[] intArray = getIntArray(nbtTagIntArray); if (intArray.length > 1) { /* TODO - for 1.10.2 and above, simplyfy with Java 8 collections and streams. Seriously, all this to remove an element fron an int array*/ List<Integer> integerArray = new ArrayList<>(); int intToRemove = intArray[selectedColour]; for (int anIntArray : intArray) { if (anIntArray != intToRemove) integerArray.add(anIntArray); } int[] newIntArray = new int[integerArray.size()]; int j = 0; for (Integer i : integerArray) { newIntArray[j] = i; j+=1; } setColourTagMaybe(newIntArray); decrAbove = selectedColour; if (selectedColour == getIntArray(nbtTagIntArray).length) { selectedColour = selectedColour -1; } EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; if (player.worldObj.isRemote) PacketSender.sendToServer(new MusePacketColourInfo(player, itemSelector.getSelectedItem().inventorySlot, nbtTagIntArray.getIntArray())); } } } public int[] getIntArray(NBTTagIntArray e) { if (e == null) // null when no armor item selected return new int[0]; return e.getIntArray(); } }
412
0.743948
1
0.743948
game-dev
MEDIA
0.892542
game-dev
0.921004
1
0.921004
ForestryMC/ForestryMC
1,951
src/main/java/forestry/core/models/ModelBlockCustomCached.java
package forestry.core.models; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public abstract class ModelBlockCustomCached<B extends Block, K> extends ModelBlockCustom<B, K> { private static final Set<ModelBlockCustomCached> CACHE_PROVIDERS = new HashSet<>(); private final Cache<K, IBakedModel> inventoryCache; private final Cache<K, IBakedModel> worldCache; public static void clear() { for (ModelBlockCustomCached modelBlockCached : CACHE_PROVIDERS) { modelBlockCached.worldCache.invalidateAll(); modelBlockCached.inventoryCache.invalidateAll(); modelBlockCached.onClearCaches(); } } protected void onClearCaches() { } protected ModelBlockCustomCached(Class<B> blockClass) { super(blockClass); worldCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); inventoryCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); CACHE_PROVIDERS.add(this); } @Override protected IBakedModel getModel(IBlockState state) { K key = getWorldKey(state); IBakedModel model = worldCache.getIfPresent(key); if (model == null) { model = super.getModel(state); worldCache.put(key, model); } return model; } @Override protected IBakedModel getModel(ItemStack stack, World world) { K key = getInventoryKey(stack); IBakedModel model = inventoryCache.getIfPresent(key); if (model == null) { model = bakeModel(stack, world, key); inventoryCache.put(key, model); } return model; } }
412
0.771841
1
0.771841
game-dev
MEDIA
0.976373
game-dev
0.904319
1
0.904319
thatgamesguy/that_game_engine
1,393
22 - Camera Follow/src/C_KeyboardMovement.cpp
#include "C_KeyboardMovement.hpp" #include "Object.hpp" C_KeyboardMovement::C_KeyboardMovement(Object* owner) : Component(owner), moveSpeed(400) {} void C_KeyboardMovement::Awake() { animation = owner->GetComponent<C_Animation>(); } void C_KeyboardMovement::SetInput(Input* input) { this->input = input; } void C_KeyboardMovement::SetMovementSpeed(int moveSpeed) { this->moveSpeed = moveSpeed; } void C_KeyboardMovement::Update(float deltaTime) { if(input == nullptr) { return; } int xMove = 0; if(input->IsKeyPressed(Input::Key::Left)) { xMove = -moveSpeed; animation->SetAnimationDirection(FacingDirection::Left); } else if(input->IsKeyPressed(Input::Key::Right)) { xMove = moveSpeed; animation->SetAnimationDirection(FacingDirection::Right); } int yMove = 0; if(input->IsKeyPressed(Input::Key::Up)) { yMove = -moveSpeed; } else if(input->IsKeyPressed(Input::Key::Down)) { yMove = moveSpeed; } float xFrameMove = xMove * deltaTime; float yFrameMove = yMove * deltaTime; owner->transform->AddPosition(xFrameMove, yFrameMove); if(xMove == 0 && yMove == 0) { animation->SetAnimationState(AnimationState::Idle); } else { animation->SetAnimationState(AnimationState::Walk); } }
412
0.765636
1
0.765636
game-dev
MEDIA
0.656076
game-dev
0.881953
1
0.881953
KiltMC/Kilt
1,030
src/main/java/xyz/bluspring/kilt/forgeinjects/client/particle/ReversePortalParticleInject.java
package xyz.bluspring.kilt.forgeinjects.client.particle; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.PortalParticle; import net.minecraft.client.particle.ReversePortalParticle; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ReversePortalParticle.class) public abstract class ReversePortalParticleInject extends PortalParticle { protected ReversePortalParticleInject(ClientLevel level, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed) { super(level, x, y, z, xSpeed, ySpeed, zSpeed); } @Inject(method = "tick", at = @At(value = "FIELD", target = "Lnet/minecraft/client/particle/ReversePortalParticle;z:D", ordinal = 2, shift = At.Shift.AFTER)) private void kilt$updateParticleBoundingBox(CallbackInfo ci) { this.setPos(this.x, this.y, this.z); } }
412
0.639631
1
0.639631
game-dev
MEDIA
0.820835
game-dev
0.5311
1
0.5311
servo/skia
2,261
src/utils/ios/SkOSFile_iOS.mm
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Foundation/Foundation.h> #include "SkOSFile.h" #include "SkString.h" struct SkFILE { NSData* fData; size_t fOffset; size_t fLength; }; SkFILE* sk_fopen(const char cpath[], SkFILE_Flags flags) { if (flags & kWrite_SkFILE_Flag) { return NULL; } SkString cname, csuffix; const char* start = strrchr(cpath, '/'); if (NULL == start) { start = cpath; } else { start += 1; } const char* stop = strrchr(cpath, '.'); if (NULL == stop) { return NULL; } else { stop += 1; } cname.set(start, stop - start - 1); csuffix.set(stop); NSBundle* bundle = [NSBundle mainBundle]; NSString* name = [NSString stringWithUTF8String:cname.c_str()]; NSString* suffix = [NSString stringWithUTF8String:csuffix.c_str()]; NSString* path = [bundle pathForResource:name ofType:suffix]; NSData* data = [NSData dataWithContentsOfMappedFile:path]; if (data) { [data retain]; SkFILE* rec = new SkFILE; rec->fData = data; rec->fOffset = 0; rec->fLength = [data length]; return reinterpret_cast<SkFILE*>(rec); } return NULL; } size_t sk_fgetsize(SkFILE* rec) { SkASSERT(rec); return rec->fLength; } bool sk_frewind(SkFILE* rec) { SkASSERT(rec); rec->fOffset = 0; return true; } size_t sk_fread(void* buffer, size_t byteCount, SkFILE* rec) { if (NULL == buffer) { return rec->fLength; } else { size_t remaining = rec->fLength - rec->fOffset; if (byteCount > remaining) { byteCount = remaining; } memcpy(buffer, (char*)[rec->fData bytes] + rec->fOffset, byteCount); rec->fOffset += byteCount; SkASSERT(rec->fOffset <= rec->fLength); return byteCount; } } size_t sk_fwrite(const void* buffer, size_t byteCount, SkFILE* f) { SkDEBUGFAIL("Not supported yet"); return 0; } void sk_fflush(SkFILE* f) { SkDEBUGFAIL("Not supported yet"); } void sk_fclose(SkFILE* rec) { SkASSERT(rec); [rec->fData release]; delete rec; }
412
0.89555
1
0.89555
game-dev
MEDIA
0.157148
game-dev
0.957107
1
0.957107
UniRmmz/UniRmmz
1,313
Assets/Effekseer/Editor/EffekseerPluginSwitcher.cs
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Linq; using System.Collections.Generic; [InitializeOnLoad] public class EffekseerPluginSwitcher { static readonly string tempFilePath = "Temp/EffekseerPluginSwitcher"; #if UNITY_2023_2_OR_NEWER static readonly string bcPath = "WebGL/3.1.38-64bit/libEffekseerUnity.bc"; #elif UNITY_2022_2_OR_NEWER static readonly string bcPath = "WebGL/3.1.8-64bit/libEffekseerUnity.bc"; #elif UNITY_2021_2_OR_NEWER static readonly string bcPath = "WebGL/2.0.19-64bit/libEffekseerUnity.bc"; #else static readonly string bcPath = "WebGL/libEffekseerUnity.bc"; #endif static EffekseerPluginSwitcher() { Run(); } static public void Run() { // called only once if (!System.IO.File.Exists(tempFilePath)) { var importers = PluginImporter.GetAllImporters().Where(importer => importer.assetPath.Contains("libEffekseerUnity.bc")); if (importers.Count() > 0) { var processed = new List<string>(); foreach (var importer in importers) { var enabled = importer.assetPath.Contains(bcPath); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, enabled); processed.Add(importer.assetPath + " : " + enabled.ToString()); } System.IO.File.WriteAllLines(tempFilePath, processed.ToArray()); } } } } #endif
412
0.904879
1
0.904879
game-dev
MEDIA
0.45051
game-dev
0.788819
1
0.788819
axx0/Civ2-clone
2,397
RaylibUI/RunGame/Commands/CityReportOptions.cs
using Civ2engine; using Model; using Model.Dialog; using Model.Images; using Model.Menu; using Raylib_CSharp.Interact; namespace RaylibUI.RunGame.Commands; public class CityReportOptions : IGameCommand { private readonly GameScreen _gameScreen; private readonly Options _options; public CityReportOptions(GameScreen gameScreen) { _gameScreen = gameScreen; _options = gameScreen.Game.Options; } public string Id => CommandIds.CityReportOptions; public Shortcut[] ActivationKeys { get; set; } = { new(KeyboardKey.E, ctrl: true) }; public CommandStatus Status => CommandStatus.Normal; public bool Update() { return true; } public void Action() { // ReSharper disable once StringLiteralTypo _gameScreen.ShowPopup("MESSAGEOPTIONS", DialogClick, checkboxStates: new List<bool> { _options.WarnWhenCityGrowthHalted, _options.ShowCityImprovementsBuilt, _options.ShowNonCombatUnitsBuilt, _options.ShowInvalidBuildInstructions, _options.AnnounceCitiesInDisorder, _options.AnnounceOrderRestored, _options.AnnounceWeLoveKingDay, _options.WarnWhenFoodDangerouslyLow, _options.WarnWhenPollutionOccurs, _options.WarnChangProductWillCostShields, _options.ZoomToCityNotDefaultAction }); } private void DialogClick(string button, int _, IList<bool>? checkboxes, IDictionary<string, string>? _2) { if (button == Labels.Ok) { _options.WarnWhenCityGrowthHalted = checkboxes[0]; _options.ShowCityImprovementsBuilt = checkboxes[1]; _options.ShowNonCombatUnitsBuilt = checkboxes[2]; _options.ShowInvalidBuildInstructions = checkboxes[3]; _options.AnnounceCitiesInDisorder = checkboxes[4]; _options.AnnounceOrderRestored = checkboxes[5]; _options.AnnounceWeLoveKingDay = checkboxes[6]; _options.WarnWhenFoodDangerouslyLow = checkboxes[7]; _options.WarnWhenPollutionOccurs = checkboxes[8]; _options.WarnChangProductWillCostShields = checkboxes[9]; _options.ZoomToCityNotDefaultAction = checkboxes[10]; } } public bool Checked => false; public MenuCommand? Command { get; set; } public string ErrorDialog { get; } = string.Empty; public DialogImageElements? ErrorImage { get; } = null; public string? Name { get; } }
412
0.845415
1
0.845415
game-dev
MEDIA
0.428887
game-dev
0.772413
1
0.772413
RSDKModding/RSDKv5-Decompilation
140,721
RSDKv5/RSDK/Scene/Legacy/v3/CollisionLegacyv3.cpp
int32 RSDK::Legacy::v3::collisionLeft = 0; int32 RSDK::Legacy::v3::collisionTop = 0; int32 RSDK::Legacy::v3::collisionRight = 0; int32 RSDK::Legacy::v3::collisionBottom = 0; RSDK::Legacy::v3::CollisionSensor RSDK::Legacy::v3::sensors[6]; RSDK::Legacy::v3::CollisionStore RSDK::Legacy::v3::collisionStorage[2]; const int32 hammerJumpHitbox[] = { -25, -25, 25, 25, -25, -25, 25, 25, -25, -25, 25, 25, -25, -25, 25, 25 }; const int32 hammerDashHitbox[] = { -10, -17, 23, 17, -23, -17, 10, 17, -18, -24, 10, 17, -10, -26, 25, 17, -10, -17, 23, 17, -23, -17, 10, 17, -18, -24, 10, 17, -10, -26, 25, 17 }; const int32 chibiHammerJumpHitbox[] = { -15, -11, 15, 20, -15, -11, 15, 20, }; const int32 chibiHammerDashHitbox[] = { -14, -12, 8, 12, -10, -12, 8, 12, -8, -12,16, 12 }; #if !RETRO_USE_ORIGINAL_CODE int32 RSDK::Legacy::v3::AddDebugHitbox(uint8 type, Entity *entity, int32 left, int32 top, int32 right, int32 bottom) { int32 XPos = 0, YPos = 0; if (entity) { XPos = entity->XPos; YPos = entity->YPos; } else { Player *player = &playerList[activePlayer]; XPos = player->XPos; YPos = player->YPos; } int32 i = 0; for (; i < debugHitboxCount; ++i) { if (debugHitboxList[i].hitbox.left == left && debugHitboxList[i].hitbox.top == top && debugHitboxList[i].hitbox.right == right && debugHitboxList[i].hitbox.bottom == bottom && debugHitboxList[i].pos.x == XPos && debugHitboxList[i].pos.y == YPos && debugHitboxList[i].entity == entity) { return i; } } if (i < DEBUG_HITBOX_COUNT) { debugHitboxList[i].type = type; debugHitboxList[i].entity = entity; debugHitboxList[i].collision = 0; debugHitboxList[i].hitbox.left = left; debugHitboxList[i].hitbox.top = top; debugHitboxList[i].hitbox.right = right; debugHitboxList[i].hitbox.bottom = bottom; debugHitboxList[i].pos.x = XPos; debugHitboxList[i].pos.y = YPos; int32 id = debugHitboxCount; debugHitboxCount++; return id; } return -1; } #endif RSDK::Legacy::Hitbox *RSDK::Legacy::v3::GetPlayerHitbox(Player *player) { AnimationFile *animFile = player->animationFile; return &hitboxList [animFrames[animationList[animFile->aniListOffset + player->boundEntity->animation].frameListOffset + player->boundEntity->frame].hitboxID + animFile->hitboxListOffset]; } void RSDK::Legacy::v3::FindFloorPosition(Player *player, CollisionSensor *sensor, int32 startY) { int32 c = 0; int32 angle = sensor->angle; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = sensor->XPos >> 16; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = (sensor->YPos >> 16) + i - TILE_SIZE; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile += tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_LRB && tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].floorMasks[c] >= 0x40) break; sensor->YPos = collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF; break; } case FLIP_X: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].floorMasks[c] >= 0x40) break; sensor->YPos = collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = 0x100 - (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF); break; } case FLIP_Y: { c = (XPos & 15) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].roofMasks[c] <= -0x40) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; uint8 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24; sensor->angle = (uint8)(-0x80 - cAngle); break; } case FLIP_XY: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].roofMasks[c] <= -0x40) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; uint8 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24; sensor->angle = 0x100 - (uint8)(-0x80 - cAngle); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if ((abs(sensor->angle - angle) > 0x20) && (abs(sensor->angle - 0x100 - angle) > 0x20) && (abs(sensor->angle + 0x100 - angle) > 0x20)) { sensor->YPos = startY << 16; sensor->collided = false; sensor->angle = angle; i = TILE_SIZE * 3; } else if (sensor->YPos - startY > (TILE_SIZE - 2)) { sensor->YPos = startY << 16; sensor->collided = false; } else if (sensor->YPos - startY < -(TILE_SIZE - 2)) { sensor->YPos = startY << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::FindLWallPosition(Player *player, CollisionSensor *sensor, int32 startX) { int32 c = 0; int32 angle = sensor->angle; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = (sensor->XPos >> 16) + i - TILE_SIZE; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = sensor->YPos >> 16; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile = tile + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].lWallMasks[c] >= 0x40) break; sensor->XPos = collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; sensor->angle = ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF00) >> 8); break; } case FLIP_X: { c = (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].rWallMasks[c] <= -0x40) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; sensor->angle = 0x100 - ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF0000) >> 16); break; } case FLIP_Y: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].lWallMasks[c] >= 0x40) break; sensor->XPos = collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF00) >> 8; sensor->angle = (uint8)(-0x80 - cAngle); break; } case FLIP_XY: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].rWallMasks[c] <= -0x40) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF0000) >> 16; sensor->angle = 0x100 - (uint8)(-0x80 - cAngle); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if (abs(angle - sensor->angle) > 0x20) { sensor->XPos = startX << 16; sensor->collided = false; sensor->angle = angle; i = TILE_SIZE * 3; } else if (sensor->XPos - startX > TILE_SIZE - 2) { sensor->XPos = startX << 16; sensor->collided = false; } else if (sensor->XPos - startX < -(TILE_SIZE - 2)) { sensor->XPos = startX << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::FindRoofPosition(Player *player, CollisionSensor *sensor, int32 startY) { int32 c = 0; int32 angle = sensor->angle; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = sensor->XPos >> 16; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = (sensor->YPos >> 16) + TILE_SIZE - i; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile = tile + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].roofMasks[c] <= -0x40) break; sensor->YPos = collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24; break; } case FLIP_X: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].roofMasks[c] <= -0x40) break; sensor->YPos = collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = 0x100 - ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24); break; } case FLIP_Y: { c = (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].floorMasks[c] >= 0x40) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; uint8 cAngle = collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF; sensor->angle = (uint8)(-0x80 - cAngle); break; } case FLIP_XY: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].floorMasks[c] >= 0x40) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; uint8 cAngle = collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF; sensor->angle = 0x100 - (uint8)(-0x80 - cAngle); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if (abs(sensor->angle - angle) <= 0x20) { if (sensor->YPos - startY > tsm1) { sensor->YPos = startY << 16; sensor->collided = false; } if (sensor->YPos - startY < -tsm1) { sensor->YPos = startY << 16; sensor->collided = false; } } else { sensor->YPos = startY << 16; sensor->collided = false; sensor->angle = angle; i = TILE_SIZE * 3; } } } } } } void RSDK::Legacy::v3::FindRWallPosition(Player *player, CollisionSensor *sensor, int32 startX) { int32 c; int32 angle = sensor->angle; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = (sensor->XPos >> 16) + TILE_SIZE - i; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = sensor->YPos >> 16; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile = tile + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].rWallMasks[c] <= -0x40) break; sensor->XPos = collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; sensor->angle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF0000) >> 16; break; } case FLIP_X: { c = (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].lWallMasks[c] >= 0x40) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; sensor->angle = 0x100 - ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF00) >> 8); break; } case FLIP_Y: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].rWallMasks[c] <= -0x40) break; sensor->XPos = collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF0000) >> 16; sensor->angle = (uint8)(-0x80 - cAngle); break; } case FLIP_XY: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if (collisionMasks[player->collisionPlane].lWallMasks[c] >= 0x40) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF00) >> 8; sensor->angle = 0x100 - (uint8)(-0x80 - cAngle); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if (abs(sensor->angle - angle) > 0x20) { sensor->XPos = startX << 16; sensor->collided = false; sensor->angle = angle; i = TILE_SIZE * 3; } else if (sensor->XPos - startX > (TILE_SIZE - 2)) { sensor->XPos = startX >> 16; sensor->collided = false; } else if (sensor->XPos - startX < -(TILE_SIZE - 2)) { sensor->XPos = startX << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::FloorCollision(Player *player, CollisionSensor *sensor) { int32 c; int32 startY = sensor->YPos >> 16; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = sensor->XPos >> 16; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = (sensor->YPos >> 16) + i - TILE_SIZE; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile += tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_LRB && tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) <= collisionMasks[player->collisionPlane].floorMasks[c] + i - TILE_SIZE || collisionMasks[player->collisionPlane].floorMasks[c] >= tsm1) break; sensor->YPos = collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF; break; } case FLIP_X: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) <= collisionMasks[player->collisionPlane].floorMasks[c] + i - TILE_SIZE || collisionMasks[player->collisionPlane].floorMasks[c] >= tsm1) break; sensor->YPos = collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = 0x100 - (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF); break; } case FLIP_Y: { c = (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) <= tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + i - TILE_SIZE) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24; sensor->angle = (uint8)(-0x80 - cAngle); break; } case FLIP_XY: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) <= tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + i - TILE_SIZE) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; int32 cAngle = (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24; sensor->angle = 0x100 - (uint8)(-0x80 - cAngle); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if (sensor->YPos - startY > (TILE_SIZE - 2)) { sensor->YPos = startY << 16; sensor->collided = false; } else if (sensor->YPos - startY < -(TILE_SIZE + 1)) { sensor->YPos = startY << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::LWallCollision(Player *player, CollisionSensor *sensor) { int32 c; int32 startX = sensor->XPos >> 16; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = (sensor->XPos >> 16) + i - TILE_SIZE; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = sensor->YPos >> 16; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile += tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_TOP && tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) <= collisionMasks[player->collisionPlane].lWallMasks[c] + i - TILE_SIZE) break; sensor->XPos = collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_X: { c = (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) <= tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + i - TILE_SIZE) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_Y: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) <= collisionMasks[player->collisionPlane].lWallMasks[c] + i - TILE_SIZE) break; sensor->XPos = collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_XY: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) <= tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + i - TILE_SIZE) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } } } if (sensor->collided) { if (sensor->XPos - startX > tsm1) { sensor->XPos = startX << 16; sensor->collided = false; } else if (sensor->XPos - startX < -tsm1) { sensor->XPos = startX << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::RoofCollision(Player *player, CollisionSensor *sensor) { int32 c; int32 startY = sensor->YPos >> 16; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = sensor->XPos >> 16; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = (sensor->YPos >> 16) + TILE_SIZE - i; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile += tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_TOP && tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) >= collisionMasks[player->collisionPlane].roofMasks[c] + TILE_SIZE - i) break; sensor->YPos = collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24); break; } case FLIP_X: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) >= collisionMasks[player->collisionPlane].roofMasks[c] + TILE_SIZE - i) break; sensor->YPos = collisionMasks[player->collisionPlane].roofMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = 0x100 - ((collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF000000) >> 24); break; } case FLIP_Y: { c = (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) >= tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + TILE_SIZE - i) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = (uint8)(-0x80 - (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF)); break; } case FLIP_XY: { c = tsm1 - (XPos & tsm1) + (tileIndex << 4); if ((YPos & tsm1) >= tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + TILE_SIZE - i) break; sensor->YPos = tsm1 - collisionMasks[player->collisionPlane].floorMasks[c] + (chunkY << 7) + (tileY << 4); sensor->collided = true; sensor->angle = 0x100 - (uint8)(-0x80 - (collisionMasks[player->collisionPlane].angles[tileIndex] & 0xFF)); break; } } } if (sensor->collided) { if (sensor->angle < 0) sensor->angle += 0x100; if (sensor->angle > 0xFF) sensor->angle -= 0x100; if (sensor->YPos - startY > (TILE_SIZE - 2)) { sensor->YPos = startY << 16; sensor->collided = false; } else if (sensor->YPos - startY < -(TILE_SIZE - 2)) { sensor->YPos = startY << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::RWallCollision(Player *player, CollisionSensor *sensor) { int32 c; int32 startX = sensor->XPos >> 16; int32 tsm1 = (TILE_SIZE - 1); for (int32 i = 0; i < TILE_SIZE * 3; i += TILE_SIZE) { if (!sensor->collided) { int32 XPos = (sensor->XPos >> 16) + TILE_SIZE - i; int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 YPos = sensor->YPos >> 16; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; if (XPos > -1 && YPos > -1) { int32 tile = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; tile += tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[tile]; if (tiles128x128.collisionFlags[player->collisionPlane][tile] != SOLID_TOP && tiles128x128.collisionFlags[player->collisionPlane][tile] < SOLID_NONE) { switch (tiles128x128.direction[tile]) { case FLIP_NONE: { c = (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) >= collisionMasks[player->collisionPlane].rWallMasks[c] + TILE_SIZE - i) break; sensor->XPos = collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_X: { c = (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) >= tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + TILE_SIZE - i) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_Y: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) >= collisionMasks[player->collisionPlane].rWallMasks[c] + TILE_SIZE - i) break; sensor->XPos = collisionMasks[player->collisionPlane].rWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } case FLIP_XY: { c = tsm1 - (YPos & tsm1) + (tileIndex << 4); if ((XPos & tsm1) >= tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + TILE_SIZE - i) break; sensor->XPos = tsm1 - collisionMasks[player->collisionPlane].lWallMasks[c] + (chunkX << 7) + (tileX << 4); sensor->collided = true; break; } } } if (sensor->collided) { if (sensor->XPos - startX > tsm1) { sensor->XPos = startX << 16; sensor->collided = false; } else if (sensor->XPos - startX < -tsm1) { sensor->XPos = startX << 16; sensor->collided = false; } } } } } } void RSDK::Legacy::v3::ProcessAirCollision(Player *player) { Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; uint8 movingDown = 0; uint8 movingUp = 1; uint8 movingLeft = 0; uint8 movingRight = 0; if (player->XVelocity < 0) { movingRight = 0; } else { movingRight = 1; sensors[0].YPos = player->YPos + 0x20000; sensors[0].collided = false; sensors[0].XPos = player->XPos + (collisionRight << 16); } if (player->XVelocity > 0) { movingLeft = 0; } else { movingLeft = 1; sensors[1].YPos = player->YPos + 0x20000; sensors[1].collided = false; sensors[1].XPos = player->XPos + ((collisionLeft - 1) << 16); } sensors[2].XPos = player->XPos + (playerHitbox->left[1] << 16); sensors[3].XPos = player->XPos + (playerHitbox->right[1] << 16); sensors[2].collided = false; sensors[3].collided = false; sensors[4].XPos = sensors[2].XPos; sensors[5].XPos = sensors[3].XPos; sensors[4].collided = false; sensors[5].collided = false; if (player->YVelocity < 0) { movingDown = 0; } else { movingDown = 1; sensors[2].YPos = player->YPos + (collisionBottom << 16); sensors[3].YPos = player->YPos + (collisionBottom << 16); } sensors[4].YPos = player->YPos + ((collisionTop - 1) << 16); sensors[5].YPos = player->YPos + ((collisionTop - 1) << 16); int32 cnt = (abs(player->XVelocity) <= abs(player->YVelocity) ? (abs(player->YVelocity) >> 19) + 1 : (abs(player->XVelocity) >> 19) + 1); int32 XVel = player->XVelocity / cnt; int32 YVel = player->YVelocity / cnt; int32 XVel2 = player->XVelocity - XVel * (cnt - 1); int32 YVel2 = player->YVelocity - YVel * (cnt - 1); while (cnt > 0) { if (cnt < 2) { XVel = XVel2; YVel = YVel2; } cnt--; if (movingRight == 1) { sensors[0].XPos += XVel + 0x10000; sensors[0].YPos += YVel; LWallCollision(player, &sensors[0]); if (sensors[0].collided) movingRight = 2; } if (movingLeft == 1) { sensors[1].XPos += XVel - 0x10000; sensors[1].YPos += YVel; RWallCollision(player, &sensors[1]); if (sensors[1].collided) movingLeft = 2; } if (movingRight == 2) { player->XVelocity = 0; player->speed = 0; player->XPos = (sensors[0].XPos - collisionRight) << 16; sensors[2].XPos = player->XPos + ((collisionLeft + 1) << 16); sensors[3].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[4].XPos = sensors[2].XPos; sensors[5].XPos = sensors[3].XPos; XVel = 0; XVel2 = 0; movingRight = 3; } if (movingLeft == 2) { player->XVelocity = 0; player->speed = 0; player->XPos = (sensors[1].XPos - collisionLeft + 1) << 16; sensors[2].XPos = player->XPos + ((collisionLeft + 1) << 16); sensors[3].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[4].XPos = sensors[2].XPos; sensors[5].XPos = sensors[3].XPos; XVel = 0; XVel2 = 0; movingLeft = 3; } if (movingDown == 1) { for (int32 i = 2; i < 4; i++) { if (!sensors[i].collided) { sensors[i].XPos += XVel; sensors[i].YPos += YVel; FloorCollision(player, &sensors[i]); } } if (sensors[2].collided || sensors[3].collided) { movingDown = 2; cnt = 0; } } if (movingUp == 1) { for (int32 i = 4; i < 6; i++) { if (!sensors[i].collided) { sensors[i].XPos += XVel; sensors[i].YPos += YVel; RoofCollision(player, &sensors[i]); } } if (sensors[4].collided || sensors[5].collided) { movingUp = 2; cnt = 0; } } } if (movingRight < 2 && movingLeft < 2) player->XPos = player->XPos + player->XVelocity; if (movingUp < 2 && movingDown < 2) { player->YPos = player->YPos + player->YVelocity; return; } if (movingDown == 2) { player->gravity = 0; if (sensors[2].collided && sensors[3].collided) { if (sensors[2].YPos >= sensors[3].YPos) { player->YPos = (sensors[3].YPos - collisionBottom) << 16; player->angle = sensors[3].angle; } else { player->YPos = (sensors[2].YPos - collisionBottom) << 16; player->angle = sensors[2].angle; } } else if (sensors[2].collided == 1) { player->YPos = (sensors[2].YPos - collisionBottom) << 16; player->angle = sensors[2].angle; } else if (sensors[3].collided == 1) { player->YPos = (sensors[3].YPos - collisionBottom) << 16; player->angle = sensors[3].angle; } if (player->angle > 0xA0 && player->angle < 0xE0 && player->collisionMode != CMODE_LWALL) { player->collisionMode = CMODE_LWALL; player->XPos = player->XPos - 0x40000; } if (player->angle > 0x20 && player->angle < 0x60 && player->collisionMode != CMODE_RWALL) { player->collisionMode = CMODE_RWALL; player->XPos = player->XPos + 0x40000; } if (player->angle < 0x20 || player->angle > 0xE0) { player->controlLock = 0; } player->boundEntity->rotation = player->angle << 1; int32 speed = 0; if (player->down) { if (player->angle < 128) { if (player->angle < 16) { speed = player->XVelocity; } else if (player->angle >= 32) { speed = (abs(player->XVelocity) <= abs(player->YVelocity) ? player->YVelocity + player->YVelocity / 12 : player->XVelocity); } else { speed = (abs(player->XVelocity) <= abs(player->YVelocity >> 1) ? (player->YVelocity + player->YVelocity / 12) >> 1 : player->XVelocity); } } else if (player->angle > 240) { speed = player->XVelocity; } else if (player->angle <= 224) { speed = (abs(player->XVelocity) <= abs(player->YVelocity) ? -(player->YVelocity + player->YVelocity / 12) : player->XVelocity); } else { speed = (abs(player->XVelocity) <= abs(player->YVelocity >> 1) ? -((player->YVelocity + player->YVelocity / 12) >> 1) : player->XVelocity); } } else if (player->angle < 0x80) { if (player->angle < 0x10) { speed = player->XVelocity; } else if (player->angle >= 0x20) { speed = (abs(player->XVelocity) <= abs(player->YVelocity) ? player->YVelocity : player->XVelocity); } else { speed = (abs(player->XVelocity) <= abs(player->YVelocity >> 1) ? player->YVelocity >> 1 : player->XVelocity); } } else if (player->angle > 0xF0) { speed = player->XVelocity; } else if (player->angle <= 0xE0) { speed = (abs(player->XVelocity) <= abs(player->YVelocity) ? -player->YVelocity : player->XVelocity); } else { speed = (abs(player->XVelocity) <= abs(player->YVelocity >> 1) ? -(player->YVelocity >> 1) : player->XVelocity); } if (speed < -0x180000) speed = -0x180000; if (speed > 0x180000) speed = 0x180000; player->speed = speed; player->YVelocity = 0; scriptEng.checkResult = 1; } if (movingUp == 2) { int32 sensorAngle = 0; if (sensors[4].collided && sensors[5].collided) { if (sensors[4].YPos <= sensors[5].YPos) { player->YPos = (sensors[5].YPos - collisionTop + 1) << 16; sensorAngle = sensors[5].angle; } else { player->YPos = (sensors[4].YPos - collisionTop + 1) << 16; sensorAngle = sensors[4].angle; } } else if (sensors[4].collided) { player->YPos = (sensors[4].YPos - collisionTop + 1) << 16; sensorAngle = sensors[4].angle; } else if (sensors[5].collided) { player->YPos = (sensors[5].YPos - collisionTop + 1) << 16; sensorAngle = sensors[5].angle; } sensorAngle &= 0xFF; int32 angle = ArcTanLookup(player->XVelocity, player->YVelocity); if (sensorAngle > 0x40 && sensorAngle < 0x62 && angle > 0xA0 && angle < 0xC2) { player->gravity = 0; player->angle = sensorAngle; player->boundEntity->rotation = player->angle << 1; player->collisionMode = CMODE_RWALL; player->XPos = player->XPos + 0x40000; player->YPos = player->YPos - 0x20000; if (player->angle <= 0x60) player->speed = player->YVelocity; else player->speed = player->YVelocity >> 1; } if (sensorAngle > 0x9E && sensorAngle < 0xC0 && angle > 0xBE && angle < 0xE0) { player->gravity = 0; player->angle = sensorAngle; player->boundEntity->rotation = player->angle << 1; player->collisionMode = CMODE_LWALL; player->XPos = player->XPos - 0x40000; player->YPos = player->YPos - 0x20000; if (player->angle >= 0xA0) player->speed = -player->YVelocity; else player->speed = -player->YVelocity >> 1; } if (player->YVelocity < 0) player->YVelocity = 0; scriptEng.checkResult = 2; } } void RSDK::Legacy::v3::ProcessPathGrip(Player *player) { int32 cosValue256; int32 sinValue256; sensors[4].XPos = player->XPos; sensors[4].YPos = player->YPos; for (int32 i = 0; i < 6; ++i) { sensors[i].angle = player->angle; sensors[i].collided = false; } SetPathGripSensors(player); int32 absSpeed = abs(player->speed); int32 checkDist = absSpeed >> 18; absSpeed &= 0x3FFFF; uint8 cMode = player->collisionMode; while (checkDist > -1) { if (checkDist >= 1) { cosValue256 = cos256LookupTable[player->angle] << 10; sinValue256 = sin256LookupTable[player->angle] << 10; checkDist--; } else { cosValue256 = absSpeed * cos256LookupTable[player->angle] >> 8; sinValue256 = absSpeed * sin256LookupTable[player->angle] >> 8; checkDist = -1; } if (player->speed < 0) { cosValue256 = -cosValue256; sinValue256 = -sinValue256; } sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[4].XPos += cosValue256; sensors[4].YPos += sinValue256; int32 tileDistance = -1; switch (player->collisionMode) { case CMODE_FLOOR: { sensors[3].XPos += cosValue256; sensors[3].YPos += sinValue256; if (player->speed > 0) LWallCollision(player, &sensors[3]); if (player->speed < 0) RWallCollision(player, &sensors[3]); if (sensors[3].collided) { cosValue256 = 0; checkDist = -1; } for (int32 i = 0; i < 3; i++) { sensors[i].XPos += cosValue256; sensors[i].YPos += sinValue256; FindFloorPosition(player, &sensors[i], sensors[i].YPos >> 16); } tileDistance = -1; for (int32 i = 0; i < 3; i++) { if (tileDistance > -1) { if (sensors[i].collided) { if (sensors[i].YPos < sensors[tileDistance].YPos) tileDistance = i; if (sensors[i].YPos == sensors[tileDistance].YPos && (sensors[i].angle < 0x08 || sensors[i].angle > 0xF8)) tileDistance = i; } } else if (sensors[i].collided) tileDistance = i; } if (tileDistance <= -1) { checkDist = -1; } else { sensors[0].YPos = sensors[tileDistance].YPos << 16; sensors[0].angle = sensors[tileDistance].angle; sensors[1].YPos = sensors[0].YPos; sensors[1].angle = sensors[0].angle; sensors[2].YPos = sensors[0].YPos; sensors[2].angle = sensors[0].angle; sensors[3].YPos = sensors[0].YPos - 0x40000; sensors[3].angle = sensors[0].angle; sensors[4].XPos = sensors[1].XPos; sensors[4].YPos = sensors[0].YPos - (collisionBottom << 16); } if (sensors[0].angle < 0xDE && sensors[0].angle > 0x80) player->collisionMode = CMODE_LWALL; if (sensors[0].angle > 0x22 && sensors[0].angle < 0x80) player->collisionMode = CMODE_RWALL; break; } case CMODE_LWALL: { sensors[3].XPos += cosValue256; sensors[3].YPos += sinValue256; if (player->speed > 0) RoofCollision(player, &sensors[3]); if (player->speed < 0) FloorCollision(player, &sensors[3]); if (sensors[3].collided) { sinValue256 = 0; checkDist = -1; } for (int32 i = 0; i < 3; i++) { sensors[i].XPos += cosValue256; sensors[i].YPos += sinValue256; FindLWallPosition(player, &sensors[i], sensors[i].XPos >> 16); } tileDistance = -1; for (int32 i = 0; i < 3; i++) { if (tileDistance > -1) { if (sensors[i].XPos < sensors[tileDistance].XPos && sensors[i].collided) { tileDistance = i; } } else if (sensors[i].collided) { tileDistance = i; } } if (tileDistance <= -1) { checkDist = -1; } else { sensors[0].XPos = sensors[tileDistance].XPos << 16; sensors[0].angle = sensors[tileDistance].angle; sensors[1].XPos = sensors[0].XPos; sensors[1].angle = sensors[0].angle; sensors[2].XPos = sensors[0].XPos; sensors[2].angle = sensors[0].angle; sensors[4].YPos = sensors[1].YPos; sensors[4].XPos = sensors[1].XPos - (collisionRight << 16); } if (sensors[0].angle > 0xE2) player->collisionMode = CMODE_FLOOR; if (sensors[0].angle < 0x9E) player->collisionMode = CMODE_ROOF; break; break; } case CMODE_ROOF: { sensors[3].XPos += cosValue256; sensors[3].YPos += sinValue256; if (player->speed > 0) RWallCollision(player, &sensors[3]); if (player->speed < 0) LWallCollision(player, &sensors[3]); if (sensors[3].collided) { cosValue256 = 0; checkDist = -1; } for (int32 i = 0; i < 3; i++) { sensors[i].XPos += cosValue256; sensors[i].YPos += sinValue256; FindRoofPosition(player, &sensors[i], sensors[i].YPos >> 16); } tileDistance = -1; for (int32 i = 0; i < 3; i++) { if (tileDistance > -1) { if (sensors[i].YPos > sensors[tileDistance].YPos && sensors[i].collided) { tileDistance = i; } } else if (sensors[i].collided) { tileDistance = i; } } if (tileDistance <= -1) { checkDist = -1; } else { sensors[0].YPos = sensors[tileDistance].YPos << 16; sensors[0].angle = sensors[tileDistance].angle; sensors[1].YPos = sensors[0].YPos; sensors[1].angle = sensors[0].angle; sensors[2].YPos = sensors[0].YPos; sensors[2].angle = sensors[0].angle; sensors[3].YPos = sensors[0].YPos + 0x40000; sensors[3].angle = sensors[0].angle; sensors[4].XPos = sensors[1].XPos; sensors[4].YPos = sensors[0].YPos - ((collisionTop - 1) << 16); } if (sensors[0].angle > 0xA2) player->collisionMode = CMODE_LWALL; if (sensors[0].angle < 0x5E) player->collisionMode = CMODE_RWALL; break; } case CMODE_RWALL: { sensors[3].XPos += cosValue256; sensors[3].YPos += sinValue256; if (player->speed > 0) FloorCollision(player, &sensors[3]); if (player->speed < 0) RoofCollision(player, &sensors[3]); if (sensors[3].collided) { sinValue256 = 0; checkDist = -1; } for (int32 i = 0; i < 3; i++) { sensors[i].XPos += cosValue256; sensors[i].YPos += sinValue256; FindRWallPosition(player, &sensors[i], sensors[i].XPos >> 16); } tileDistance = -1; for (int32 i = 0; i < 3; i++) { if (tileDistance > -1) { if (sensors[i].XPos > sensors[tileDistance].XPos && sensors[i].collided) { tileDistance = i; } } else if (sensors[i].collided) { tileDistance = i; } } if (tileDistance <= -1) { checkDist = -1; } else { sensors[0].XPos = sensors[tileDistance].XPos << 16; sensors[0].angle = sensors[tileDistance].angle; sensors[1].XPos = sensors[0].XPos; sensors[1].angle = sensors[0].angle; sensors[2].XPos = sensors[0].XPos; sensors[2].angle = sensors[0].angle; sensors[4].YPos = sensors[1].YPos; sensors[4].XPos = sensors[1].XPos - ((collisionLeft - 1) << 16); } if (sensors[0].angle < 0x1E) player->collisionMode = CMODE_FLOOR; if (sensors[0].angle > 0x62) player->collisionMode = CMODE_ROOF; break; } } if (tileDistance > -1) player->angle = sensors[0].angle; if (!sensors[3].collided) SetPathGripSensors(player); else checkDist = -2; } switch (cMode) { case CMODE_FLOOR: { if (sensors[0].collided || sensors[1].collided || sensors[2].collided) { player->angle = sensors[0].angle; player->boundEntity->rotation = player->angle << 1; player->flailing[0] = sensors[0].collided; player->flailing[1] = sensors[1].collided; player->flailing[2] = sensors[2].collided; if (!sensors[3].collided) { player->pushing = 0; player->XPos = sensors[4].XPos; } else { if (player->speed > 0) player->XPos = (sensors[3].XPos - collisionRight) << 16; if (player->speed < 0) player->XPos = (sensors[3].XPos - collisionLeft + 1) << 16; player->speed = 0; if ((player->left || player->right) && player->pushing < 2) player->pushing++; } player->YPos = sensors[4].YPos; return; } player->gravity = 1; player->collisionMode = CMODE_FLOOR; player->XVelocity = cos256LookupTable[player->angle] * player->speed >> 8; player->YVelocity = sin256LookupTable[player->angle] * player->speed >> 8; if (player->YVelocity < -0x100000) player->YVelocity = -0x100000; if (player->YVelocity > 0x100000) player->YVelocity = 0x100000; player->speed = player->XVelocity; player->angle = 0; if (!sensors[3].collided) { player->pushing = 0; player->XPos = player->XPos + player->XVelocity; } else { if (player->speed > 0) player->XPos = (sensors[3].XPos - collisionRight) << 16; if (player->speed < 0) player->XPos = (sensors[3].XPos - collisionLeft + 1) << 16; player->speed = 0; if ((player->left || player->right) && player->pushing < 2) player->pushing++; } player->YPos = player->YPos + player->YVelocity; return; } case CMODE_LWALL: { if (!sensors[0].collided && !sensors[1].collided && !sensors[2].collided) { player->gravity = 1; player->collisionMode = CMODE_FLOOR; player->XVelocity = cos256LookupTable[player->angle] * player->speed >> 8; player->YVelocity = sin256LookupTable[player->angle] * player->speed >> 8; if (player->YVelocity < -1048576) { player->YVelocity = -1048576; } if (player->YVelocity > 0x100000) { player->YVelocity = 0x100000; } player->speed = player->XVelocity; player->angle = 0; } else if (player->speed >= 0x28000 || player->speed <= -0x28000 || player->controlLock != 0) { player->angle = sensors[0].angle; player->boundEntity->rotation = player->angle << 1; } else { player->gravity = 1; player->angle = 0; player->collisionMode = CMODE_FLOOR; player->speed = player->XVelocity; player->controlLock = 30; } if (!sensors[3].collided) { player->YPos = sensors[4].YPos; } else { if (player->speed > 0) player->YPos = (sensors[3].YPos - collisionTop) << 16; if (player->speed < 0) player->YPos = (sensors[3].YPos - collisionBottom) << 16; player->speed = 0; } player->XPos = sensors[4].XPos; return; } case CMODE_ROOF: { if (!sensors[0].collided && !sensors[1].collided && !sensors[2].collided) { player->gravity = 1; player->collisionMode = CMODE_FLOOR; player->XVelocity = cos256LookupTable[player->angle] * player->speed >> 8; player->YVelocity = sin256LookupTable[player->angle] * player->speed >> 8; player->flailing[0] = 0; player->flailing[1] = 0; player->flailing[2] = 0; if (player->YVelocity < -0x100000) player->YVelocity = -0x100000; if (player->YVelocity > 0x100000) player->YVelocity = 0x100000; player->angle = 0; player->speed = player->XVelocity; if (!sensors[3].collided) { player->XPos = player->XPos + player->XVelocity; } else { if (player->speed > 0) player->XPos = (sensors[3].XPos - collisionRight) << 16; if (player->speed < 0) player->XPos = (sensors[3].XPos - collisionLeft + 1) << 16; player->speed = 0; } } else if (player->speed <= -0x28000 || player->speed >= 0x28000) { player->angle = sensors[0].angle; player->boundEntity->rotation = player->angle << 1; if (!sensors[3].collided) { player->XPos = sensors[4].XPos; } else { if (player->speed < 0) player->XPos = (sensors[3].XPos - collisionRight) << 16; if (player->speed > 0) player->XPos = (sensors[3].XPos - collisionLeft + 1) << 16; player->speed = 0; } } else { player->gravity = 1; player->angle = 0; player->collisionMode = CMODE_FLOOR; player->speed = player->XVelocity; player->flailing[0] = 0; player->flailing[1] = 0; player->flailing[2] = 0; if (!sensors[3].collided) { player->XPos = player->XPos + player->XVelocity; } else { if (player->speed > 0) player->XPos = (sensors[3].XPos - collisionRight) << 16; if (player->speed < 0) player->XPos = (sensors[3].XPos - collisionLeft + 1) << 16; player->speed = 0; } } player->YPos = sensors[4].YPos; return; } case CMODE_RWALL: { if (!sensors[0].collided && !sensors[1].collided && !sensors[2].collided) { player->gravity = 1; player->collisionMode = CMODE_FLOOR; player->XVelocity = cos256LookupTable[player->angle] * player->speed >> 8; player->YVelocity = sin256LookupTable[player->angle] * player->speed >> 8; if (player->YVelocity < -0x100000) player->YVelocity = -0x100000; if (player->YVelocity > 0x100000) player->YVelocity = 0x100000; player->speed = player->XVelocity; player->angle = 0; } else if (player->speed <= -0x28000 || player->speed >= 0x28000 || player->controlLock != 0) { player->angle = sensors[0].angle; player->boundEntity->rotation = player->angle << 1; } else { player->gravity = 1; player->angle = 0; player->collisionMode = CMODE_FLOOR; player->speed = player->XVelocity; player->controlLock = 30; } if (!sensors[3].collided) { player->YPos = sensors[4].YPos; } else { if (player->speed > 0) player->YPos = (sensors[3].YPos - collisionBottom) << 16; if (player->speed < 0) player->YPos = (sensors[3].YPos - collisionTop + 1) << 16; player->speed = 0; } player->XPos = sensors[4].XPos; return; } default: return; } } void RSDK::Legacy::v3::SetPathGripSensors(Player *player) { Hitbox *playerHitbox = GetPlayerHitbox(player); switch (player->collisionMode) { case CMODE_FLOOR: { collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; sensors[0].YPos = sensors[4].YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; sensors[3].YPos = sensors[4].YPos + 0x40000; sensors[0].XPos = sensors[4].XPos + ((playerHitbox->left[1] - 1) << 16); sensors[1].XPos = sensors[4].XPos; sensors[2].XPos = sensors[4].XPos + (playerHitbox->right[1] << 16); if (player->speed > 0) { sensors[3].XPos = sensors[4].XPos + ((collisionRight + 1) << 16); return; } sensors[3].XPos = sensors[4].XPos + ((collisionLeft - 1) << 16); return; } case CMODE_LWALL: { collisionLeft = playerHitbox->left[2]; collisionTop = playerHitbox->top[2]; collisionRight = playerHitbox->right[2]; collisionBottom = playerHitbox->bottom[2]; sensors[0].XPos = sensors[4].XPos + (collisionRight << 16); sensors[1].XPos = sensors[0].XPos; sensors[2].XPos = sensors[0].XPos; sensors[3].XPos = sensors[4].XPos + 0x40000; sensors[0].YPos = sensors[4].YPos + ((playerHitbox->top[3] - 1) << 16); sensors[1].YPos = sensors[4].YPos; sensors[2].YPos = sensors[4].YPos + (playerHitbox->bottom[3] << 16); if (player->speed > 0) { sensors[3].YPos = sensors[4].YPos + (collisionTop << 16); return; } sensors[3].YPos = sensors[4].YPos + ((collisionBottom - 1) << 16); return; } case CMODE_ROOF: { collisionLeft = playerHitbox->left[4]; collisionTop = playerHitbox->top[4]; collisionRight = playerHitbox->right[4]; collisionBottom = playerHitbox->bottom[4]; sensors[0].YPos = sensors[4].YPos + ((collisionTop - 1) << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; sensors[3].YPos = sensors[4].YPos - 0x40000; sensors[0].XPos = sensors[4].XPos + ((playerHitbox->left[5] - 1) << 16); sensors[1].XPos = sensors[4].XPos; sensors[2].XPos = sensors[4].XPos + (playerHitbox->right[5] << 16); if (player->speed < 0) { sensors[3].XPos = sensors[4].XPos + ((collisionRight + 1) << 16); return; } sensors[3].XPos = sensors[4].XPos + ((collisionLeft - 1) << 16); return; } case CMODE_RWALL: { collisionLeft = playerHitbox->left[6]; collisionTop = playerHitbox->top[6]; collisionRight = playerHitbox->right[6]; collisionBottom = playerHitbox->bottom[6]; sensors[0].XPos = sensors[4].XPos + ((collisionLeft - 1) << 16); sensors[1].XPos = sensors[0].XPos; sensors[2].XPos = sensors[0].XPos; sensors[3].XPos = sensors[4].XPos - 0x40000; sensors[0].YPos = sensors[4].YPos + ((playerHitbox->top[7] - 1) << 16); sensors[1].YPos = sensors[4].YPos; sensors[2].YPos = sensors[4].YPos + (playerHitbox->bottom[7] << 16); if (player->speed > 0) { sensors[3].YPos = sensors[4].YPos + (collisionBottom << 16); return; } sensors[3].YPos = sensors[4].YPos + ((collisionTop - 1) << 16); return; } default: return; } } void RSDK::Legacy::v3::ProcessPlayerTileCollisions(Player *player) { player->flailing[0] = 0; player->flailing[1] = 0; player->flailing[2] = 0; scriptEng.checkResult = false; if (player->gravity == 1) ProcessAirCollision(player); else ProcessPathGrip(player); } void RSDK::Legacy::v3::ObjectFloorCollision(int32 xOffset, int32 yOffset, int32 cPath) { scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 c = 0; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = (stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6) + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] != SOLID_LRB && tiles128x128.collisionFlags[cPath][chunk] != SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (XPos & 15) + (tileIndex << 4); if ((YPos & 15) <= collisionMasks[cPath].floorMasks[c]) { break; } YPos = collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 1: { c = 15 - (XPos & 15) + (tileIndex << 4); if ((YPos & 15) <= collisionMasks[cPath].floorMasks[c]) { break; } YPos = collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 2: { c = (XPos & 15) + (tileIndex << 4); if ((YPos & 15) <= 15 - collisionMasks[cPath].roofMasks[c]) { break; } YPos = 15 - collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (XPos & 15) + (tileIndex << 4); if ((YPos & 15) <= 15 - collisionMasks[cPath].roofMasks[c]) { break; } YPos = 15 - collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } } } if (scriptEng.checkResult) { entity->YPos = (YPos - yOffset) << 16; } } } void RSDK::Legacy::v3::ObjectLWallCollision(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; chunk = chunk + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] != SOLID_TOP && tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (YPos & 15) + (tileIndex << 4); if ((XPos & 15) <= collisionMasks[cPath].lWallMasks[c]) { break; } XPos = collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 1: { c = (YPos & 15) + (tileIndex << 4); if ((XPos & 15) <= 15 - collisionMasks[cPath].rWallMasks[c]) { break; } XPos = 15 - collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 2: { c = 15 - (YPos & 15) + (tileIndex << 4); if ((XPos & 15) <= collisionMasks[cPath].lWallMasks[c]) { break; } XPos = collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (YPos & 15) + (tileIndex << 4); if ((XPos & 15) <= 15 - collisionMasks[cPath].rWallMasks[c]) { break; } XPos = 15 - collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } } } if (scriptEng.checkResult) { entity->XPos = (XPos - xOffset) << 16; } } } void RSDK::Legacy::v3::ObjectRoofCollision(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; chunk = chunk + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] != SOLID_TOP && tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (XPos & 15) + (tileIndex << 4); if ((YPos & 15) >= collisionMasks[cPath].roofMasks[c]) { break; } YPos = collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 1: { c = 15 - (XPos & 15) + (tileIndex << 4); if ((YPos & 15) >= collisionMasks[cPath].roofMasks[c]) { break; } YPos = collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 2: { c = (XPos & 15) + (tileIndex << 4); if ((YPos & 15) >= 15 - collisionMasks[cPath].floorMasks[c]) { break; } YPos = 15 - collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (XPos & 15) + (tileIndex << 4); if ((YPos & 15) >= 15 - collisionMasks[cPath].floorMasks[c]) { break; } YPos = 15 - collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } } } if (scriptEng.checkResult) { entity->YPos = (YPos - yOffset) << 16; } } } void RSDK::Legacy::v3::ObjectRWallCollision(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6; chunk = chunk + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] != SOLID_TOP && tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (YPos & 15) + (tileIndex << 4); if ((XPos & 15) >= collisionMasks[cPath].rWallMasks[c]) { break; } XPos = collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 1: { c = (YPos & 15) + (tileIndex << 4); if ((XPos & 15) >= 15 - collisionMasks[cPath].lWallMasks[c]) { break; } XPos = 15 - collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 2: { c = 15 - (YPos & 15) + (tileIndex << 4); if ((XPos & 15) >= collisionMasks[cPath].rWallMasks[c]) { break; } XPos = collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (YPos & 15) + (tileIndex << 4); if ((XPos & 15) >= 15 - collisionMasks[cPath].lWallMasks[c]) { break; } XPos = 15 - collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } } } if (scriptEng.checkResult) { entity->XPos = (XPos - xOffset) << 16; } } } void RSDK::Legacy::v3::ObjectFloorGrip(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; int32 chunkX = YPos; YPos = YPos - 16; for (int32 i = 3; i > 0; i--) { if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7 && !scriptEng.checkResult) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = (stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6) + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] != SOLID_LRB && tiles128x128.collisionFlags[cPath][chunk] != SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].floorMasks[c] >= 64) { break; } entity->YPos = collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 1: { c = 15 - (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].floorMasks[c] >= 64) { break; } entity->YPos = collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 2: { c = (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].roofMasks[c] <= -64) { break; } entity->YPos = 15 - collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].roofMasks[c] <= -64) { break; } entity->YPos = 15 - collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } } } } YPos += 16; } if (scriptEng.checkResult) { if (abs(entity->YPos - chunkX) < 16) { entity->YPos = (entity->YPos - yOffset) << 16; return; } entity->YPos = (chunkX - yOffset) << 16; scriptEng.checkResult = false; } } void RSDK::Legacy::v3::ObjectLWallGrip(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; int32 startX = XPos; XPos = XPos - 16; int32 chunk = xOffset; for (int32 i = 3; i > 0; i--) { if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7 && !scriptEng.checkResult) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; chunk = (stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6) + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].lWallMasks[c] >= 64) { break; } entity->XPos = collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 1: { c = (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].rWallMasks[c] <= -64) { break; } entity->XPos = 15 - collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 2: { c = 15 - (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].lWallMasks[c] >= 64) { break; } entity->XPos = collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].rWallMasks[c] <= -64) { break; } entity->XPos = 15 - collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } } } } XPos += 16; } if (scriptEng.checkResult) { if (abs(entity->XPos - startX) < 16) { entity->XPos = (entity->XPos - xOffset) << 16; return; } entity->XPos = (startX - xOffset) << 16; scriptEng.checkResult = tiles128x128.collisionFlags[cPath][chunk] == 1; } } void RSDK::Legacy::v3::ObjectRoofGrip(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; int32 startY = YPos; YPos = YPos + 16; for (int32 i = 3; i > 0; i--) { if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7 && !scriptEng.checkResult) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; int32 chunk = (stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6) + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].roofMasks[c] <= -64) { break; } entity->YPos = collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 1: { c = 15 - (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].roofMasks[c] <= -64) { break; } entity->YPos = collisionMasks[cPath].roofMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 2: { c = (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].floorMasks[c] >= 64) { break; } entity->YPos = 15 - collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (XPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].floorMasks[c] >= 64) { break; } entity->YPos = 15 - collisionMasks[cPath].floorMasks[c] + (chunkY << 7) + (tileY << 4); scriptEng.checkResult = true; break; } } } } YPos -= 16; } if (scriptEng.checkResult) { if (abs(entity->YPos - startY) < 16) { entity->YPos = (entity->YPos - yOffset) << 16; return; } entity->YPos = (startY - yOffset) << 16; scriptEng.checkResult = false; } } void RSDK::Legacy::v3::ObjectRWallGrip(int32 xOffset, int32 yOffset, int32 cPath) { int32 c; scriptEng.checkResult = false; Entity *entity = &objectEntityList[objectLoop]; int32 XPos = (entity->XPos >> 16) + xOffset; int32 YPos = (entity->YPos >> 16) + yOffset; int32 startX = XPos; XPos = XPos + 16; int32 chunk = xOffset; for (int32 i = 3; i > 0; i--) { if (XPos > 0 && XPos < stageLayouts[0].xsize << 7 && YPos > 0 && YPos < stageLayouts[0].ysize << 7 && !scriptEng.checkResult) { int32 chunkX = XPos >> 7; int32 tileX = (XPos & 0x7F) >> 4; int32 chunkY = YPos >> 7; int32 tileY = (YPos & 0x7F) >> 4; chunk = (stageLayouts[0].tiles[chunkX + (chunkY << 8)] << 6) + tileX + (tileY << 3); int32 tileIndex = tiles128x128.tileIndex[chunk]; if (tiles128x128.collisionFlags[cPath][chunk] < SOLID_NONE) { switch (tiles128x128.direction[chunk]) { case 0: { c = (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].rWallMasks[c] <= -64) { break; } entity->XPos = collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 1: { c = (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].lWallMasks[c] >= 64) { break; } entity->XPos = 15 - collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 2: { c = 15 - (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].rWallMasks[c] <= -64) { break; } entity->XPos = collisionMasks[cPath].rWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } case 3: { c = 15 - (YPos & 15) + (tileIndex << 4); if (collisionMasks[cPath].lWallMasks[c] >= 64) { break; } entity->XPos = 15 - collisionMasks[cPath].lWallMasks[c] + (chunkX << 7) + (tileX << 4); scriptEng.checkResult = true; break; } } } } XPos -= 16; } if (scriptEng.checkResult) { if (abs(entity->XPos - startX) < 16) { entity->XPos = (entity->XPos - xOffset) << 16; return; } entity->XPos = (startX - xOffset) << 16; scriptEng.checkResult = tiles128x128.collisionFlags[cPath][chunk] == 1; } } void RSDK::Legacy::v3::ObjectEntityGrip(int32 direction, int32 extendBottomCol, int32 effect) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; int32 storePos = 0; int32 storeCount = 0; scriptEng.checkResult = false; for (int32 i = 0; i < COLSTORE_COUNT; i++) { if (collisionStorage[i].entityNo != -1) { storeCount++; storePos = i; scriptEng.checkResult = true; } } switch (effect) { case ECEFFECT_NONE: case ECEFFECT_RESETSTORAGE: { if (storeCount == 1) { scriptEng.checkResult = false; int32 extendedBottomCol = extendBottomCol ? collisionBottom + 5 : -5; Entity *entity = &objectEntityList[collisionStorage[storePos].entityNo]; int32 yCheck1 = ((collisionStorage[storePos].top + extendedBottomCol) << 16) + entity->YPos; int32 yCheck2 = ((collisionStorage[storePos].bottom + extendedBottomCol) << 16) + entity->YPos; int32 xCheck1 = (collisionStorage[storePos].left << 16) + entity->XPos; int32 xCheck2 = (collisionStorage[storePos].right << 16) + entity->XPos; if (direction) { if (((collisionLeft << 16) + player->XPos) <= xCheck2 && xCheck2 < (player->XPos - player->XVelocity)) { if (yCheck1 < (player->YPos + (collisionBottom << 16)) && (player->YPos + (collisionTop << 16)) < yCheck2) { player->XPos = xCheck2 - (collisionLeft << 16); scriptEng.checkResult = true; } else { if (effect == ECEFFECT_RESETSTORAGE) { for (int32 i = 0; i < COLSTORE_COUNT; i++) { CollisionStore *entityHitbox = &collisionStorage[i]; entityHitbox->entityNo = -1; entityHitbox->type = -1; entityHitbox->left = 0; entityHitbox->top = 0; entityHitbox->right = 0; entityHitbox->bottom = 0; } } } } } else { if (((collisionRight << 16) + player->XPos) >= xCheck1 && xCheck1 > (player->XPos - player->XVelocity)) { player->XPos = xCheck1 - (collisionRight << 16); if (yCheck1 < (player->YPos + (collisionBottom << 16)) && (player->YPos + (collisionTop << 16)) < yCheck2) { scriptEng.checkResult = true; player->XPos = xCheck1 - (collisionRight << 16); } else { if (effect == ECEFFECT_RESETSTORAGE) { for (int32 i = 0; i < COLSTORE_COUNT; i++) { CollisionStore *entityHitbox = &collisionStorage[i]; entityHitbox->entityNo = -1; entityHitbox->type = -1; entityHitbox->left = 0; entityHitbox->top = 0; entityHitbox->right = 0; entityHitbox->bottom = 0; } } } } } } else { if (effect == ECEFFECT_RESETSTORAGE) { for (int32 i = 0; i < COLSTORE_COUNT; i++) { CollisionStore *entityHitbox = &collisionStorage[i]; entityHitbox->entityNo = -1; entityHitbox->type = -1; entityHitbox->left = 0; entityHitbox->top = 0; entityHitbox->right = 0; entityHitbox->bottom = 0; } } } break; } case ECEFFECT_BOXCOL3: { CollisionStore *entityHitbox = &collisionStorage[storePos]; for (int32 o = 0; o < LEGACY_v3_ENTITY_COUNT; o++) { Entity *entity = &objectEntityList[o]; if (entityHitbox->type == entity->type) { BoxCollision3(entity->XPos + (entityHitbox->left << 16), entity->YPos + (entityHitbox->top << 16), entity->XPos + (entityHitbox->right << 16), entity->YPos + (entityHitbox->bottom << 16)); } } break; } default: break; } } void RSDK::Legacy::v3::TouchCollision(int32 left, int32 top, int32 right, int32 bottom) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = player->XPos >> 16; collisionTop = player->YPos >> 16; collisionRight = collisionLeft; collisionBottom = collisionTop; collisionLeft += playerHitbox->left[0]; collisionTop += playerHitbox->top[0]; collisionRight += playerHitbox->right[0]; collisionBottom += playerHitbox->bottom[0]; scriptEng.checkResult = collisionRight > left && collisionLeft < right && collisionBottom > top && collisionTop < bottom; #if !RETRO_USE_ORIGINAL_CODE if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos >> 16; top -= entity->YPos >> 16; right -= entity->XPos >> 16; bottom -= entity->YPos >> 16; int32 thisHitboxID = AddDebugHitbox(H_TYPE_TOUCH, entity, left, top, right, bottom); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1; int32 otherHitboxID = AddDebugHitbox(H_TYPE_TOUCH, NULL, playerHitbox->left[0], playerHitbox->top[0], playerHitbox->right[0], playerHitbox->bottom[0]); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1; } } #endif } void RSDK::Legacy::v3::BoxCollision(int32 left, int32 top, int32 right, int32 bottom) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; scriptEng.checkResult = false; int32 spd = 0; switch (player->collisionMode) { case CMODE_FLOOR: case CMODE_ROOF: if (player->XVelocity) spd = abs(player->XVelocity); else spd = abs(player->speed); break; case CMODE_LWALL: case CMODE_RWALL: spd = abs(player->XVelocity); break; default: break; } if (spd <= abs(player->YVelocity)) { sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; if (player->YVelocity > -1) { for (int32 i = 0; i < 3; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos >= top && player->YPos - player->YVelocity < top) { sensors[i].collided = true; player->flailing[i] = true; } } } if (sensors[2].collided || sensors[1].collided || sensors[0].collided) { if (!player->gravity && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->YPos = top - (collisionBottom << 16); player->gravity = 0; player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = true; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionTop << 16); sensors[1].YPos = sensors[0].YPos; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos <= bottom && player->YPos - player->YVelocity > bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { if (player->gravity == 1) { player->YPos = bottom - (collisionTop << 16); } if (player->YVelocity < 1) player->YVelocity = 0; scriptEng.checkResult = 4; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionRight << 16); sensors[1].XPos = sensors[0].XPos; sensors[0].YPos = player->YPos - 0x20000; sensors[1].YPos = player->YPos + 0x80000; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos >= left && player->XPos - player->XVelocity < left && sensors[1].YPos > top && sensors[0].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = left - (collisionRight << 16); if (player->XVelocity > 0) { if (!player->boundEntity->direction) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 2; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionLeft << 16); sensors[1].XPos = sensors[0].XPos; sensors[0].YPos = player->YPos - 0x20000; sensors[1].YPos = player->YPos + 0x80000; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos <= right && player->XPos - player->XVelocity > right && sensors[1].YPos > top && sensors[0].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || (sensors[0].collided)) { player->XPos = right - (collisionLeft << 16); if (player->XVelocity < 0) { if (player->boundEntity->direction == FLIP_X) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 3; } } } } } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionRight << 16); sensors[1].XPos = sensors[0].XPos; sensors[0].YPos = player->YPos - 0x20000; sensors[1].YPos = player->YPos + 0x80000; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos >= left && player->XPos - player->XVelocity < left && sensors[1].YPos > top && sensors[0].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = left - (collisionRight << 16); if (player->XVelocity > 0) { if (!player->boundEntity->direction) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 2; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionLeft << 16); sensors[1].XPos = sensors[0].XPos; sensors[0].YPos = player->YPos - 0x20000; sensors[1].YPos = player->YPos + 0x80000; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos <= right && player->XPos - player->XVelocity > right && sensors[1].YPos > top && sensors[0].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = right - (collisionLeft << 16); if (player->XVelocity < 0) { if (player->boundEntity->direction == FLIP_X) { player->pushing = 2; } player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 3; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; if (player->YVelocity > -1) { for (int32 i = 0; i < 3; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos >= top && player->YPos - player->YVelocity < top) { sensors[i].collided = true; player->flailing[i] = true; } } } if (sensors[2].collided || sensors[1].collided || sensors[0].collided) { if (!player->gravity && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->YPos = top - (collisionBottom << 16); player->gravity = 0; player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = true; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionTop << 16); sensors[1].YPos = sensors[0].YPos; for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos <= bottom && player->YPos - player->YVelocity > bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { if (player->gravity == 1) { player->YPos = bottom - (collisionTop << 16); } if (player->YVelocity < 1) player->YVelocity = 0; scriptEng.checkResult = 4; } } } } } #if !RETRO_USE_ORIGINAL_CODE int32 thisHitboxID = 0; if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos; top -= entity->YPos; right -= entity->XPos; bottom -= entity->YPos; thisHitboxID = AddDebugHitbox(H_TYPE_BOX, &objectEntityList[objectLoop], left >> 16, top >> 16, right >> 16, bottom >> 16); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1 << (scriptEng.checkResult - 1); int32 otherHitboxID = AddDebugHitbox(H_TYPE_BOX, NULL, playerHitbox->left[0], playerHitbox->top[0], playerHitbox->right[0], playerHitbox->bottom[0]); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1 << (4 - scriptEng.checkResult); } } #endif } void RSDK::Legacy::v3::BoxCollision2(int32 left, int32 top, int32 right, int32 bottom) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; scriptEng.checkResult = false; int32 spd = 0; switch (player->collisionMode) { case CMODE_FLOOR: case CMODE_ROOF: if (player->XVelocity) spd = abs(player->XVelocity); else spd = abs(player->speed); break; case CMODE_LWALL: case CMODE_RWALL: spd = abs(player->XVelocity); break; default: break; } if (spd <= abs(player->YVelocity)) { sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; if (player->YVelocity > -1) { for (int32 i = 0; i < 3; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos >= top && player->YPos - player->YVelocity < top) { sensors[i].collided = true; player->flailing[i] = true; } } } if (sensors[2].collided || sensors[1].collided || sensors[0].collided) { if (!player->gravity && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->YPos = top - (collisionBottom << 16); player->gravity = 0; player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = 1; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionTop << 16); sensors[1].YPos = player->YPos + (collisionTop << 16); for (int32 i = 0; i < 2; ++i) { if (left < sensors[i].XPos && right > sensors[i].XPos && bottom >= sensors[i].YPos && bottom < player->YPos - player->YVelocity) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { if (player->gravity == 1) player->YPos = bottom - (collisionTop << 16); if (player->YVelocity < 1) player->YVelocity = 0; scriptEng.checkResult = 4; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionRight << 16); sensors[1].XPos = player->XPos + (collisionRight << 16); sensors[0].YPos = player->YPos + ((collisionBottom - 2) << 16); sensors[1].YPos = player->YPos + ((collisionTop + 2) << 16); for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos >= left && player->XPos - player->XVelocity < left && sensors[0].YPos > top && sensors[1].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = left - (collisionRight << 16); if (player->XVelocity > 0) { if (player->boundEntity->direction == FLIP_NONE) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 2; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = sensors[0].XPos; sensors[1].XPos = player->XPos + (collisionLeft << 16); sensors[0].YPos = player->YPos + ((collisionBottom - 2) << 16); sensors[1].YPos = player->YPos + ((collisionTop + 2) << 16); for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos <= right && player->XPos - player->XVelocity > right && sensors[0].YPos > top && sensors[1].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || (sensors[0].collided)) { player->XPos = right - (collisionLeft << 16); if (player->XVelocity < 0) { if (player->boundEntity->direction == FLIP_X) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 3; } } } } } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + (collisionRight << 16); sensors[1].XPos = player->XPos + (collisionRight << 16); sensors[0].YPos = player->YPos + ((collisionBottom - 2) << 16); sensors[1].YPos = player->YPos + ((collisionTop + 2) << 16); for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos >= left && player->XPos - player->XVelocity < left && sensors[0].YPos > top && sensors[1].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = left - (collisionRight << 16); if (player->XVelocity > 0) { if (!player->boundEntity->direction) player->pushing = 2; player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 2; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = sensors[0].XPos; sensors[1].XPos = player->XPos + (collisionLeft << 16); sensors[0].YPos = player->YPos + ((collisionBottom - 2) << 16); sensors[1].YPos = player->YPos + ((collisionTop + 2) << 16); for (int32 i = 0; i < 2; ++i) { if (sensors[i].XPos <= right && player->XPos - player->XVelocity > right && sensors[0].YPos > top && sensors[1].YPos < bottom) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { player->XPos = right - (collisionLeft << 16); if (player->XVelocity < 0) { if (player->boundEntity->direction == FLIP_X) { player->pushing = 2; } player->XVelocity = 0; player->speed = 0; } scriptEng.checkResult = 3; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; if (player->YVelocity > -1) { for (int32 i = 0; i < 3; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos >= top && player->YPos - player->YVelocity < top) { sensors[i].collided = true; player->flailing[i] = true; } } } if (sensors[2].collided || sensors[1].collided || sensors[0].collided) { if (!player->gravity && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->YPos = top - (collisionBottom << 16); player->gravity = 0; player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = 1; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionTop << 16); sensors[1].YPos = player->YPos + (collisionTop << 16); for (int32 i = 0; i < 2; ++i) { if (left < sensors[i].XPos && right > sensors[i].XPos && bottom >= sensors[i].YPos && bottom < player->YPos - player->YVelocity) { sensors[i].collided = true; } } if (sensors[1].collided || sensors[0].collided) { if (player->gravity == 1) { player->YPos = bottom - (collisionTop << 16); } if (player->YVelocity < 1) player->YVelocity = 0; scriptEng.checkResult = 4; } } } } } #if !RETRO_USE_ORIGINAL_CODE int32 thisHitboxID = 0; if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos; top -= entity->YPos; right -= entity->XPos; bottom -= entity->YPos; thisHitboxID = AddDebugHitbox(H_TYPE_BOX, &objectEntityList[objectLoop], left >> 16, top >> 16, right >> 16, bottom >> 16); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1 << (scriptEng.checkResult - 1); int32 otherHitboxID = AddDebugHitbox(H_TYPE_BOX, NULL, playerHitbox->left[0], playerHitbox->top[0], playerHitbox->right[0], playerHitbox->bottom[0]); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1 << (4 - scriptEng.checkResult); } } #endif } void RSDK::Legacy::v3::PlatformCollision(int32 left, int32 top, int32 right, int32 bottom) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 1) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + (collisionRight << 16); sensors[0].YPos = player->YPos + (collisionBottom << 16); sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; scriptEng.checkResult = false; for (int32 i = 0; i < 3; ++i) { if (sensors[i].XPos > left && sensors[i].XPos < right && sensors[i].YPos > top - 2 && sensors[i].YPos < bottom && player->YVelocity >= 0) { sensors[i].collided = 1; player->flailing[i] = 1; } } if (sensors[0].collided || sensors[1].collided || sensors[2].collided) { if (!player->gravity && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->YPos = top - (collisionBottom << 16); player->gravity = 0; player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = true; } #if !RETRO_USE_ORIGINAL_CODE int32 thisHitboxID = 0; if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos; top -= entity->YPos; right -= entity->XPos; bottom -= entity->YPos; thisHitboxID = AddDebugHitbox(H_TYPE_PLAT, &objectEntityList[objectLoop], left >> 16, top >> 16, right >> 16, bottom >> 16); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1 << 0; int32 otherHitboxID = AddDebugHitbox(H_TYPE_PLAT, NULL, playerHitbox->left[0], playerHitbox->top[0], playerHitbox->right[0], playerHitbox->bottom[0]); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1 << 3; } } #endif } void RSDK::Legacy::v3::BoxCollision3(int32 left, int32 top, int32 right, int32 bottom) { Player *player = &playerList[activePlayer]; Hitbox *playerHitbox = GetPlayerHitbox(player); collisionLeft = playerHitbox->left[0]; collisionTop = playerHitbox->top[0]; collisionRight = playerHitbox->right[0]; collisionBottom = playerHitbox->bottom[0]; scriptEng.checkResult = false; sensors[0].collided = false; sensors[1].collided = false; sensors[2].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos; sensors[2].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = (collisionBottom << 16) + player->YPos; sensors[1].YPos = sensors[0].YPos; sensors[2].YPos = sensors[0].YPos; if (player->YVelocity > -1) { for (int32 i = 0; i < 3; ++i) { if ((left < sensors[i].XPos) && (sensors[i].XPos < right) && (top <= sensors[i].YPos) && ((player->YPos - player->YVelocity) < top)) { sensors[i].collided = true; player->flailing[i] = 1; } } } if (sensors[0].collided || sensors[1].collided || sensors[2].collided) { if ((!player->gravity) && (player->collisionMode == CMODE_RWALL || player->collisionMode == CMODE_LWALL)) { player->XVelocity = 0; player->speed = 0; } player->gravity = 0; player->YPos = top - (collisionBottom << 16); player->YVelocity = 0; player->angle = 0; player->boundEntity->rotation = 0; player->controlLock = 0; scriptEng.checkResult = true; } else { sensors[0].collided = false; sensors[1].collided = false; sensors[0].XPos = player->XPos + ((collisionLeft + 2) << 16); sensors[1].XPos = player->XPos + ((collisionRight - 2) << 16); sensors[0].YPos = player->YPos + (collisionTop << 16); sensors[1].YPos = sensors[0].YPos; for (int32 i = 0; i < 2; ++i) { if ((left < sensors[i].XPos && sensors[i].XPos < right) && (sensors[i].YPos <= bottom && bottom < player->YPos - player->YVelocity)) { sensors[i].collided = true; } } if (sensors[0].collided || sensors[1].collided) { if (player->gravity == 1) { player->YPos = bottom - (collisionTop << 16); } if (player->YVelocity < 1) { player->YVelocity = 0; } scriptEng.checkResult = 4; } else { sensors[0].collided = false; sensors[1].collided = false; if (left <= (player->XPos + (collisionRight << 16)) && (player->XPos - player->XVelocity) < left) { for (int32 i = 0; i < 2; ++i) { if (top < (player->YPos + (collisionBottom << 16)) && sensors[i].YPos < bottom) { sensors[i].collided = true; } } } if (sensors[0].collided || sensors[1].collided) { scriptEng.checkResult = 2; player->XPos = left - (collisionRight << 16); for (int32 i = 0; i < COLSTORE_COUNT; i++) { CollisionStore *entityHitbox = &collisionStorage[i]; if (entityHitbox->entityNo == objectLoop) break; if (entityHitbox->entityNo == -1) { entityHitbox->entityNo = objectLoop; entityHitbox->type = objectEntityList[objectLoop].type; entityHitbox->left = scriptEng.operands[1]; entityHitbox->top = scriptEng.operands[2]; entityHitbox->right = scriptEng.operands[3]; entityHitbox->bottom = scriptEng.operands[4]; break; } } } else { sensors[0].collided = false; sensors[1].collided = false; if (((collisionLeft << 16) + player->XPos) <= right && right < (player->XPos - player->XVelocity)) { for (int32 i = 0; i < 2; ++i) { if (top < ((collisionBottom << 16) + player->YPos) && sensors[i].YPos < bottom) { sensors[i].collided = true; } } } if (sensors[0].collided || sensors[1].collided) { scriptEng.checkResult = 3; player->XPos = right - (collisionLeft << 16); for (int32 i = 0; i < COLSTORE_COUNT; i++) { CollisionStore *entityHitbox = &collisionStorage[i]; if (entityHitbox->entityNo == objectLoop) break; if (entityHitbox->entityNo == -1) { entityHitbox->entityNo = objectLoop; entityHitbox->type = objectEntityList[objectLoop].type; entityHitbox->left = scriptEng.operands[1]; entityHitbox->top = scriptEng.operands[2]; entityHitbox->right = scriptEng.operands[3]; entityHitbox->bottom = scriptEng.operands[4]; break; } } } } } } #if !RETRO_USE_ORIGINAL_CODE int32 thisHitboxID = 0; if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos; top -= entity->YPos; right -= entity->XPos; bottom -= entity->YPos; thisHitboxID = AddDebugHitbox(H_TYPE_BOX, &objectEntityList[objectLoop], left >> 16, top >> 16, right >> 16, bottom >> 16); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1 << 0; int32 otherHitboxID = AddDebugHitbox(H_TYPE_BOX, NULL, playerHitbox->left[0], playerHitbox->top[0], playerHitbox->right[0], playerHitbox->bottom[0]); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1 << 3; } } #endif } // Note for those that care: This is not a direct decomp of this function // We did try to make one, but the original function was too much of a mess to comprehend fully, so we opted to instead take what we could understand // from it and make a new one that replicates the behavior the best we could. If anyone out there wants to take a shot at fully decompiling the // original function, feel free to do so and send a PR, but this should be good enough as is void RSDK::Legacy::v3::EnemyCollision(int32 left, int32 top, int32 right, int32 bottom) { TouchCollision(left, top, right, bottom); #if RSDK_AUTOBUILD // Skip the hammer hitboxes on autobuilds, just in case return; #endif Player *player = &playerList[activePlayer]; int32 hammerHitboxLeft = 0; int32 hammerHitboxRight = 0; int32 hammerHitboxTop = 0; int32 hammerHitboxBottom = 0; #if !RETRO_USE_ORIGINAL_CODE bool32 miniPlayerFlag = GetGlobalVariableByName("Mini_PlayerFlag"); int8 playerAmy = GetGlobalVariableByName("PLAYER_AMY") ? GetGlobalVariableByName("PLAYER_AMY") : 5; int8 aniHammerJump = GetGlobalVariableByName("ANI_HAMMER_JUMP") ? GetGlobalVariableByName("ANI_HAMMER_JUMP") : 45; int8 aniHammerDash = GetGlobalVariableByName("ANI_HAMMER_DASH") ? GetGlobalVariableByName("ANI_HAMMER_DASH") : 46; #else bool32 mini_PlayerFlag = globalVariables[62]; int8 playerAmy = 5; int8 aniHammerJump = 45; int8 aniHammerDash = 46; #endif collisionLeft = player->XPos >> 16; collisionTop = player->YPos >> 16; collisionRight = collisionLeft; collisionBottom = collisionTop; if (!scriptEng.checkResult) { if (playerListPos == playerAmy) { if (player->boundEntity->animation == aniHammerDash) { int32 frame = (miniPlayerFlag ? player->boundEntity->frame % 3 : player->boundEntity->frame % 8) * 4; hammerHitboxLeft = miniPlayerFlag ? chibiHammerDashHitbox[frame] : hammerDashHitbox[frame]; hammerHitboxTop = miniPlayerFlag ? chibiHammerDashHitbox[frame + 1] : hammerDashHitbox[frame + 1]; hammerHitboxRight = miniPlayerFlag ? chibiHammerDashHitbox[frame + 2] : hammerDashHitbox[frame + 2]; hammerHitboxBottom = miniPlayerFlag ? chibiHammerDashHitbox[frame + 3] : hammerDashHitbox[frame + 3]; } if (player->boundEntity->animation == aniHammerJump) { int32 frame = (miniPlayerFlag ? player->boundEntity->frame % 2 : player->boundEntity->frame % 4) * 4; hammerHitboxLeft = miniPlayerFlag ? chibiHammerJumpHitbox[frame] : hammerJumpHitbox[frame]; hammerHitboxTop = miniPlayerFlag ? chibiHammerJumpHitbox[frame + 1] : hammerJumpHitbox[frame + 1]; hammerHitboxRight = miniPlayerFlag ? chibiHammerJumpHitbox[frame + 2] : hammerJumpHitbox[frame + 2]; hammerHitboxBottom = miniPlayerFlag ? chibiHammerJumpHitbox[frame + 3] : hammerJumpHitbox[frame + 3]; } if (player->boundEntity->direction) { int32 storeHitboxLeft = hammerHitboxLeft; hammerHitboxLeft = -hammerHitboxRight; hammerHitboxRight = -storeHitboxLeft; } scriptEng.checkResult = collisionRight + hammerHitboxRight > left && collisionLeft + hammerHitboxLeft < right && collisionBottom + hammerHitboxBottom > top && collisionTop + hammerHitboxTop < bottom; } } #if !RETRO_USE_ORIGINAL_CODE if (showHitboxes) { Entity *entity = &objectEntityList[objectLoop]; left -= entity->XPos >> 16; top -= entity->YPos >> 16; right -= entity->XPos >> 16; bottom -= entity->YPos >> 16; Hitbox *playerHitbox = GetPlayerHitbox(player); int32 thisHitboxID = AddDebugHitbox(H_TYPE_HAMMER, entity, left, top, right, bottom); if (thisHitboxID >= 0 && scriptEng.checkResult) debugHitboxList[thisHitboxID].collision |= 1; int32 otherHitboxID = AddDebugHitbox(H_TYPE_HAMMER, NULL, hammerHitboxLeft, hammerHitboxTop, hammerHitboxRight, hammerHitboxBottom); if (otherHitboxID >= 0) { debugHitboxList[otherHitboxID].pos.x = player->XPos; debugHitboxList[otherHitboxID].pos.y = player->YPos; if (scriptEng.checkResult) debugHitboxList[otherHitboxID].collision |= 1; } } #endif }
412
0.675043
1
0.675043
game-dev
MEDIA
0.972227
game-dev
0.955187
1
0.955187
open-osrs/runelite
12,625
runelite-client/src/main/java/net/runelite/client/game/LootManager.java
/* * Copyright (c) 2018, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.game; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import lombok.extern.slf4j.Slf4j; import net.runelite.api.AnimationID; import net.runelite.api.Client; import net.runelite.api.ItemID; import net.runelite.api.NPC; import net.runelite.api.NPCComposition; import net.runelite.api.NpcID; import net.runelite.api.Player; import net.runelite.api.Tile; import net.runelite.api.TileItem; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.ItemDespawned; import net.runelite.api.events.ItemQuantityChanged; import net.runelite.api.events.ItemSpawned; import net.runelite.api.events.NpcChanged; import net.runelite.api.events.NpcDespawned; import net.runelite.api.events.PlayerDespawned; import net.runelite.client.eventbus.EventBus; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.NpcLootReceived; import net.runelite.client.events.PlayerLootReceived; @Singleton @Slf4j public class LootManager { private static final Map<Integer, Integer> NPC_DEATH_ANIMATIONS = ImmutableMap.of( NpcID.CAVE_KRAKEN, AnimationID.CAVE_KRAKEN_DEATH ); private final EventBus eventBus; private final Client client; private final NpcUtil npcUtil; private final ListMultimap<Integer, ItemStack> itemSpawns = ArrayListMultimap.create(); private final Set<LocalPoint> killPoints = new HashSet<>(); private WorldPoint playerLocationLastTick; private WorldPoint krakenPlayerLocation; private NPC delayedLootNpc; private int delayedLootTickLimit; @Inject private LootManager(EventBus eventBus, Client client, NpcUtil npcUtil) { this.eventBus = eventBus; this.client = client; this.npcUtil = npcUtil; eventBus.register(this); } @Subscribe public void onNpcDespawned(NpcDespawned npcDespawned) { final NPC npc = npcDespawned.getNpc(); if (npc == delayedLootNpc) { delayedLootNpc = null; delayedLootTickLimit = 0; } if (!npcUtil.isDying(npc)) { int id = npc.getId(); switch (id) { case NpcID.GARGOYLE: case NpcID.GARGOYLE_413: case NpcID.GARGOYLE_1543: case NpcID.MARBLE_GARGOYLE: case NpcID.MARBLE_GARGOYLE_7408: case NpcID.DUSK_7888: case NpcID.DUSK_7889: case NpcID.ROCKSLUG: case NpcID.ROCKSLUG_422: case NpcID.GIANT_ROCKSLUG: case NpcID.SMALL_LIZARD: case NpcID.SMALL_LIZARD_463: case NpcID.DESERT_LIZARD: case NpcID.DESERT_LIZARD_460: case NpcID.DESERT_LIZARD_461: case NpcID.LIZARD: case NpcID.ZYGOMITE: case NpcID.ZYGOMITE_1024: case NpcID.ANCIENT_ZYGOMITE: // these monsters die with >0 hp, so we just look for coincident // item spawn with despawn break; default: return; } } processNpcLoot(npc); } @Subscribe public void onPlayerDespawned(PlayerDespawned playerDespawned) { final Player player = playerDespawned.getPlayer(); // Only care about dead Players if (player.getHealthRatio() != 0) { return; } final LocalPoint location = LocalPoint.fromWorld(client, player.getWorldLocation()); if (location == null || killPoints.contains(location)) { return; } final int x = location.getSceneX(); final int y = location.getSceneY(); final int packed = x << 8 | y; final Collection<ItemStack> items = itemSpawns.get(packed); if (items.isEmpty()) { return; } killPoints.add(location); eventBus.post(new PlayerLootReceived(player, items)); } @Subscribe public void onItemSpawned(ItemSpawned itemSpawned) { final TileItem item = itemSpawned.getItem(); final Tile tile = itemSpawned.getTile(); final LocalPoint location = tile.getLocalLocation(); final int packed = location.getSceneX() << 8 | location.getSceneY(); itemSpawns.put(packed, new ItemStack(item.getId(), item.getQuantity(), location)); log.debug("Item spawn {} ({}) location {}", item.getId(), item.getQuantity(), location); } @Subscribe public void onItemDespawned(ItemDespawned itemDespawned) { final TileItem item = itemDespawned.getItem(); final LocalPoint location = itemDespawned.getTile().getLocalLocation(); log.debug("Item despawn {} ({}) location {}", item.getId(), item.getQuantity(), location); } @Subscribe public void onItemQuantityChanged(ItemQuantityChanged itemQuantityChanged) { final TileItem item = itemQuantityChanged.getItem(); final Tile tile = itemQuantityChanged.getTile(); final LocalPoint location = tile.getLocalLocation(); final int packed = location.getSceneX() << 8 | location.getSceneY(); final int diff = itemQuantityChanged.getNewQuantity() - itemQuantityChanged.getOldQuantity(); if (diff <= 0) { return; } itemSpawns.put(packed, new ItemStack(item.getId(), diff, location)); } @Subscribe public void onAnimationChanged(AnimationChanged e) { if (!(e.getActor() instanceof NPC)) { return; } final NPC npc = (NPC) e.getActor(); int id = npc.getId(); // We only care about certain NPCs final Integer deathAnim = NPC_DEATH_ANIMATIONS.get(id); // Current animation is death animation? if (deathAnim != null && deathAnim == npc.getAnimation()) { if (id == NpcID.CAVE_KRAKEN) { // Big Kraken drops loot wherever player is standing when animation starts. krakenPlayerLocation = client.getLocalPlayer().getWorldLocation(); } else { // These NPCs drop loot on death animation, which is right now. processNpcLoot(npc); } } } @Subscribe public void onNpcChanged(NpcChanged npcChanged) { final NPC npc = npcChanged.getNpc(); if (npc.getId() == NpcID.THE_NIGHTMARE_9433 || npc.getId() == NpcID.PHOSANIS_NIGHTMARE_9424) { delayedLootNpc = npc; delayedLootTickLimit = 15; } } @Subscribe public void onGameTick(GameTick gameTick) { if (delayedLootNpc != null && delayedLootTickLimit-- > 0) { processDelayedLoot(); } playerLocationLastTick = client.getLocalPlayer().getWorldLocation(); itemSpawns.clear(); killPoints.clear(); } private void processDelayedLoot() { final WorldPoint adjacentLootTile = getAdjacentSquareLootTile(delayedLootNpc); final LocalPoint localPoint = LocalPoint.fromWorld(client, adjacentLootTile); if (localPoint == null) { log.debug("Scene changed away from delayed loot location"); delayedLootNpc = null; delayedLootTickLimit = 0; return; } final int sceneX = localPoint.getSceneX(); final int sceneY = localPoint.getSceneY(); final int packed = sceneX << 8 | sceneY; final List<ItemStack> itemStacks = itemSpawns.get(packed); if (itemStacks.isEmpty()) { // no loot yet return; } log.debug("Got delayed loot stack from {}: {}", delayedLootNpc.getName(), itemStacks); eventBus.post(new NpcLootReceived(delayedLootNpc, itemStacks)); delayedLootNpc = null; delayedLootTickLimit = 0; } private void processNpcLoot(NPC npc) { final LocalPoint location = LocalPoint.fromWorld(client, getDropLocation(npc, npc.getWorldLocation())); if (location == null || killPoints.contains(location)) { return; } final int x = location.getSceneX(); final int y = location.getSceneY(); final int size = npc.getComposition().getSize(); // Some NPCs drop items onto multiple tiles final List<ItemStack> allItems = new ArrayList<>(); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { final int packed = (x + i) << 8 | (y + j); final Collection<ItemStack> items = itemSpawns.get(packed); allItems.addAll(items); } } if (allItems.isEmpty()) { return; } killPoints.add(location); eventBus.post(new NpcLootReceived(npc, allItems)); } private WorldPoint getDropLocation(NPC npc, WorldPoint worldLocation) { switch (npc.getId()) { case NpcID.KRAKEN: case NpcID.KRAKEN_6640: case NpcID.KRAKEN_6656: worldLocation = playerLocationLastTick; break; case NpcID.CAVE_KRAKEN: worldLocation = krakenPlayerLocation; break; case NpcID.ZULRAH: // Green case NpcID.ZULRAH_2043: // Red case NpcID.ZULRAH_2044: // Blue for (Map.Entry<Integer, ItemStack> entry : itemSpawns.entries()) { if (entry.getValue().getId() == ItemID.ZULRAHS_SCALES) { int packed = entry.getKey(); int unpackedX = packed >> 8; int unpackedY = packed & 0xFF; worldLocation = WorldPoint.fromScene(client, unpackedX, unpackedY, worldLocation.getPlane()); break; } } break; case NpcID.VORKATH: case NpcID.VORKATH_8058: case NpcID.VORKATH_8059: case NpcID.VORKATH_8060: case NpcID.VORKATH_8061: { int x = worldLocation.getX() + 3; int y = worldLocation.getY() + 3; if (playerLocationLastTick.getX() < x) { x -= 4; } else if (playerLocationLastTick.getX() > x) { x += 4; } if (playerLocationLastTick.getY() < y) { y -= 4; } else if (playerLocationLastTick.getY() > y) { y += 4; } worldLocation = new WorldPoint(x, y, worldLocation.getPlane()); break; } case NpcID.NEX: case NpcID.NEX_11279: case NpcID.NEX_11280: case NpcID.NEX_11281: case NpcID.NEX_11282: { // Nex loot is under the player, or under nex LocalPoint localPoint = LocalPoint.fromWorld(client, playerLocationLastTick); if (localPoint != null) { int x = localPoint.getSceneX(); int y = localPoint.getSceneY(); final int packed = x << 8 | y; if (itemSpawns.containsKey(packed)) { return playerLocationLastTick; } } break; } } return worldLocation; } private WorldPoint getAdjacentSquareLootTile(NPC npc) { final NPCComposition composition = npc.getComposition(); final WorldPoint worldLocation = npc.getWorldLocation(); int x = worldLocation.getX(); int y = worldLocation.getY(); if (playerLocationLastTick.getX() < x) { x -= 1; } else { x += Math.min(playerLocationLastTick.getX() - x, composition.getSize()); } if (playerLocationLastTick.getY() < y) { y -= 1; } else { y += Math.min(playerLocationLastTick.getY() - y, composition.getSize()); } return new WorldPoint(x, y, worldLocation.getPlane()); } /** * Get the list of items present at the provided WorldPoint that spawned this tick. * * @param worldPoint the location in question * @return the list of item stacks */ public Collection<ItemStack> getItemSpawns(WorldPoint worldPoint) { LocalPoint localPoint = LocalPoint.fromWorld(client, worldPoint); if (localPoint == null) { return Collections.emptyList(); } final int sceneX = localPoint.getSceneX(); final int sceneY = localPoint.getSceneY(); final int packed = sceneX << 8 | sceneY; final List<ItemStack> itemStacks = itemSpawns.get(packed); return Collections.unmodifiableList(itemStacks); } }
412
0.970007
1
0.970007
game-dev
MEDIA
0.829975
game-dev
0.991222
1
0.991222
PacktPublishing/Demystified-Object-Oriented-Programming-with-CPP
8,545
Chapter18/original/Chp18-Ex1.cpp
// (c) Dorothy R. Kirk. All Rights Reserved. // Purpose: To illustrate a simple Adapter class, using private inheritance between Adapter and Adaptee. #include <iostream> #include <list> using std::cout; // preferable to: using namespace std; using std::endl; using std::string; using std::list; // Person is the Adaptee class (the class requiring an adaptation) class Person { private: string firstName; string lastName; char middleInitial = '\0'; // in-class initialization -- value to be used in default constructor string title; // Mr., Ms., Mrs., Miss, Dr., etc. string greeting; protected: void ModifyTitle(const string &); // Make this operation available to derived classes public: Person() = default; // default constructor Person(const string &, const string &, char, const string &); // alternate constructor Person(const Person &) = default; // copy constructor Person &operator=(const Person &); // overloaded assignment operator virtual ~Person() = default; // virtual destructor const string &GetFirstName() const { return firstName; } // firstName returned as reference to const string const string &GetLastName() const { return lastName; } // so is lastName (via implicit cast) const string &GetTitle() const { return title; } char GetMiddleInitial() const { return middleInitial; } void SetGreeting(const string &); virtual const string &Speak() { return greeting; } // note return type of const string & (we're no longer returning a literal) virtual void Print() const; }; // Remember, using system-supplied default constructor, copy constructor and destructor Person::Person(const string &fn, const string &ln, char mi, const string &t) : firstName(fn), lastName(ln), middleInitial(mi), title(t), greeting("Hello") { } // We're using the default, system-supplied copy constructor, but if you wrote it, it would look like: /* Person::Person(const Person &p) : firstName(p.firstName), lastName(p.lastName), middleInitial(p.middleInitial), title(p.title), greeting(p.greeting) { } */ Person &Person::operator=(const Person &p) { // make sure we're not assigning an object to itself if (this != &p) { // Note: there's no dynamically allocated data members, so implementing = is straightforward firstName = p.firstName; lastName = p.lastName; middleInitial = p.middleInitial; title = p.title; greeting = p.greeting; } return *this; // allow for cascaded assignments } void Person::ModifyTitle(const string &newTitle) { title = newTitle; } void Person::SetGreeting(const string &newGreeting) { greeting = newGreeting; } void Person::Print() const { cout << title << " " << firstName << " " << lastName << endl; } // Adapter Class -- uses private inheritance. Could have also used an association // Decided this should be an abstract class, so Converse is a pure virtual function (albeit with an optional definition!) // Derived classes will still need to override this pure virtual function if they'd like to be instantiable (concrete classes) // Humanoid is primarily an Adapter class, however, is is secondarily a Target class, as derived class instances of this type // can be generalized as Humanoid *'s and manipulated in the Client (application). class Humanoid: private Person { protected: void SetTitle(const string &t) { ModifyTitle(t); } // calls Person::ModifyTitle() public: Humanoid() = default; Humanoid(const string &, const string &, const string &, const string &); Humanoid(const Humanoid &h) = default; // if we wrote copy constructor ourselves, we'd add : Person(h) { } Humanoid &operator=(const Humanoid &h) { return dynamic_cast<Humanoid &>(Person::operator=(h)); } ~Humanoid() override = default; // Added interfaces for the Adapter class - due to private inheritance, inherited interfaces are hidden outside the scope of Humaniod const string &GetSecondaryName() const { return GetFirstName(); } const string &GetPrimaryName() const { return GetLastName(); } const string &GetTitle() const { return Person::GetTitle(); } // Scope resolution needed on GetTitle() to avoid recursion void SetSalutation(const string &m) { SetGreeting(m); } virtual void GetInfo() { Print(); } virtual const string &Converse() = 0; // Pure virtual function prototype }; Humanoid::Humanoid(const string &n2, const string &n1, const string &planetNation, const string &greeting): Person(n2, n1, ' ', planetNation) { SetGreeting(greeting); } const string &Humanoid::Converse() // Yes, there can be a default implementation for a pure virtual function { // but it can not be specified inline return Speak(); } // One of several Target classes class Orkan: public Humanoid { public: Orkan() = default; // default constructor Orkan(const string &n2, const string &n1, const string &t) : Humanoid(n2, n1, t, "Nanu nanu") { } Orkan(const Orkan &h) = default; // If we instead wrote copy constructor ourselves, we'd add : Humanoid(h) { } Orkan &operator=(const Orkan &h) { return dynamic_cast<Orkan &>(Humanoid::operator=(h)); } ~Orkan() override = default; // virtual destructor const string &Converse() override; // We must override this method if we want Orkan to be a concrete class }; const string &Orkan::Converse() { return Humanoid::Converse(); // even if we just call the default implementation, we must provide a method here } // One of several Target classes class Romulan: public Humanoid { public: Romulan() = default; // default constructor Romulan(const string &n2, const string &n1, const string &t) : Humanoid(n2, n1, t, "jolan'tru") { } Romulan(const Romulan &h) = default; // If we instead wrote copy constructor ourselves, we'd add : Humanoid(h) { } Romulan &operator=(const Romulan &h) { return dynamic_cast<Romulan &>(Humanoid::operator=(h)); } ~Romulan() override = default; // virtual destructor const string &Converse() override; // We must override this method if we want Romulan to be a concrete class }; const string &Romulan::Converse() { return Humanoid::Converse(); // even if we just call the default implementation, we must provide a method here } // One of several Target classes class Earthling: public Humanoid { public: Earthling() = default; // default constructor Earthling(const string &n2, const string &n1, const string &t) : Humanoid(n2, n1, t, "Hello") { } Earthling(const Earthling &h) = default; // If we instead wrote copy constructor, we'd add : Humanoid(h) { } Earthling &operator=(const Earthling &h) { return dynamic_cast<Earthling &>(Humanoid::operator=(h)); } ~Earthling() { } // virtual destructor const string &Converse() override; // We must override this method if we want Romulan to be a concrete class }; const string &Earthling::Converse() { return Humanoid::Converse(); // even if we just call the default implementation, we must provide a method here } int main() { list<Humanoid *> allies; Orkan *o1 = new Orkan("Mork", "McConnell", "Orkan"); Romulan *r1 = new Romulan("Donatra", "Jarok", "Romulan"); Earthling *e1 = new Earthling("Eve", "Xu", "Earthling"); // Add Humanoid *'s to the allies list. The list will make copies of the objects internally and will // properly clean up these objects when they are no longer members of the list. // You are responsible to delete and heap instances you provide to the list when you are done with them. // Add various derived types of Humanoid to the list allies.push_back(o1); allies.push_back(r1); allies.push_back(e1); // Create a list iterator and set to first item in the list list <Humanoid *>::iterator listIter = allies.begin(); while (listIter != allies.end()) { (*listIter)->GetInfo(); cout << (*listIter)->Converse() << endl; listIter++; } // Though each type of Humanoid has a default Salutation, each may expand their language skills and choose an alternate language e1->SetSalutation("Bonjour"); e1->GetInfo(); cout << e1->Converse() << endl; // Show the Earthling's revised language capabilities delete o1; // delete the heap instances delete r1; delete e1; return 0; }
412
0.852334
1
0.852334
game-dev
MEDIA
0.266533
game-dev
0.70924
1
0.70924
idsoftware/quake2
42,550
game/p_client.c
/* Copyright (C) 1997-2001 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" #include "m_player.h" void ClientUserinfoChanged (edict_t *ent, char *userinfo); void SP_misc_teleporter_dest (edict_t *ent); // // Gross, ugly, disgustuing hack section // // this function is an ugly as hell hack to fix some map flaws // // the coop spawn spots on some maps are SNAFU. There are coop spots // with the wrong targetname as well as spots with no name at all // // we use carnal knowledge of the maps to fix the coop spot targetnames to match // that of the nearest named single player spot static void SP_FixCoopSpots (edict_t *self) { edict_t *spot; vec3_t d; spot = NULL; while(1) { spot = G_Find(spot, FOFS(classname), "info_player_start"); if (!spot) return; if (!spot->targetname) continue; VectorSubtract(self->s.origin, spot->s.origin, d); if (VectorLength(d) < 384) { if ((!self->targetname) || Q_stricmp(self->targetname, spot->targetname) != 0) { // gi.dprintf("FixCoopSpots changed %s at %s targetname from %s to %s\n", self->classname, vtos(self->s.origin), self->targetname, spot->targetname); self->targetname = spot->targetname; } return; } } } // now if that one wasn't ugly enough for you then try this one on for size // some maps don't have any coop spots at all, so we need to create them // where they should have been static void SP_CreateCoopSpots (edict_t *self) { edict_t *spot; if(Q_stricmp(level.mapname, "security") == 0) { spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 - 64; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 + 64; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 + 128; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; return; } } /*QUAKED info_player_start (1 0 0) (-16 -16 -24) (16 16 32) The normal starting point for a level. */ void SP_info_player_start(edict_t *self) { if (!coop->value) return; if(Q_stricmp(level.mapname, "security") == 0) { // invoke one of our gross, ugly, disgusting hacks self->think = SP_CreateCoopSpots; self->nextthink = level.time + FRAMETIME; } } /*QUAKED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) potential spawning position for deathmatch games */ void SP_info_player_deathmatch(edict_t *self) { if (!deathmatch->value) { G_FreeEdict (self); return; } SP_misc_teleporter_dest (self); } /*QUAKED info_player_coop (1 0 1) (-16 -16 -24) (16 16 32) potential spawning position for coop games */ void SP_info_player_coop(edict_t *self) { if (!coop->value) { G_FreeEdict (self); return; } if((Q_stricmp(level.mapname, "jail2") == 0) || (Q_stricmp(level.mapname, "jail4") == 0) || (Q_stricmp(level.mapname, "mine1") == 0) || (Q_stricmp(level.mapname, "mine2") == 0) || (Q_stricmp(level.mapname, "mine3") == 0) || (Q_stricmp(level.mapname, "mine4") == 0) || (Q_stricmp(level.mapname, "lab") == 0) || (Q_stricmp(level.mapname, "boss1") == 0) || (Q_stricmp(level.mapname, "fact3") == 0) || (Q_stricmp(level.mapname, "biggun") == 0) || (Q_stricmp(level.mapname, "space") == 0) || (Q_stricmp(level.mapname, "command") == 0) || (Q_stricmp(level.mapname, "power2") == 0) || (Q_stricmp(level.mapname, "strike") == 0)) { // invoke one of our gross, ugly, disgusting hacks self->think = SP_FixCoopSpots; self->nextthink = level.time + FRAMETIME; } } /*QUAKED info_player_intermission (1 0 1) (-16 -16 -24) (16 16 32) The deathmatch intermission point will be at one of these Use 'angles' instead of 'angle', so you can set pitch or roll as well as yaw. 'pitch yaw roll' */ void SP_info_player_intermission(void) { } //======================================================================= void player_pain (edict_t *self, edict_t *other, float kick, int damage) { // player pain is handled at the end of the frame in P_DamageFeedback } qboolean IsFemale (edict_t *ent) { char *info; if (!ent->client) return false; info = Info_ValueForKey (ent->client->pers.userinfo, "gender"); if (info[0] == 'f' || info[0] == 'F') return true; return false; } qboolean IsNeutral (edict_t *ent) { char *info; if (!ent->client) return false; info = Info_ValueForKey (ent->client->pers.userinfo, "gender"); if (info[0] != 'f' && info[0] != 'F' && info[0] != 'm' && info[0] != 'M') return true; return false; } void ClientObituary (edict_t *self, edict_t *inflictor, edict_t *attacker) { int mod; char *message; char *message2; qboolean ff; if (coop->value && attacker->client) meansOfDeath |= MOD_FRIENDLY_FIRE; if (deathmatch->value || coop->value) { ff = meansOfDeath & MOD_FRIENDLY_FIRE; mod = meansOfDeath & ~MOD_FRIENDLY_FIRE; message = NULL; message2 = ""; switch (mod) { case MOD_SUICIDE: message = "suicides"; break; case MOD_FALLING: message = "cratered"; break; case MOD_CRUSH: message = "was squished"; break; case MOD_WATER: message = "sank like a rock"; break; case MOD_SLIME: message = "melted"; break; case MOD_LAVA: message = "does a back flip into the lava"; break; case MOD_EXPLOSIVE: case MOD_BARREL: message = "blew up"; break; case MOD_EXIT: message = "found a way out"; break; case MOD_TARGET_LASER: message = "saw the light"; break; case MOD_TARGET_BLASTER: message = "got blasted"; break; case MOD_BOMB: case MOD_SPLASH: case MOD_TRIGGER_HURT: message = "was in the wrong place"; break; } if (attacker == self) { switch (mod) { case MOD_HELD_GRENADE: message = "tried to put the pin back in"; break; case MOD_HG_SPLASH: case MOD_G_SPLASH: if (IsNeutral(self)) message = "tripped on its own grenade"; else if (IsFemale(self)) message = "tripped on her own grenade"; else message = "tripped on his own grenade"; break; case MOD_R_SPLASH: if (IsNeutral(self)) message = "blew itself up"; else if (IsFemale(self)) message = "blew herself up"; else message = "blew himself up"; break; case MOD_BFG_BLAST: message = "should have used a smaller gun"; break; default: if (IsNeutral(self)) message = "killed itself"; else if (IsFemale(self)) message = "killed herself"; else message = "killed himself"; break; } } if (message) { gi.bprintf (PRINT_MEDIUM, "%s %s.\n", self->client->pers.netname, message); if (deathmatch->value) self->client->resp.score--; self->enemy = NULL; return; } self->enemy = attacker; if (attacker && attacker->client) { switch (mod) { case MOD_BLASTER: message = "was blasted by"; break; case MOD_SHOTGUN: message = "was gunned down by"; break; case MOD_SSHOTGUN: message = "was blown away by"; message2 = "'s super shotgun"; break; case MOD_MACHINEGUN: message = "was machinegunned by"; break; case MOD_CHAINGUN: message = "was cut in half by"; message2 = "'s chaingun"; break; case MOD_GRENADE: message = "was popped by"; message2 = "'s grenade"; break; case MOD_G_SPLASH: message = "was shredded by"; message2 = "'s shrapnel"; break; case MOD_ROCKET: message = "ate"; message2 = "'s rocket"; break; case MOD_R_SPLASH: message = "almost dodged"; message2 = "'s rocket"; break; case MOD_HYPERBLASTER: message = "was melted by"; message2 = "'s hyperblaster"; break; case MOD_RAILGUN: message = "was railed by"; break; case MOD_BFG_LASER: message = "saw the pretty lights from"; message2 = "'s BFG"; break; case MOD_BFG_BLAST: message = "was disintegrated by"; message2 = "'s BFG blast"; break; case MOD_BFG_EFFECT: message = "couldn't hide from"; message2 = "'s BFG"; break; case MOD_HANDGRENADE: message = "caught"; message2 = "'s handgrenade"; break; case MOD_HG_SPLASH: message = "didn't see"; message2 = "'s handgrenade"; break; case MOD_HELD_GRENADE: message = "feels"; message2 = "'s pain"; break; case MOD_TELEFRAG: message = "tried to invade"; message2 = "'s personal space"; break; } if (message) { gi.bprintf (PRINT_MEDIUM,"%s %s %s%s\n", self->client->pers.netname, message, attacker->client->pers.netname, message2); if (deathmatch->value) { if (ff) attacker->client->resp.score--; else attacker->client->resp.score++; } return; } } } gi.bprintf (PRINT_MEDIUM,"%s died.\n", self->client->pers.netname); if (deathmatch->value) self->client->resp.score--; } void Touch_Item (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf); void TossClientWeapon (edict_t *self) { gitem_t *item; edict_t *drop; qboolean quad; float spread; if (!deathmatch->value) return; item = self->client->pers.weapon; if (! self->client->pers.inventory[self->client->ammo_index] ) item = NULL; if (item && (strcmp (item->pickup_name, "Blaster") == 0)) item = NULL; if (!((int)(dmflags->value) & DF_QUAD_DROP)) quad = false; else quad = (self->client->quad_framenum > (level.framenum + 10)); if (item && quad) spread = 22.5; else spread = 0.0; if (item) { self->client->v_angle[YAW] -= spread; drop = Drop_Item (self, item); self->client->v_angle[YAW] += spread; drop->spawnflags = DROPPED_PLAYER_ITEM; } if (quad) { self->client->v_angle[YAW] += spread; drop = Drop_Item (self, FindItemByClassname ("item_quad")); self->client->v_angle[YAW] -= spread; drop->spawnflags |= DROPPED_PLAYER_ITEM; drop->touch = Touch_Item; drop->nextthink = level.time + (self->client->quad_framenum - level.framenum) * FRAMETIME; drop->think = G_FreeEdict; } } /* ================== LookAtKiller ================== */ void LookAtKiller (edict_t *self, edict_t *inflictor, edict_t *attacker) { vec3_t dir; if (attacker && attacker != world && attacker != self) { VectorSubtract (attacker->s.origin, self->s.origin, dir); } else if (inflictor && inflictor != world && inflictor != self) { VectorSubtract (inflictor->s.origin, self->s.origin, dir); } else { self->client->killer_yaw = self->s.angles[YAW]; return; } if (dir[0]) self->client->killer_yaw = 180/M_PI*atan2(dir[1], dir[0]); else { self->client->killer_yaw = 0; if (dir[1] > 0) self->client->killer_yaw = 90; else if (dir[1] < 0) self->client->killer_yaw = -90; } if (self->client->killer_yaw < 0) self->client->killer_yaw += 360; } /* ================== player_die ================== */ void player_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point) { int n; VectorClear (self->avelocity); self->takedamage = DAMAGE_YES; self->movetype = MOVETYPE_TOSS; self->s.modelindex2 = 0; // remove linked weapon model self->s.angles[0] = 0; self->s.angles[2] = 0; self->s.sound = 0; self->client->weapon_sound = 0; self->maxs[2] = -8; // self->solid = SOLID_NOT; self->svflags |= SVF_DEADMONSTER; if (!self->deadflag) { self->client->respawn_time = level.time + 1.0; LookAtKiller (self, inflictor, attacker); self->client->ps.pmove.pm_type = PM_DEAD; ClientObituary (self, inflictor, attacker); TossClientWeapon (self); if (deathmatch->value) Cmd_Help_f (self); // show scores // clear inventory // this is kind of ugly, but it's how we want to handle keys in coop for (n = 0; n < game.num_items; n++) { if (coop->value && itemlist[n].flags & IT_KEY) self->client->resp.coop_respawn.inventory[n] = self->client->pers.inventory[n]; self->client->pers.inventory[n] = 0; } } // remove powerups self->client->quad_framenum = 0; self->client->invincible_framenum = 0; self->client->breather_framenum = 0; self->client->enviro_framenum = 0; self->flags &= ~FL_POWER_ARMOR; if (self->health < -40) { // gib gi.sound (self, CHAN_BODY, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0); for (n= 0; n < 4; n++) ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); ThrowClientHead (self, damage); self->takedamage = DAMAGE_NO; } else { // normal death if (!self->deadflag) { static int i; i = (i+1)%3; // start a death animation self->client->anim_priority = ANIM_DEATH; if (self->client->ps.pmove.pm_flags & PMF_DUCKED) { self->s.frame = FRAME_crdeath1-1; self->client->anim_end = FRAME_crdeath5; } else switch (i) { case 0: self->s.frame = FRAME_death101-1; self->client->anim_end = FRAME_death106; break; case 1: self->s.frame = FRAME_death201-1; self->client->anim_end = FRAME_death206; break; case 2: self->s.frame = FRAME_death301-1; self->client->anim_end = FRAME_death308; break; } gi.sound (self, CHAN_VOICE, gi.soundindex(va("*death%i.wav", (rand()%4)+1)), 1, ATTN_NORM, 0); } } self->deadflag = DEAD_DEAD; gi.linkentity (self); } //======================================================================= /* ============== InitClientPersistant This is only called when the game first initializes in single player, but is called after each death and level change in deathmatch ============== */ void InitClientPersistant (gclient_t *client) { gitem_t *item; memset (&client->pers, 0, sizeof(client->pers)); item = FindItem("Blaster"); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->pers.health = 100; client->pers.max_health = 100; client->pers.max_bullets = 200; client->pers.max_shells = 100; client->pers.max_rockets = 50; client->pers.max_grenades = 50; client->pers.max_cells = 200; client->pers.max_slugs = 50; client->pers.connected = true; } void InitClientResp (gclient_t *client) { memset (&client->resp, 0, sizeof(client->resp)); client->resp.enterframe = level.framenum; client->resp.coop_respawn = client->pers; } /* ================== SaveClientData Some information that should be persistant, like health, is still stored in the edict structure, so it needs to be mirrored out to the client structure before all the edicts are wiped. ================== */ void SaveClientData (void) { int i; edict_t *ent; for (i=0 ; i<game.maxclients ; i++) { ent = &g_edicts[1+i]; if (!ent->inuse) continue; game.clients[i].pers.health = ent->health; game.clients[i].pers.max_health = ent->max_health; game.clients[i].pers.savedFlags = (ent->flags & (FL_GODMODE|FL_NOTARGET|FL_POWER_ARMOR)); if (coop->value) game.clients[i].pers.score = ent->client->resp.score; } } void FetchClientEntData (edict_t *ent) { ent->health = ent->client->pers.health; ent->max_health = ent->client->pers.max_health; ent->flags |= ent->client->pers.savedFlags; if (coop->value) ent->client->resp.score = ent->client->pers.score; } /* ======================================================================= SelectSpawnPoint ======================================================================= */ /* ================ PlayersRangeFromSpot Returns the distance to the nearest player from the given spot ================ */ float PlayersRangeFromSpot (edict_t *spot) { edict_t *player; float bestplayerdistance; vec3_t v; int n; float playerdistance; bestplayerdistance = 9999999; for (n = 1; n <= maxclients->value; n++) { player = &g_edicts[n]; if (!player->inuse) continue; if (player->health <= 0) continue; VectorSubtract (spot->s.origin, player->s.origin, v); playerdistance = VectorLength (v); if (playerdistance < bestplayerdistance) bestplayerdistance = playerdistance; } return bestplayerdistance; } /* ================ SelectRandomDeathmatchSpawnPoint go to a random point, but NOT the two points closest to other players ================ */ edict_t *SelectRandomDeathmatchSpawnPoint (void) { edict_t *spot, *spot1, *spot2; int count = 0; int selection; float range, range1, range2; spot = NULL; range1 = range2 = 99999; spot1 = spot2 = NULL; while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { count++; range = PlayersRangeFromSpot(spot); if (range < range1) { range1 = range; spot1 = spot; } else if (range < range2) { range2 = range; spot2 = spot; } } if (!count) return NULL; if (count <= 2) { spot1 = spot2 = NULL; } else count -= 2; selection = rand() % count; spot = NULL; do { spot = G_Find (spot, FOFS(classname), "info_player_deathmatch"); if (spot == spot1 || spot == spot2) selection++; } while(selection--); return spot; } /* ================ SelectFarthestDeathmatchSpawnPoint ================ */ edict_t *SelectFarthestDeathmatchSpawnPoint (void) { edict_t *bestspot; float bestdistance, bestplayerdistance; edict_t *spot; spot = NULL; bestspot = NULL; bestdistance = 0; while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { bestplayerdistance = PlayersRangeFromSpot (spot); if (bestplayerdistance > bestdistance) { bestspot = spot; bestdistance = bestplayerdistance; } } if (bestspot) { return bestspot; } // if there is a player just spawned on each and every start spot // we have no choice to turn one into a telefrag meltdown spot = G_Find (NULL, FOFS(classname), "info_player_deathmatch"); return spot; } edict_t *SelectDeathmatchSpawnPoint (void) { if ( (int)(dmflags->value) & DF_SPAWN_FARTHEST) return SelectFarthestDeathmatchSpawnPoint (); else return SelectRandomDeathmatchSpawnPoint (); } edict_t *SelectCoopSpawnPoint (edict_t *ent) { int index; edict_t *spot = NULL; char *target; index = ent->client - game.clients; // player 0 starts in normal player spawn point if (!index) return NULL; spot = NULL; // assume there are four coop spots at each spawnpoint while (1) { spot = G_Find (spot, FOFS(classname), "info_player_coop"); if (!spot) return NULL; // we didn't have enough... target = spot->targetname; if (!target) target = ""; if ( Q_stricmp(game.spawnpoint, target) == 0 ) { // this is a coop spawn point for one of the clients here index--; if (!index) return spot; // this is it } } return spot; } /* =========== SelectSpawnPoint Chooses a player start, deathmatch start, coop start, etc ============ */ void SelectSpawnPoint (edict_t *ent, vec3_t origin, vec3_t angles) { edict_t *spot = NULL; if (deathmatch->value) spot = SelectDeathmatchSpawnPoint (); else if (coop->value) spot = SelectCoopSpawnPoint (ent); // find a single player start spot if (!spot) { while ((spot = G_Find (spot, FOFS(classname), "info_player_start")) != NULL) { if (!game.spawnpoint[0] && !spot->targetname) break; if (!game.spawnpoint[0] || !spot->targetname) continue; if (Q_stricmp(game.spawnpoint, spot->targetname) == 0) break; } if (!spot) { if (!game.spawnpoint[0]) { // there wasn't a spawnpoint without a target, so use any spot = G_Find (spot, FOFS(classname), "info_player_start"); } if (!spot) gi.error ("Couldn't find spawn point %s\n", game.spawnpoint); } } VectorCopy (spot->s.origin, origin); origin[2] += 9; VectorCopy (spot->s.angles, angles); } //====================================================================== void InitBodyQue (void) { int i; edict_t *ent; level.body_que = 0; for (i=0; i<BODY_QUEUE_SIZE ; i++) { ent = G_Spawn(); ent->classname = "bodyque"; } } void body_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point) { int n; if (self->health < -40) { gi.sound (self, CHAN_BODY, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0); for (n= 0; n < 4; n++) ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); self->s.origin[2] -= 48; ThrowClientHead (self, damage); self->takedamage = DAMAGE_NO; } } void CopyToBodyQue (edict_t *ent) { edict_t *body; // grab a body que and cycle to the next one body = &g_edicts[(int)maxclients->value + level.body_que + 1]; level.body_que = (level.body_que + 1) % BODY_QUEUE_SIZE; // FIXME: send an effect on the removed body gi.unlinkentity (ent); gi.unlinkentity (body); body->s = ent->s; body->s.number = body - g_edicts; body->svflags = ent->svflags; VectorCopy (ent->mins, body->mins); VectorCopy (ent->maxs, body->maxs); VectorCopy (ent->absmin, body->absmin); VectorCopy (ent->absmax, body->absmax); VectorCopy (ent->size, body->size); body->solid = ent->solid; body->clipmask = ent->clipmask; body->owner = ent->owner; body->movetype = ent->movetype; body->die = body_die; body->takedamage = DAMAGE_YES; gi.linkentity (body); } void respawn (edict_t *self) { if (deathmatch->value || coop->value) { // spectator's don't leave bodies if (self->movetype != MOVETYPE_NOCLIP) CopyToBodyQue (self); self->svflags &= ~SVF_NOCLIENT; PutClientInServer (self); // add a teleportation effect self->s.event = EV_PLAYER_TELEPORT; // hold in place briefly self->client->ps.pmove.pm_flags = PMF_TIME_TELEPORT; self->client->ps.pmove.pm_time = 14; self->client->respawn_time = level.time; return; } // restart the entire server gi.AddCommandString ("menu_loadgame\n"); } /* * only called when pers.spectator changes * note that resp.spectator should be the opposite of pers.spectator here */ void spectator_respawn (edict_t *ent) { int i, numspec; // if the user wants to become a spectator, make sure he doesn't // exceed max_spectators if (ent->client->pers.spectator) { char *value = Info_ValueForKey (ent->client->pers.userinfo, "spectator"); if (*spectator_password->string && strcmp(spectator_password->string, "none") && strcmp(spectator_password->string, value)) { gi.cprintf(ent, PRINT_HIGH, "Spectator password incorrect.\n"); ent->client->pers.spectator = false; gi.WriteByte (svc_stufftext); gi.WriteString ("spectator 0\n"); gi.unicast(ent, true); return; } // count spectators for (i = 1, numspec = 0; i <= maxclients->value; i++) if (g_edicts[i].inuse && g_edicts[i].client->pers.spectator) numspec++; if (numspec >= maxspectators->value) { gi.cprintf(ent, PRINT_HIGH, "Server spectator limit is full."); ent->client->pers.spectator = false; // reset his spectator var gi.WriteByte (svc_stufftext); gi.WriteString ("spectator 0\n"); gi.unicast(ent, true); return; } } else { // he was a spectator and wants to join the game // he must have the right password char *value = Info_ValueForKey (ent->client->pers.userinfo, "password"); if (*password->string && strcmp(password->string, "none") && strcmp(password->string, value)) { gi.cprintf(ent, PRINT_HIGH, "Password incorrect.\n"); ent->client->pers.spectator = true; gi.WriteByte (svc_stufftext); gi.WriteString ("spectator 1\n"); gi.unicast(ent, true); return; } } // clear client on respawn ent->client->resp.score = ent->client->pers.score = 0; ent->svflags &= ~SVF_NOCLIENT; PutClientInServer (ent); // add a teleportation effect if (!ent->client->pers.spectator) { // send effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_LOGIN); gi.multicast (ent->s.origin, MULTICAST_PVS); // hold in place briefly ent->client->ps.pmove.pm_flags = PMF_TIME_TELEPORT; ent->client->ps.pmove.pm_time = 14; } ent->client->respawn_time = level.time; if (ent->client->pers.spectator) gi.bprintf (PRINT_HIGH, "%s has moved to the sidelines\n", ent->client->pers.netname); else gi.bprintf (PRINT_HIGH, "%s joined the game\n", ent->client->pers.netname); } //============================================================== /* =========== PutClientInServer Called when a player connects to a server or respawns in a deathmatch. ============ */ void PutClientInServer (edict_t *ent) { vec3_t mins = {-16, -16, -24}; vec3_t maxs = {16, 16, 32}; int index; vec3_t spawn_origin, spawn_angles; gclient_t *client; int i; client_persistant_t saved; client_respawn_t resp; // find a spawn point // do it before setting health back up, so farthest // ranging doesn't count this client SelectSpawnPoint (ent, spawn_origin, spawn_angles); index = ent-g_edicts-1; client = ent->client; // deathmatch wipes most client data every spawn if (deathmatch->value) { char userinfo[MAX_INFO_STRING]; resp = client->resp; memcpy (userinfo, client->pers.userinfo, sizeof(userinfo)); InitClientPersistant (client); ClientUserinfoChanged (ent, userinfo); } else if (coop->value) { // int n; char userinfo[MAX_INFO_STRING]; resp = client->resp; memcpy (userinfo, client->pers.userinfo, sizeof(userinfo)); // this is kind of ugly, but it's how we want to handle keys in coop // for (n = 0; n < game.num_items; n++) // { // if (itemlist[n].flags & IT_KEY) // resp.coop_respawn.inventory[n] = client->pers.inventory[n]; // } resp.coop_respawn.game_helpchanged = client->pers.game_helpchanged; resp.coop_respawn.helpchanged = client->pers.helpchanged; client->pers = resp.coop_respawn; ClientUserinfoChanged (ent, userinfo); if (resp.score > client->pers.score) client->pers.score = resp.score; } else { memset (&resp, 0, sizeof(resp)); } // clear everything but the persistant data saved = client->pers; memset (client, 0, sizeof(*client)); client->pers = saved; if (client->pers.health <= 0) InitClientPersistant(client); client->resp = resp; // copy some data from the client to the entity FetchClientEntData (ent); // clear entity values ent->groundentity = NULL; ent->client = &game.clients[index]; ent->takedamage = DAMAGE_AIM; ent->movetype = MOVETYPE_WALK; ent->viewheight = 22; ent->inuse = true; ent->classname = "player"; ent->mass = 200; ent->solid = SOLID_BBOX; ent->deadflag = DEAD_NO; ent->air_finished = level.time + 12; ent->clipmask = MASK_PLAYERSOLID; ent->model = "players/male/tris.md2"; ent->pain = player_pain; ent->die = player_die; ent->waterlevel = 0; ent->watertype = 0; ent->flags &= ~FL_NO_KNOCKBACK; ent->svflags &= ~SVF_DEADMONSTER; VectorCopy (mins, ent->mins); VectorCopy (maxs, ent->maxs); VectorClear (ent->velocity); // clear playerstate values memset (&ent->client->ps, 0, sizeof(client->ps)); client->ps.pmove.origin[0] = spawn_origin[0]*8; client->ps.pmove.origin[1] = spawn_origin[1]*8; client->ps.pmove.origin[2] = spawn_origin[2]*8; if (deathmatch->value && ((int)dmflags->value & DF_FIXED_FOV)) { client->ps.fov = 90; } else { client->ps.fov = atoi(Info_ValueForKey(client->pers.userinfo, "fov")); if (client->ps.fov < 1) client->ps.fov = 90; else if (client->ps.fov > 160) client->ps.fov = 160; } client->ps.gunindex = gi.modelindex(client->pers.weapon->view_model); // clear entity state values ent->s.effects = 0; ent->s.modelindex = 255; // will use the skin specified model ent->s.modelindex2 = 255; // custom gun model // sknum is player num and weapon number // weapon number will be added in changeweapon ent->s.skinnum = ent - g_edicts - 1; ent->s.frame = 0; VectorCopy (spawn_origin, ent->s.origin); ent->s.origin[2] += 1; // make sure off ground VectorCopy (ent->s.origin, ent->s.old_origin); // set the delta angle for (i=0 ; i<3 ; i++) { client->ps.pmove.delta_angles[i] = ANGLE2SHORT(spawn_angles[i] - client->resp.cmd_angles[i]); } ent->s.angles[PITCH] = 0; ent->s.angles[YAW] = spawn_angles[YAW]; ent->s.angles[ROLL] = 0; VectorCopy (ent->s.angles, client->ps.viewangles); VectorCopy (ent->s.angles, client->v_angle); // spawn a spectator if (client->pers.spectator) { client->chase_target = NULL; client->resp.spectator = true; ent->movetype = MOVETYPE_NOCLIP; ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->client->ps.gunindex = 0; gi.linkentity (ent); return; } else client->resp.spectator = false; if (!KillBox (ent)) { // could't spawn in? } gi.linkentity (ent); // force the current weapon up client->newweapon = client->pers.weapon; ChangeWeapon (ent); } /* ===================== ClientBeginDeathmatch A client has just connected to the server in deathmatch mode, so clear everything out before starting them. ===================== */ void ClientBeginDeathmatch (edict_t *ent) { G_InitEdict (ent); InitClientResp (ent->client); // locate ent at a spawn point PutClientInServer (ent); if (level.intermissiontime) { MoveClientToIntermission (ent); } else { // send effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_LOGIN); gi.multicast (ent->s.origin, MULTICAST_PVS); } gi.bprintf (PRINT_HIGH, "%s entered the game\n", ent->client->pers.netname); // make sure all view stuff is valid ClientEndServerFrame (ent); } /* =========== ClientBegin called when a client has finished connecting, and is ready to be placed into the game. This will happen every level load. ============ */ void ClientBegin (edict_t *ent) { int i; ent->client = game.clients + (ent - g_edicts - 1); if (deathmatch->value) { ClientBeginDeathmatch (ent); return; } // if there is already a body waiting for us (a loadgame), just // take it, otherwise spawn one from scratch if (ent->inuse == true) { // the client has cleared the client side viewangles upon // connecting to the server, which is different than the // state when the game is saved, so we need to compensate // with deltaangles for (i=0 ; i<3 ; i++) ent->client->ps.pmove.delta_angles[i] = ANGLE2SHORT(ent->client->ps.viewangles[i]); } else { // a spawn point will completely reinitialize the entity // except for the persistant data that was initialized at // ClientConnect() time G_InitEdict (ent); ent->classname = "player"; InitClientResp (ent->client); PutClientInServer (ent); } if (level.intermissiontime) { MoveClientToIntermission (ent); } else { // send effect if in a multiplayer game if (game.maxclients > 1) { gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_LOGIN); gi.multicast (ent->s.origin, MULTICAST_PVS); gi.bprintf (PRINT_HIGH, "%s entered the game\n", ent->client->pers.netname); } } // make sure all view stuff is valid ClientEndServerFrame (ent); } /* =========== ClientUserInfoChanged called whenever the player updates a userinfo variable. The game can override any of the settings in place (forcing skins or names, etc) before copying it off. ============ */ void ClientUserinfoChanged (edict_t *ent, char *userinfo) { char *s; int playernum; // check for malformed or illegal info strings if (!Info_Validate(userinfo)) { strcpy (userinfo, "\\name\\badinfo\\skin\\male/grunt"); } // set name s = Info_ValueForKey (userinfo, "name"); strncpy (ent->client->pers.netname, s, sizeof(ent->client->pers.netname)-1); // set spectator s = Info_ValueForKey (userinfo, "spectator"); // spectators are only supported in deathmatch if (deathmatch->value && *s && strcmp(s, "0")) ent->client->pers.spectator = true; else ent->client->pers.spectator = false; // set skin s = Info_ValueForKey (userinfo, "skin"); playernum = ent-g_edicts-1; // combine name and skin into a configstring gi.configstring (CS_PLAYERSKINS+playernum, va("%s\\%s", ent->client->pers.netname, s) ); // fov if (deathmatch->value && ((int)dmflags->value & DF_FIXED_FOV)) { ent->client->ps.fov = 90; } else { ent->client->ps.fov = atoi(Info_ValueForKey(userinfo, "fov")); if (ent->client->ps.fov < 1) ent->client->ps.fov = 90; else if (ent->client->ps.fov > 160) ent->client->ps.fov = 160; } // handedness s = Info_ValueForKey (userinfo, "hand"); if (strlen(s)) { ent->client->pers.hand = atoi(s); } // save off the userinfo in case we want to check something later strncpy (ent->client->pers.userinfo, userinfo, sizeof(ent->client->pers.userinfo)-1); } /* =========== ClientConnect Called when a player begins connecting to the server. The game can refuse entrance to a client by returning false. If the client is allowed, the connection process will continue and eventually get to ClientBegin() Changing levels will NOT cause this to be called again, but loadgames will. ============ */ qboolean ClientConnect (edict_t *ent, char *userinfo) { char *value; // check to see if they are on the banned IP list value = Info_ValueForKey (userinfo, "ip"); if (SV_FilterPacket(value)) { Info_SetValueForKey(userinfo, "rejmsg", "Banned."); return false; } // check for a spectator value = Info_ValueForKey (userinfo, "spectator"); if (deathmatch->value && *value && strcmp(value, "0")) { int i, numspec; if (*spectator_password->string && strcmp(spectator_password->string, "none") && strcmp(spectator_password->string, value)) { Info_SetValueForKey(userinfo, "rejmsg", "Spectator password required or incorrect."); return false; } // count spectators for (i = numspec = 0; i < maxclients->value; i++) if (g_edicts[i+1].inuse && g_edicts[i+1].client->pers.spectator) numspec++; if (numspec >= maxspectators->value) { Info_SetValueForKey(userinfo, "rejmsg", "Server spectator limit is full."); return false; } } else { // check for a password value = Info_ValueForKey (userinfo, "password"); if (*password->string && strcmp(password->string, "none") && strcmp(password->string, value)) { Info_SetValueForKey(userinfo, "rejmsg", "Password required or incorrect."); return false; } } // they can connect ent->client = game.clients + (ent - g_edicts - 1); // if there is already a body waiting for us (a loadgame), just // take it, otherwise spawn one from scratch if (ent->inuse == false) { // clear the respawning variables InitClientResp (ent->client); if (!game.autosaved || !ent->client->pers.weapon) InitClientPersistant (ent->client); } ClientUserinfoChanged (ent, userinfo); if (game.maxclients > 1) gi.dprintf ("%s connected\n", ent->client->pers.netname); ent->svflags = 0; // make sure we start with known default ent->client->pers.connected = true; return true; } /* =========== ClientDisconnect Called when a player drops from the server. Will not be called between levels. ============ */ void ClientDisconnect (edict_t *ent) { int playernum; if (!ent->client) return; gi.bprintf (PRINT_HIGH, "%s disconnected\n", ent->client->pers.netname); // send effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_LOGOUT); gi.multicast (ent->s.origin, MULTICAST_PVS); gi.unlinkentity (ent); ent->s.modelindex = 0; ent->solid = SOLID_NOT; ent->inuse = false; ent->classname = "disconnected"; ent->client->pers.connected = false; playernum = ent-g_edicts-1; gi.configstring (CS_PLAYERSKINS+playernum, ""); } //============================================================== edict_t *pm_passent; // pmove doesn't need to know about passent and contentmask trace_t PM_trace (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) { if (pm_passent->health > 0) return gi.trace (start, mins, maxs, end, pm_passent, MASK_PLAYERSOLID); else return gi.trace (start, mins, maxs, end, pm_passent, MASK_DEADSOLID); } unsigned CheckBlock (void *b, int c) { int v,i; v = 0; for (i=0 ; i<c ; i++) v+= ((byte *)b)[i]; return v; } void PrintPmove (pmove_t *pm) { unsigned c1, c2; c1 = CheckBlock (&pm->s, sizeof(pm->s)); c2 = CheckBlock (&pm->cmd, sizeof(pm->cmd)); Com_Printf ("sv %3i:%i %i\n", pm->cmd.impulse, c1, c2); } /* ============== ClientThink This will be called once for each client frame, which will usually be a couple times for each server frame. ============== */ void ClientThink (edict_t *ent, usercmd_t *ucmd) { gclient_t *client; edict_t *other; int i, j; pmove_t pm; level.current_entity = ent; client = ent->client; if (level.intermissiontime) { client->ps.pmove.pm_type = PM_FREEZE; // can exit intermission after five seconds if (level.time > level.intermissiontime + 5.0 && (ucmd->buttons & BUTTON_ANY) ) level.exitintermission = true; return; } pm_passent = ent; if (ent->client->chase_target) { client->resp.cmd_angles[0] = SHORT2ANGLE(ucmd->angles[0]); client->resp.cmd_angles[1] = SHORT2ANGLE(ucmd->angles[1]); client->resp.cmd_angles[2] = SHORT2ANGLE(ucmd->angles[2]); } else { // set up for pmove memset (&pm, 0, sizeof(pm)); if (ent->movetype == MOVETYPE_NOCLIP) client->ps.pmove.pm_type = PM_SPECTATOR; else if (ent->s.modelindex != 255) client->ps.pmove.pm_type = PM_GIB; else if (ent->deadflag) client->ps.pmove.pm_type = PM_DEAD; else client->ps.pmove.pm_type = PM_NORMAL; client->ps.pmove.gravity = sv_gravity->value; pm.s = client->ps.pmove; for (i=0 ; i<3 ; i++) { pm.s.origin[i] = ent->s.origin[i]*8; pm.s.velocity[i] = ent->velocity[i]*8; } if (memcmp(&client->old_pmove, &pm.s, sizeof(pm.s))) { pm.snapinitial = true; // gi.dprintf ("pmove changed!\n"); } pm.cmd = *ucmd; pm.trace = PM_trace; // adds default parms pm.pointcontents = gi.pointcontents; // perform a pmove gi.Pmove (&pm); // save results of pmove client->ps.pmove = pm.s; client->old_pmove = pm.s; for (i=0 ; i<3 ; i++) { ent->s.origin[i] = pm.s.origin[i]*0.125; ent->velocity[i] = pm.s.velocity[i]*0.125; } VectorCopy (pm.mins, ent->mins); VectorCopy (pm.maxs, ent->maxs); client->resp.cmd_angles[0] = SHORT2ANGLE(ucmd->angles[0]); client->resp.cmd_angles[1] = SHORT2ANGLE(ucmd->angles[1]); client->resp.cmd_angles[2] = SHORT2ANGLE(ucmd->angles[2]); if (ent->groundentity && !pm.groundentity && (pm.cmd.upmove >= 10) && (pm.waterlevel == 0)) { gi.sound(ent, CHAN_VOICE, gi.soundindex("*jump1.wav"), 1, ATTN_NORM, 0); PlayerNoise(ent, ent->s.origin, PNOISE_SELF); } ent->viewheight = pm.viewheight; ent->waterlevel = pm.waterlevel; ent->watertype = pm.watertype; ent->groundentity = pm.groundentity; if (pm.groundentity) ent->groundentity_linkcount = pm.groundentity->linkcount; if (ent->deadflag) { client->ps.viewangles[ROLL] = 40; client->ps.viewangles[PITCH] = -15; client->ps.viewangles[YAW] = client->killer_yaw; } else { VectorCopy (pm.viewangles, client->v_angle); VectorCopy (pm.viewangles, client->ps.viewangles); } gi.linkentity (ent); if (ent->movetype != MOVETYPE_NOCLIP) G_TouchTriggers (ent); // touch other objects for (i=0 ; i<pm.numtouch ; i++) { other = pm.touchents[i]; for (j=0 ; j<i ; j++) if (pm.touchents[j] == other) break; if (j != i) continue; // duplicated if (!other->touch) continue; other->touch (other, ent, NULL, NULL); } } client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; client->latched_buttons |= client->buttons & ~client->oldbuttons; // save light level the player is standing on for // monster sighting AI ent->light_level = ucmd->lightlevel; // fire weapon from final position if needed if (client->latched_buttons & BUTTON_ATTACK) { if (client->resp.spectator) { client->latched_buttons = 0; if (client->chase_target) { client->chase_target = NULL; client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; } else GetChaseTarget(ent); } else if (!client->weapon_thunk) { client->weapon_thunk = true; Think_Weapon (ent); } } if (client->resp.spectator) { if (ucmd->upmove >= 10) { if (!(client->ps.pmove.pm_flags & PMF_JUMP_HELD)) { client->ps.pmove.pm_flags |= PMF_JUMP_HELD; if (client->chase_target) ChaseNext(ent); else GetChaseTarget(ent); } } else client->ps.pmove.pm_flags &= ~PMF_JUMP_HELD; } // update chase cam if being followed for (i = 1; i <= maxclients->value; i++) { other = g_edicts + i; if (other->inuse && other->client->chase_target == ent) UpdateChaseCam(other); } } /* ============== ClientBeginServerFrame This will be called once for each server frame, before running any other entities in the world. ============== */ void ClientBeginServerFrame (edict_t *ent) { gclient_t *client; int buttonMask; if (level.intermissiontime) return; client = ent->client; if (deathmatch->value && client->pers.spectator != client->resp.spectator && (level.time - client->respawn_time) >= 5) { spectator_respawn(ent); return; } // run weapon animations if it hasn't been done by a ucmd_t if (!client->weapon_thunk && !client->resp.spectator) Think_Weapon (ent); else client->weapon_thunk = false; if (ent->deadflag) { // wait for any button just going down if ( level.time > client->respawn_time) { // in deathmatch, only wait for attack button if (deathmatch->value) buttonMask = BUTTON_ATTACK; else buttonMask = -1; if ( ( client->latched_buttons & buttonMask ) || (deathmatch->value && ((int)dmflags->value & DF_FORCE_RESPAWN) ) ) { respawn(ent); client->latched_buttons = 0; } } return; } // add player trail so monsters can follow if (!deathmatch->value) if (!visible (ent, PlayerTrail_LastSpot() ) ) PlayerTrail_Add (ent->s.old_origin); client->latched_buttons = 0; }
412
0.964942
1
0.964942
game-dev
MEDIA
0.861133
game-dev
0.893244
1
0.893244
openvinotoolkit/openvino
2,240
src/frontends/paddle/tests/test_models/gen_scripts/generate_tril_triu.py
# Copyright (C) 2018-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # tril_triu ops paddle model generator # import sys import numpy as np import paddle from save_model import saveModel def triu(name: str, x, diagonal=0, dtype="float32"): paddle.enable_static() x = x.astype(dtype) with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): node_x = paddle.static.data(name="x", shape=x.shape, dtype=dtype) triu_outs = paddle.triu(node_x, diagonal) cpu = paddle.static.cpu_places(1) exe = paddle.static.Executor(cpu[0]) exe.run(paddle.static.default_startup_program()) outs = exe.run(feed={"x": x}, fetch_list=[triu_outs]) saveModel( name, exe, feed_vars=[node_x], fetchlist=[triu_outs], inputs=[x], outputs=outs, target_dir=sys.argv[1], ) def tril(name: str, x, diagonal=0, dtype="float32"): paddle.enable_static() x = x.astype(dtype) with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): node_x = paddle.static.data(name="x", shape=x.shape, dtype=dtype) tril_outs = paddle.tril(node_x, diagonal) cpu = paddle.static.cpu_places(1) exe = paddle.static.Executor(cpu[0]) exe.run(paddle.static.default_startup_program()) outs = exe.run(feed={"x": x}, fetch_list=[tril_outs]) saveModel( name, exe, feed_vars=[node_x], fetchlist=[tril_outs], inputs=[x], outputs=outs, target_dir=sys.argv[1], ) def main(): data = np.random.randn(4, 5) * 10 triu("triu", data) triu("triu_1", data, 1) triu("triu_2", data, -1) triu("triu_3", data, 10) triu("triu_4", data, -3) triu("triu_int32", data, dtype="int32") triu("triu_int64", data, dtype="int64") tril("tril", data) tril("tril_1", data, 1) tril("tril_2", data, -1) tril("tril_3", data, 10) tril("tril_4", data, -3) tril("tril_int32", data, dtype="int32") tril("tril_int64", data, dtype="int64") if __name__ == "__main__": main()
412
0.787485
1
0.787485
game-dev
MEDIA
0.428127
game-dev
0.86564
1
0.86564
LanKuDot/game_modules
8,476
CircularScrollingList/Scripts/ListStateProcessing/Linear/Controller/FreeMovementCtrl.cs
using System; using UnityEngine; namespace AirFishLab.ScrollingList.ListStateProcessing.Linear { /// <summary> /// Control the movement for the free movement /// </summary> /// /// There are three statuses of the movement:<para /> /// - Dragging: The moving distance is the same as the dragging distance<para /> /// - Released: When the list is released after being dragged, the moving distance /// is decided by the releasing velocity and a velocity factor curve<para /> /// - Aligning: If the aligning option is set or the list reaches the end /// in the linear mode, the movement will switch to this status to make the list /// move to the desired position. public class FreeMovementCtrl : IMovementCtrl { #region Private Variables /// <summary> /// The curve for evaluating the free movement after releasing /// </summary> private readonly VelocityMovementCurve _releasingMovementCurve; /// <summary> /// The curve for evaluating the movement of aligning the list /// </summary> private readonly DistanceMovementCurve _aligningMovementCurve; /// <summary> /// Is the list being dragged? /// </summary> private bool _isDragging; /// <summary> /// The dragging distance of the list /// </summary> private float _draggingDistance; /// <summary> /// Does it need to align the list after a movement? /// </summary> private readonly bool _toAlign; /// <summary> /// The maximum delta distance per frame /// </summary> private readonly float _maxMovingDistance; /// <summary> /// How far could the 1ist exceed the end? /// </summary> private readonly float _exceedingDistanceLimit; /// <summary> /// The velocity threshold that stops the list to align it /// </summary> /// It is used when `_alignMiddle` is true. private const float _stopVelocityThreshold = 200.0f; /// <summary> /// The function that returns the focusing position offset /// </summary> private readonly Func<float> _getFocusingPositionOffset; /// <summary> /// The function that gets the focusing state of the list /// </summary> private readonly Func<ListFocusingState> _getFocusingStateFunc; #endregion /// <summary> /// Create the movement control for the free list movement /// </summary> /// <param name="releasingCurve"> /// The curve that defines the velocity factor for the releasing movement. /// The x axis is the moving duration, and the y axis is the factor. /// </param> /// <param name="toAlign">Is it need to aligning after a movement?</param> /// <param name="maxMovingDistance"> /// The maximum delta distance per frame /// </param> /// <param name="exceedingDistanceLimit"> /// How far could the list exceed the end? /// </param> /// <param name="getFocusingPositionOffset"> /// The function that gets the focusing position offset /// </param> /// <param name="getFocusingStateFunc"> /// The function that returns the focusing state of the list /// </param> public FreeMovementCtrl( AnimationCurve releasingCurve, bool toAlign, float maxMovingDistance, float exceedingDistanceLimit, Func<float> getFocusingPositionOffset, Func<ListFocusingState> getFocusingStateFunc) { _releasingMovementCurve = new VelocityMovementCurve(releasingCurve); _aligningMovementCurve = new DistanceMovementCurve( new AnimationCurve( new Keyframe(0.0f, 0.0f, 0.0f, 8.0f), new Keyframe(0.25f, 1.0f, 0.0f, 0.0f) )); _toAlign = toAlign; _maxMovingDistance = maxMovingDistance; _exceedingDistanceLimit = exceedingDistanceLimit; _getFocusingPositionOffset = getFocusingPositionOffset; _getFocusingStateFunc = getFocusingStateFunc; } /// <summary> /// Set the base value for this new movement /// </summary> /// <param name="value"> /// If `isDragging` is true, this value is the dragging distance. /// Otherwise, this value is the base velocity for the releasing movement. /// </param> /// <param name="isDragging">Is the list being dragged?</param> public void SetMovement(float value, bool isDragging) { _isDragging = isDragging; if (isDragging) { _draggingDistance = value; // End the last movement when start dragging _aligningMovementCurve.EndMovement(); _releasingMovementCurve.EndMovement(); } else if (_getFocusingStateFunc() != ListFocusingState.Middle) { _aligningMovementCurve.SetMovement(-_getFocusingPositionOffset()); } else { _releasingMovementCurve.SetMovement(value); } } /// <summary> /// Is the movement ended? /// </summary> public bool IsMovementEnded() { return !_isDragging && _aligningMovementCurve.IsMovementEnded() && _releasingMovementCurve.IsMovementEnded(); } /// <summary> /// Get the moving distance for the next delta time /// </summary> public float GetDistance(float deltaTime) { var distance = 0.0f; var curDistance = _getFocusingPositionOffset(); var state = _getFocusingStateFunc(); // ===== Dragging ===== // if (_isDragging) { if (Mathf.Approximately(_draggingDistance, 0f)) return 0f; distance = LimitMovingDistance(_draggingDistance); // The dragging distance is only valid for one frame _draggingDistance = 0; if (!MovementUtility.IsGoingToFar( state, _exceedingDistanceLimit, curDistance + distance)) return distance; var limit = _exceedingDistanceLimit * Mathf.Sign(distance); distance = limit - curDistance; } // ===== Aligning ===== // else if (!_aligningMovementCurve.IsMovementEnded()) { distance = _aligningMovementCurve.GetDistance(deltaTime); } // ===== Releasing ===== // else if (!_releasingMovementCurve.IsMovementEnded()) { distance = LimitMovingDistance(_releasingMovementCurve.GetDistance(deltaTime)); if (!MovementUtility.IsGoingToFar( state, _exceedingDistanceLimit, curDistance + distance) && !IsTooSlow()) return distance; // Make the releasing movement end _releasingMovementCurve.EndMovement(); // Start the aligning movement instead _aligningMovementCurve.SetMovement(-_getFocusingPositionOffset()); distance = _aligningMovementCurve.GetDistance(deltaTime); } return distance; } public void EndMovement() { _isDragging = false; _releasingMovementCurve.EndMovement(); _aligningMovementCurve.EndMovement(); } /// <summary> /// Limit the moving distance /// </summary> private float LimitMovingDistance(float value) { return Mathf.Min(Mathf.Abs(value), _maxMovingDistance) * Mathf.Sign(value); } /// <summary> /// Check if the movement is too slow /// </summary> /// <returns> /// Return true if the last movement speed is too slow /// when the <c>_toAlign</c> is set. /// </returns> private bool IsTooSlow() { return _toAlign && Mathf.Abs(_releasingMovementCurve.lastVelocity) < _stopVelocityThreshold; } } }
412
0.918371
1
0.918371
game-dev
MEDIA
0.268928
game-dev
0.958702
1
0.958702
open-scan-crew/OpenScanTools
3,738
ext/ifcplusplus/include/ifcpp/IFC4/include/IfcWorkSchedule.h
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "ifcpp/model/GlobalDefines.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingObject.h" #include "IfcWorkControl.h" class IFCQUERY_EXPORT IfcWorkScheduleTypeEnum; //ENTITY class IFCQUERY_EXPORT IfcWorkSchedule : public IfcWorkControl { public: IfcWorkSchedule() = default; IfcWorkSchedule( int id ); virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ); virtual void setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self ); virtual size_t getNumAttributes() { return 14; } virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const; virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const; virtual void unlinkFromInverseCounterparts(); virtual const char* className() const { return "IfcWorkSchedule"; } virtual const std::wstring toString() const; // IfcRoot ----------------------------------------------------------- // attributes: // shared_ptr<IfcGloballyUniqueId> m_GlobalId; // shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcText> m_Description; //optional // IfcObjectDefinition ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse; // std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse; // std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse; // std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse; // std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse; // IfcObject ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_ObjectType; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse; // std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse; // IfcControl ----------------------------------------------------------- // attributes: // shared_ptr<IfcIdentifier> m_Identification; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelAssignsToControl> > m_Controls_inverse; // IfcWorkControl ----------------------------------------------------------- // attributes: // shared_ptr<IfcDateTime> m_CreationDate; // std::vector<shared_ptr<IfcPerson> > m_Creators; //optional // shared_ptr<IfcLabel> m_Purpose; //optional // shared_ptr<IfcDuration> m_Duration; //optional // shared_ptr<IfcDuration> m_TotalFloat; //optional // shared_ptr<IfcDateTime> m_StartTime; // shared_ptr<IfcDateTime> m_FinishTime; //optional // IfcWorkSchedule ----------------------------------------------------------- // attributes: shared_ptr<IfcWorkScheduleTypeEnum> m_PredefinedType; //optional };
412
0.881186
1
0.881186
game-dev
MEDIA
0.189637
game-dev
0.621501
1
0.621501
GENIVI/genivi-vehicle-simulator
2,403
Assets/Standard Assets/Utility/FOVKick.cs
using System; using System.Collections; using UnityEngine; namespace UnityStandardAssets.Utility { [Serializable] public class FOVKick { public Camera Camera; // optional camera setup, if null the main camera will be used [HideInInspector] public float originalFov; // the original fov public float FOVIncrease = 3f; // the amount the field of view increases when going into a run public float TimeToIncrease = 1f; // the amount of time the field of view will increase over public float TimeToDecrease = 1f; // the amount of time the field of view will take to return to its original size public AnimationCurve IncreaseCurve; public void Setup(Camera camera) { CheckStatus(camera); Camera = camera; originalFov = camera.fieldOfView; } private void CheckStatus(Camera camera) { if (camera == null) { throw new Exception("FOVKick camera is null, please supply the camera to the constructor"); } if (IncreaseCurve == null) { throw new Exception( "FOVKick Increase curve is null, please define the curve for the field of view kicks"); } } public void ChangeCamera(Camera camera) { Camera = camera; } public IEnumerator FOVKickUp() { float t = Mathf.Abs((Camera.fieldOfView - originalFov)/FOVIncrease); while (t < TimeToIncrease) { Camera.fieldOfView = originalFov + (IncreaseCurve.Evaluate(t/TimeToIncrease)*FOVIncrease); t += Time.deltaTime; yield return new WaitForEndOfFrame(); } } public IEnumerator FOVKickDown() { float t = Mathf.Abs((Camera.fieldOfView - originalFov)/FOVIncrease); while (t > 0) { Camera.fieldOfView = originalFov + (IncreaseCurve.Evaluate(t/TimeToDecrease)*FOVIncrease); t -= Time.deltaTime; yield return new WaitForEndOfFrame(); } //make sure that fov returns to the original size Camera.fieldOfView = originalFov; } } }
412
0.789148
1
0.789148
game-dev
MEDIA
0.845427
game-dev
0.509642
1
0.509642
unresolved3169/Turanic
1,391
src/pocketmine/event/player/PlayerToggleGlideEvent.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\event\player; use pocketmine\event\Cancellable; use pocketmine\Player; class PlayerToggleGlideEvent extends PlayerEvent implements Cancellable { public static $handlerList = null; /** @var bool */ protected $isGliding; /** * PlayerToggleGlideEvent constructor. * * @param Player $player * @param $isGliding */ public function __construct(Player $player, $isGliding){ $this->player = $player; $this->isGliding = (bool) $isGliding; } /** * @return bool */ public function isGliding(){ return $this->isGliding; } /** * @return EventName|string */ public function getName(){ return "PlayerToggleGlideEvent"; } }
412
0.767801
1
0.767801
game-dev
MEDIA
0.688451
game-dev
0.521058
1
0.521058
SeleniumHQ/seleniumhq.github.io
3,766
examples/python/tests/actions_api/test_pen.py
import math from selenium.webdriver.common.actions.action_builder import ActionBuilder from selenium.webdriver.common.actions.interaction import POINTER_PEN from selenium.webdriver.common.actions.pointer_input import PointerInput from selenium.webdriver.common.by import By def test_use_pen(driver): driver.get('https://www.selenium.dev/selenium/web/pointerActionsPage.html') pointer_area = driver.find_element(By.ID, "pointerArea") pen_input = PointerInput(POINTER_PEN, "default pen") action = ActionBuilder(driver, mouse=pen_input) action.pointer_action\ .move_to(pointer_area)\ .pointer_down()\ .move_by(2, 2)\ .pointer_up() action.perform() moves = driver.find_elements(By.CLASS_NAME, "pointermove") move_to = properties(moves[0]) down = properties(driver.find_element(By.CLASS_NAME, "pointerdown")) move_by = properties(moves[1]) up = properties(driver.find_element(By.CLASS_NAME, "pointerup")) rect = pointer_area.rect center_x = rect["x"] + rect["width"] / 2 center_y = rect["y"] + rect["height"] / 2 assert move_to["button"] == "-1" assert move_to["pointerType"] == "pen" assert move_to["pageX"] == str(math.floor(center_x)) assert move_to["pageY"] == str(math.floor(center_y)) assert down["button"] == "0" assert down["pointerType"] == "pen" assert down["pageX"] == str(math.floor(center_x)) assert down["pageY"] == str(math.floor(center_y)) assert move_by["button"] == "-1" assert move_by["pointerType"] == "pen" assert move_by["pageX"] == str(math.floor(center_x + 2)) assert move_by["pageY"] == str(math.floor(center_y + 2)) assert up["button"] == "0" assert up["pointerType"] == "pen" assert up["pageX"] == str(math.floor(center_x + 2)) assert up["pageY"] == str(math.floor(center_y + 2)) def test_set_pointer_event_properties(driver): driver.get('https://www.selenium.dev/selenium/web/pointerActionsPage.html') pointer_area = driver.find_element(By.ID, "pointerArea") pen_input = PointerInput(POINTER_PEN, "default pen") action = ActionBuilder(driver, mouse=pen_input) action.pointer_action\ .move_to(pointer_area)\ .pointer_down()\ .move_by(2, 2, tilt_x=-72, tilt_y=9, twist=86)\ .pointer_up(0) action.perform() moves = driver.find_elements(By.CLASS_NAME, "pointermove") move_to = properties(moves[0]) down = properties(driver.find_element(By.CLASS_NAME, "pointerdown")) move_by = properties(moves[1]) up = properties(driver.find_element(By.CLASS_NAME, "pointerup")) rect = pointer_area.rect center_x = rect["x"] + rect["width"] / 2 center_y = rect["y"] + rect["height"] / 2 assert move_to["button"] == "-1" assert move_to["pointerType"] == "pen" assert move_to["pageX"] == str(math.floor(center_x)) assert move_to["pageY"] == str(math.floor(center_y)) assert down["button"] == "0" assert down["pointerType"] == "pen" assert down["pageX"] == str(math.floor(center_x)) assert down["pageY"] == str(math.floor(center_y)) assert move_by["button"] == "-1" assert move_by["pointerType"] == "pen" assert move_by["pageX"] == str(math.floor(center_x + 2)) assert move_by["pageY"] == str(math.floor(center_y + 2)) assert move_by["tiltX"] == "-72" assert move_by["tiltY"] == "9" assert move_by["twist"] == "86" assert up["button"] == "0" assert up["pointerType"] == "pen" assert up["pageX"] == str(math.floor(center_x + 2)) assert up["pageY"] == str(math.floor(center_y + 2)) def properties(element): kv = element.text.split(' ', 1)[1].split(', ') return {x[0]:x[1] for x in list(map(lambda item: item.split(': '), kv))}
412
0.935469
1
0.935469
game-dev
MEDIA
0.32976
game-dev
0.857162
1
0.857162
racenis/tram-sdk
3,782
libraries/bullet/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_POLYHEDRAL_CONVEX_SHAPE_H #define BT_POLYHEDRAL_CONVEX_SHAPE_H #include "LinearMath/btMatrix3x3.h" #include "btConvexInternalShape.h" class btConvexPolyhedron; ///The btPolyhedralConvexShape is an internal interface class for polyhedral convex shapes. ATTRIBUTE_ALIGNED16(class) btPolyhedralConvexShape : public btConvexInternalShape { protected: btConvexPolyhedron* m_polyhedron; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btPolyhedralConvexShape(); virtual ~btPolyhedralConvexShape(); ///optional method mainly used to generate multiple contact points by clipping polyhedral features (faces/edges) ///experimental/work-in-progress virtual bool initializePolyhedralFeatures(int shiftVerticesByMargin = 0); virtual void setPolyhedralFeatures(btConvexPolyhedron & polyhedron); const btConvexPolyhedron* getConvexPolyhedron() const { return m_polyhedron; } //brute force implementations virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const; virtual void calculateLocalInertia(btScalar mass, btVector3 & inertia) const; virtual int getNumVertices() const = 0; virtual int getNumEdges() const = 0; virtual void getEdge(int i, btVector3& pa, btVector3& pb) const = 0; virtual void getVertex(int i, btVector3& vtx) const = 0; virtual int getNumPlanes() const = 0; virtual void getPlane(btVector3 & planeNormal, btVector3 & planeSupport, int i) const = 0; // virtual int getIndex(int i) const = 0 ; virtual bool isInside(const btVector3& pt, btScalar tolerance) const = 0; }; ///The btPolyhedralConvexAabbCachingShape adds aabb caching to the btPolyhedralConvexShape class btPolyhedralConvexAabbCachingShape : public btPolyhedralConvexShape { btVector3 m_localAabbMin; btVector3 m_localAabbMax; bool m_isLocalAabbValid; protected: void setCachedLocalAabb(const btVector3& aabbMin, const btVector3& aabbMax) { m_isLocalAabbValid = true; m_localAabbMin = aabbMin; m_localAabbMax = aabbMax; } inline void getCachedLocalAabb(btVector3& aabbMin, btVector3& aabbMax) const { btAssert(m_isLocalAabbValid); aabbMin = m_localAabbMin; aabbMax = m_localAabbMax; } protected: btPolyhedralConvexAabbCachingShape(); public: inline void getNonvirtualAabb(const btTransform& trans, btVector3& aabbMin, btVector3& aabbMax, btScalar margin) const { //lazy evaluation of local aabb btAssert(m_isLocalAabbValid); btTransformAabb(m_localAabbMin, m_localAabbMax, margin, trans, aabbMin, aabbMax); } virtual void setLocalScaling(const btVector3& scaling); virtual void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const; void recalcLocalAabb(); }; #endif //BT_POLYHEDRAL_CONVEX_SHAPE_H
412
0.860086
1
0.860086
game-dev
MEDIA
0.985041
game-dev
0.813407
1
0.813407
SmashingMods/Alchemistry
2,858
src/main/java/com/smashingmods/alchemistry/common/recipe/combiner/CombinerRecipe.java
package com.smashingmods.alchemistry.common.recipe.combiner; import com.smashingmods.alchemistry.registry.RecipeRegistry; import com.smashingmods.alchemylib.api.item.IngredientStack; import com.smashingmods.alchemylib.api.recipe.AbstractProcessingRecipe; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; import org.jetbrains.annotations.NotNull; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class CombinerRecipe extends AbstractProcessingRecipe { private final ItemStack output; private final Set<IngredientStack> input = new LinkedHashSet<>(); public CombinerRecipe(ResourceLocation pId, String pGroup, Set<IngredientStack> pInputList, ItemStack pOutput) { super(pId, pGroup); this.output = pOutput; input.addAll(pInputList); } @Override public RecipeSerializer<?> getSerializer() { return RecipeRegistry.COMBINER_SERIALIZER.get(); } @Override public RecipeType<?> getType() { return RecipeRegistry.COMBINER_TYPE.get(); } @Override public ItemStack assemble(Inventory pContainer, RegistryAccess pRegistryAccess) { return output; } @Override public ItemStack getResultItem(RegistryAccess pRegistryAccess) { return output; } @Override public String toString() { return String.format("input=[%s],output=[%s]", input, output); } @Override public int compareTo(@NotNull AbstractProcessingRecipe pRecipe) { return getId().compareTo(pRecipe.getId()); } @Override public CombinerRecipe copy() { return new CombinerRecipe(getId(), getGroup(), Set.copyOf(input), output.copy()); } public List<IngredientStack> getInput() { return new LinkedList<>(input); } public ItemStack getOutput() { return output; } public boolean matchInputs(List<ItemStack> pStacks) { List<ItemStack> inputStacks = pStacks.stream().filter(itemStack -> !itemStack.isEmpty()).toList(); // Iterate over all recipe input IngredientStacks to make sure that all match the contents of the ItemStack input list. // Each ingredient must match to *any* of the input item stacks, have an equal or greater count, and both lists must be the same size. return input.stream().allMatch(ingredientStack -> inputStacks.stream() .anyMatch(itemStack -> itemStack.getCount() >= ingredientStack.getCount() && ingredientStack.matches(itemStack))) && input.size() == inputStacks.size(); } }
412
0.856131
1
0.856131
game-dev
MEDIA
0.972702
game-dev
0.858133
1
0.858133
Athlaeos/ValhallaMMO
5,315
core/src/main/java/me/athlaeos/valhallammo/potioneffects/effect_triggers/EffectTriggerRegistry.java
package me.athlaeos.valhallammo.potioneffects.effect_triggers; import me.athlaeos.valhallammo.dom.CustomDamageType; import me.athlaeos.valhallammo.potioneffects.effect_triggers.implementations.*; import org.bukkit.entity.LivingEntity; import java.util.*; public class EffectTriggerRegistry { private static final Map<UUID, Collection<String>> entitiesAffectedCache = new HashMap<>(); private static final Map<String, EffectTrigger> registeredTriggers = new HashMap<>(); static { register(new Constant()); for (CustomDamageType type : CustomDamageType.getRegisteredTypes().values()) register(new OnDamageTick(type)); // on_<type>_damage (type lowercase) register(new OnDamageTick(null)); // on_damaged register(new OnAttack(false, false)); // on_attack_inflict_enemy register(new OnAttack(false, true)); // on_attacked_inflict_enemy register(new OnAttack(true, false)); // on_attack_inflict_self register(new OnAttack(true, true)); // on_attacked_inflict_self register(new WhileMovementModifier(null)); // while_walking register(new WhileMovementModifier(true)); // while_sprinting register(new WhileMovementModifier(false)); // while_sneaking register(new WhileStandingStill(true)); // while_standing_still register(new WhileStandingStill(false)); // while_moving register(new WhileCombatStatus(true)); // while_in_combat register(new WhileCombatStatus(false)); // while_out_of_combat register(new DayTimeOrLightExposure(null, true, null)); // while_light register(new DayTimeOrLightExposure(true, null, null)); // while_day register(new DayTimeOrLightExposure(null, false, null)); // while_dark register(new DayTimeOrLightExposure(false, null, null)); // while_night register(new DayTimeOrLightExposure(false, false, null)); // while_night_or_dark register(new DayTimeOrLightExposure(false, true, null)); // while_night_or_light register(new DayTimeOrLightExposure(true, false, null)); // while_day_or_dark register(new DayTimeOrLightExposure(true, true, null)); // while_day_or_light register(new DayTimeOrLightExposure(null, true, true)); // while_light_and_outside register(new DayTimeOrLightExposure(null, true, false)); // while_light_and_sheltered register(new DayTimeOrLightExposure(true, null, true)); // while_day_and_outside register(new DayTimeOrLightExposure(true, null, false)); // while_day_and_sheltered register(new DayTimeOrLightExposure(null, false, true)); // while_dark_and_outside register(new DayTimeOrLightExposure(null, false, false)); // while_dark_and_sheltered register(new DayTimeOrLightExposure(false, null, true)); // while_night_and_outside register(new DayTimeOrLightExposure(false, null, false)); // while_night_and_sheltered register(new DayTimeOrLightExposure(false, false, true)); // while_night_or_dark_and_outside register(new DayTimeOrLightExposure(false, false, false)); // while_night_or_dark_and_sheltered register(new DayTimeOrLightExposure(false, true, true)); // while_night_or_light_and_outside register(new DayTimeOrLightExposure(false, true, false)); // while_night_or_light_and_sheltered register(new DayTimeOrLightExposure(true, false, true)); // while_day_or_dark_and_outside register(new DayTimeOrLightExposure(true, false, false)); // while_day_or_dark_and_sheltered register(new DayTimeOrLightExposure(true, true, true)); // while_day_or_light_and_outside register(new DayTimeOrLightExposure(true, true, false)); // while_day_or_light_and_sheltered register(new Submerged(true)); // while_in_water register(new Submerged(false)); // while_not_in_water } public static void register(EffectTrigger trigger){ if (trigger.id() == null) return; registeredTriggers.put(trigger.id(), trigger); trigger.onRegister(); } public static EffectTrigger getTrigger(String id){ return registeredTriggers.get(id); } public static Map<String, EffectTrigger> getRegisteredTriggers() { return new HashMap<>(registeredTriggers); } public static boolean isEntityAffectedByTrigger(LivingEntity entity, String triggerType){ return entitiesAffectedCache.getOrDefault(entity.getUniqueId(), new HashSet<>()).contains(triggerType); } public static void setEntityAffected(LivingEntity entity, String triggerType, boolean affected){ Collection<String> affectedByTriggers = entitiesAffectedCache.getOrDefault(entity.getUniqueId(), new HashSet<>()); if (affected) affectedByTriggers.add(triggerType); else affectedByTriggers.remove(triggerType); if (affectedByTriggers.isEmpty()) entitiesAffectedCache.remove(entity.getUniqueId()); else entitiesAffectedCache.put(entity.getUniqueId(), affectedByTriggers); } public static void setEntityTriggerTypesAffected(LivingEntity entity, Collection<String> affectedByTriggers){ if (affectedByTriggers.isEmpty()) entitiesAffectedCache.remove(entity.getUniqueId()); else entitiesAffectedCache.put(entity.getUniqueId(), affectedByTriggers); } }
412
0.89492
1
0.89492
game-dev
MEDIA
0.66267
game-dev
0.906233
1
0.906233
magefree/mage
1,759
Mage.Sets/src/mage/cards/r/RushingTideZubera.java
package mage.cards.r; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.game.Game; import mage.game.permanent.Permanent; import java.util.Optional; import java.util.UUID; /** * @author LevelX2 */ public final class RushingTideZubera extends CardImpl { public RushingTideZubera(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{U}"); this.subtype.add(SubType.ZUBERA); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(3); this.toughness = new MageInt(3); // When Rushing-Tide Zubera dies, if 4 or more damage was dealt to it this turn, draw three cards. this.addAbility(new DiesSourceTriggeredAbility(new DrawCardSourceControllerEffect(3)).withInterveningIf(RushingTideZuberaCondition.instance)); } private RushingTideZubera(final RushingTideZubera card) { super(card); } @Override public RushingTideZubera copy() { return new RushingTideZubera(this); } } enum RushingTideZuberaCondition implements Condition { instance; @Override public boolean apply(Game game, Ability source) { return Optional .ofNullable(source.getSourcePermanentOrLKI(game)) .map(Permanent::getDamage) .orElse(0) >= 4; } @Override public String toString() { return "4 or more damage was dealt to it this turn"; } }
412
0.936679
1
0.936679
game-dev
MEDIA
0.899923
game-dev
0.997705
1
0.997705
OpenRA/OpenRA
3,008
OpenRA.Mods.Cnc/Traits/Render/WithGunboatBody.cs
#region Copyright & License Information /* * Copyright (c) The OpenRA Developers and Contributors * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. For more * information, see COPYING. */ #endregion using System; using System.Linq; using OpenRA.Graphics; using OpenRA.Mods.Common.Traits; using OpenRA.Mods.Common.Traits.Render; using OpenRA.Traits; namespace OpenRA.Mods.Cnc.Traits.Render { sealed class WithGunboatBodyInfo : WithSpriteBodyInfo, Requires<BodyOrientationInfo>, Requires<IFacingInfo>, Requires<TurretedInfo> { [Desc("Turreted 'Turret' key to display")] public readonly string Turret = "primary"; [SequenceReference] public readonly string LeftSequence = "left"; [SequenceReference] public readonly string RightSequence = "right"; [SequenceReference] public readonly string WakeLeftSequence = "wake-left"; [SequenceReference] public readonly string WakeRightSequence = "wake-right"; public override object Create(ActorInitializer init) { return new WithGunboatBody(init, this); } } sealed class WithGunboatBody : WithSpriteBody, ITick { readonly WithGunboatBodyInfo info; readonly Animation wake; readonly IFacing facing; readonly Turreted turret; static Func<WAngle> MakeTurretFacingFunc(Actor self) { // Turret artwork is baked into the sprite, so only the first turret makes sense. var turreted = self.TraitsImplementing<Turreted>().FirstOrDefault(); return () => turreted.WorldOrientation.Yaw; } public WithGunboatBody(ActorInitializer init, WithGunboatBodyInfo info) : base(init, info, MakeTurretFacingFunc(init.Self)) { this.info = info; var rs = init.Self.Trait<RenderSprites>(); facing = init.Self.Trait<IFacing>(); var name = rs.GetImage(init.Self); turret = init.Self.TraitsImplementing<Turreted>() .First(t => t.Name == info.Turret); wake = new Animation(init.World, name); wake.PlayRepeating(info.WakeLeftSequence); rs.Add(new AnimationWithOffset(wake, null, null, -87)); } protected override void TraitEnabled(Actor self) { base.TraitEnabled(self); turret.QuantizedFacings = DefaultAnimation.CurrentSequence.Facings; } void ITick.Tick(Actor self) { if (facing.Facing.Angle <= 512) { var left = NormalizeSequence(self, info.LeftSequence); if (DefaultAnimation.CurrentSequence.Name != left) DefaultAnimation.ReplaceAnim(left); if (wake.CurrentSequence.Name != info.WakeLeftSequence) wake.ReplaceAnim(info.WakeLeftSequence); } else { var right = NormalizeSequence(self, info.RightSequence); if (DefaultAnimation.CurrentSequence.Name != right) DefaultAnimation.ReplaceAnim(right); if (wake.CurrentSequence.Name != info.WakeRightSequence) wake.ReplaceAnim(info.WakeRightSequence); } } } }
412
0.771713
1
0.771713
game-dev
MEDIA
0.516829
game-dev
0.556141
1
0.556141
LAM0578/Dancing-Line-Fanmade-Template
2,757
Assets/Template/Scripts/Gameplay/Managers/AutoPlayManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DancingLineSample.Utility; using UnityEditor; using UnityEngine; using UnityEngine.Serialization; namespace DancingLineSample.Gameplay { [Serializable] public class AutoHitData { public AutoHitData(int timing) => Timing = timing; public int Timing; public bool Actived { get; private set; } public void Reset() => Actived = false; public void Active() => Actived = true; } public class AutoPlayManager : Singleton<AutoPlayManager> { [SerializeField] private List<AutoHitData> currentHitData = new List<AutoHitData>(); public bool EnableAuto; public int AutoPlayOffset; #if UNITY_EDITOR // 用于测试自动打击的准确度(? [Space] public bool PlayHitSound; [PropertyActive("PlayHitSound", false)] public AudioSource TestSource; [PropertyActive("PlayHitSound", false)] public AudioClip TestClip; #endif public void LoadAutoData(IEnumerable<int> hitTimings) { currentHitData = hitTimings.Where(t => t > 0).Select(t => new AutoHitData(t)).ToList(); } public List<int> GetTimingsFromCurrentHitData() { return currentHitData.Select(t => t.Timing).ToList(); } private void Update() { if (!EnableAuto || GameplayManager.Instance.LineStatus != PlayerStatus.Playing) return; int curTiming = GameplayManager.Instance.CurrentTiming - AutoPlayOffset; foreach (var data in currentHitData) { if (curTiming < data.Timing || data.Actived) continue; data.Active(); GameplayManager.Instance.Line.Turn(); #if UNITY_EDITOR if (!PlayHitSound) continue; TestSource.PlayOneShot(TestClip); #endif } } public void ResetAutoHitDataStatus() { foreach (var data in currentHitData) { data.Reset(); } } public void ActiveAutoHitDatasByTiming(int checkpointCheckpointTime) { int curTiming = checkpointCheckpointTime - AutoPlayOffset; foreach (var data in currentHitData) { if (curTiming < data.Timing || data.Actived) continue; data.Active(); } } } #if UNITY_EDITOR [CustomEditor(typeof(AutoPlayManager))] public class AutoPlayManagerEditor : Editor { private static IEnumerable<int> ParseString(string s) { s = s.Trim('[', ']'); string[] parts = s.Split(','); var result = new List<int>(); foreach (string part in parts) { if (!int.TryParse(part.Trim(), out int value)) continue; result.Add(value); } return result; } private string data; public override void OnInspectorGUI() { base.OnInspectorGUI(); var obj = (AutoPlayManager)target; data = GUILayout.TextArea(data); if (GUILayout.Button("Parse")) { var lst = ParseString(data); obj.LoadAutoData(lst); } } } #endif }
412
0.918276
1
0.918276
game-dev
MEDIA
0.794443
game-dev
0.973089
1
0.973089
oxidecomputer/omicron
5,962
wicket/src/state/rack.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Global state of the rack. //! //! This is mostly visual selection state right now. use super::inventory::ComponentId; use serde::{Deserialize, Serialize}; use slog::Logger; // Easter egg alert: Support for Knight Rider mode #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct KnightRiderMode { pub count: usize, } impl KnightRiderMode { pub fn step(&mut self) { self.count += 1; } } // The visual state of the rack #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RackState { #[serde(skip)] pub log: Option<Logger>, pub selected: ComponentId, pub knight_rider_mode: Option<KnightRiderMode>, // Useful for arrow based navigation. When we cross the switches going up // or down the rack we want to stay in the same column. This allows a user // to repeatedly hit up or down arrow and stay in the same column, as they // would expect. // // This is the only part of the state that is "historical", and doesn't // rely on the `self.selected` at all times. left_column: bool, } #[allow(clippy::new_without_default)] impl RackState { pub fn new() -> RackState { RackState { log: None, selected: ComponentId::Sled(0), knight_rider_mode: None, // Default to the left column, where sled 0 lives left_column: true, } } pub fn toggle_knight_rider_mode(&mut self) { if self.knight_rider_mode.is_none() { self.knight_rider_mode = Some(KnightRiderMode::default()); } else { self.knight_rider_mode = None; } } pub fn up(&mut self) { self.selected = match self.selected { ComponentId::Sled(14 | 15) => ComponentId::Switch(0), ComponentId::Sled(i) => ComponentId::Sled((i + 2) % 32), ComponentId::Switch(0) => ComponentId::Psc(0), ComponentId::Switch(1) => { if self.left_column { ComponentId::Sled(16) } else { ComponentId::Sled(17) } } ComponentId::Psc(0) => ComponentId::Psc(1), ComponentId::Psc(1) => ComponentId::Switch(1), _ => unreachable!(), }; } pub fn down(&mut self) { self.selected = match self.selected { ComponentId::Sled(16 | 17) => ComponentId::Switch(1), ComponentId::Sled(i) => ComponentId::Sled((30 + i) % 32), ComponentId::Switch(1) => ComponentId::Psc(1), ComponentId::Switch(0) => { if self.left_column { ComponentId::Sled(14) } else { ComponentId::Sled(15) } } ComponentId::Psc(0) => ComponentId::Switch(0), ComponentId::Psc(1) => ComponentId::Psc(0), _ => unreachable!(), }; } pub fn left_or_right(&mut self) { match self.selected { ComponentId::Sled(i) => { self.selected = ComponentId::Sled(i ^ 1); self.set_column(); } _ => (), } } pub fn next(&mut self) { self.selected = match self.selected { ComponentId::Sled(15) => ComponentId::Switch(0), ComponentId::Sled(i) => ComponentId::Sled((i + 1) % 32), ComponentId::Switch(0) => ComponentId::Psc(0), ComponentId::Psc(0) => ComponentId::Psc(1), ComponentId::Psc(1) => ComponentId::Switch(1), ComponentId::Switch(1) => ComponentId::Sled(16), _ => unreachable!(), }; self.set_column(); } pub fn prev(&mut self) { self.selected = match self.selected { ComponentId::Sled(16) => ComponentId::Switch(1), ComponentId::Sled(0) => ComponentId::Sled(31), ComponentId::Sled(i) => ComponentId::Sled(i - 1), ComponentId::Switch(1) => ComponentId::Psc(1), ComponentId::Psc(1) => ComponentId::Psc(0), ComponentId::Psc(0) => ComponentId::Switch(0), ComponentId::Switch(0) => ComponentId::Sled(15), _ => unreachable!(), }; self.set_column(); } fn set_column(&mut self) { match self.selected { ComponentId::Sled(i) => self.left_column = i % 2 == 0, _ => (), } } pub fn set_logger(&mut self, log: Logger) { self.log = Some(log); } } #[cfg(test)] mod tests { use super::*; use crate::state::ALL_COMPONENT_IDS; #[test] fn prev_next_are_opposites() { let mut state = RackState::new(); for &id in ALL_COMPONENT_IDS.iter() { state.selected = id; state.next(); state.prev(); assert_eq!( state.selected, id, "prev is not inverse of next for {id:?}" ); state.prev(); state.next(); assert_eq!( state.selected, id, "next is not inverse of prev for {id:?}" ); } } #[test] fn up_down_are_opposites() { let mut state = RackState::new(); for &id in ALL_COMPONENT_IDS.iter() { state.selected = id; state.set_column(); state.down(); state.up(); assert_eq!( state.selected, id, "up is not inverse of down for {id:?}" ); state.up(); state.down(); assert_eq!( state.selected, id, "down is not inverse of up for {id:?}" ); } } }
412
0.908194
1
0.908194
game-dev
MEDIA
0.90437
game-dev
0.909358
1
0.909358
psiroki/gzdoomxxh
2,779
wadsrc/static/zscript/actors/strife/svestuff.zs
// CTC flag spots. They are not functional and only here so that something gets spawned for them. class SVEFlagSpotRed : Inventory { States { Spawn: FLGR A 1 BRIGHT; FLGR A 0 BRIGHT; // A_FlagStandSpawn FLGR A 1 BRIGHT; // A_FlagStandCheck Wait; } } class SVEFlagSpotBlue : Inventory { States { Spawn: FLGB A 1 BRIGHT; FLGB A 0 BRIGHT; // A_FlagStandSpawn FLGB A 1 BRIGHT; // A_FlagStandCheck Wait; } } class SVEBlueChalice : Inventory { Default { +DROPPED +FLOORCLIP +INVENTORY.INVBAR Radius 10; Height 16; Tag "$TAG_OFFERINGCHALICE"; Inventory.Icon "I_RELB"; Inventory.PickupMessage "$TXT_OFFERINGCHALICE"; } States { Spawn: RELB A -1 BRIGHT; Stop; } } class SVETalismanPowerup : Inventory { } class SVETalismanRed : Inventory { Default { +DROPPED +FLOORCLIP +INVENTORY.INVBAR Radius 10; Height 16; Inventory.MaxAmount 1; Inventory.Icon "I_FLGR"; Tag "$TAG_TALISMANRED"; Inventory.PickupMessage "$MSG_TALISMANRED"; } States { Spawn: FLGR A -1 BRIGHT; Stop; } override bool TryPickup (in out Actor toucher) { let useok = Super.TryPickup (toucher); if (useok) { if (toucher.FindInventory("SVETalismanRed") && toucher.FindInventory("SVETalismanGreen") && toucher.FindInventory("SVETalismanBlue")) { toucher.A_Print("$MSG_TALISMANPOWER"); toucher.GiveInventoryType("SVETalismanPowerup"); } } return useok; } } class SVETalismanBlue : SVETalismanRed { Default { +INVENTORY.INVBAR Inventory.Icon "I_FLGB"; Tag "$TAG_TALISMANBLUE"; Inventory.PickupMessage "$MSG_TALISMANBLUE"; } States { Spawn: FLGB A -1 BRIGHT; Stop; } } class SVETalismanGreen : SVETalismanRed { Default { +INVENTORY.INVBAR Inventory.Icon "I_FLGG"; Tag "$TAG_TALISMANGREEN"; Inventory.PickupMessage "$MSG_TALISMANGREEN"; } States { Spawn: FLGG A -1 BRIGHT; Stop; } } class SVEOreSpawner : Actor { Default { +NOSECTOR } States { Spawn: TNT1 A 175 A_OreSpawner; loop; } // // A_OreSpawner // // [SVE] svillarreal // void A_OreSpawner() { if(deathmatch) return; bool inrange = false; for(int i = 0; i < MAXPLAYERS; i++) { if(!playeringame[i]) continue; if(Distance2D(players[i].mo) < 2048) { inrange = true; break; } } if(!inrange) return; let it = ThinkerIterator.Create("DegninOre"); Thinker ac; int numores = 0; while (ac = it.Next()) { if (++numores == 3) return; } Spawn("DegninOre", Pos); } } class SVEOpenDoor225 : DummyStrifeItem { override bool TryPickup (in out Actor toucher) { Door_Open(225, 16); GoAwayAndDie (); return true; } override bool SpecialDropAction (Actor dropper) { Door_Open(225, 16); Destroy (); return true; } }
412
0.945371
1
0.945371
game-dev
MEDIA
0.981934
game-dev
0.976646
1
0.976646
TerraFirmaCraft/TerraFirmaCraft
2,896
src/main/java/net/dries007/tfc/common/entities/prey/WingedPrey.java
/* * Licensed under the EUPL, Version 1.2. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 */ package net.dries007.tfc.common.entities.prey; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.dries007.tfc.client.TFCSounds; import net.dries007.tfc.common.entities.EntityHelpers; import net.dries007.tfc.common.entities.Pluckable; public class WingedPrey extends Prey implements Pluckable { public float flapping = 1f; public float oFlap; public float flap; public float oFlapSpeed; public float flapSpeed; private float nextFlap = 1f; private long lastPlucked = Long.MIN_VALUE; public WingedPrey(EntityType<? extends Prey> type, Level level, TFCSounds.EntityId sounds) { super(type, level, sounds); } @Override public void readAdditionalSaveData(CompoundTag tag) { super.readAdditionalSaveData(tag); EntityHelpers.getLongOrDefault(tag, "plucked", Long.MIN_VALUE); } @Override public void addAdditionalSaveData(CompoundTag tag) { super.addAdditionalSaveData(tag); tag.putLong("plucked", lastPlucked); } @Override public long getLastPluckedTick() { return lastPlucked; } @Override public void setLastPluckedTick(long tick) { lastPlucked = tick; } @Override protected boolean isFlapping() { return flyDist > nextFlap; } @Override protected void onFlap() { nextFlap = flyDist + flapSpeed / 2.0F; } @Override public void aiStep() { super.aiStep(); oFlap = flap; oFlapSpeed = flapSpeed; flapSpeed += (onGround() ? -1.0F : 4.0F) * 0.3F; flapSpeed = Mth.clamp(flapSpeed, 0.0F, 1.0F); if (isPassenger()) flapSpeed = 0F; if (!onGround() && flapping < 1.0F) { flapping = 1.0F; } flapping *= 0.9F; final Vec3 move = getDeltaMovement(); if (!onGround() && move.y < 0.0D) { setDeltaMovement(move.multiply(1.0D, 0.6D, 1.0D)); } flap += flapping * 2.0F; } @Override public boolean causeFallDamage(float amount, float speed, DamageSource src) { return false; } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { return pluck(player, hand, this) ? InteractionResult.sidedSuccess(level().isClientSide) : super.mobInteract(player, hand); } }
412
0.846829
1
0.846829
game-dev
MEDIA
0.996972
game-dev
0.961255
1
0.961255
openclonk/openclonk
8,489
planet/Arena.ocf/Hideout.ocs/Script.c
/*-- Hideout Author: Maikel A capture the flag scenario for two teams, both teams occupy a hideout and must steal the flag from the opposing team. The hideout is protected by doors and various weapons are there to fight with. --*/ protected func Initialize() { // Environment PlaceGrass(185); // Goal: Capture the flag, with bases in both hideouts. var goal = CreateObject(Goal_CaptureTheFlag, 0, 0, NO_OWNER); goal->SetFlagBase(1, 120, 506); goal->SetFlagBase(2, LandscapeWidth() - 120, 506); // Rules var relaunch_rule = GetRelaunchRule(); relaunch_rule->SetAllowPlayerRestart(true); relaunch_rule->SetRespawnDelay(8); relaunch_rule->SetLastWeaponUse(false); CreateObject(Rule_ObjectFade)->DoFadeTime(5 * 36); CreateObject(Rule_KillLogs); CreateObject(Rule_Gravestones); var lwidth = LandscapeWidth(); // Doors and spinwheels. var gate, wheel; gate = CreateObjectAbove(StoneDoor, 364, 448, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", 360, 446, 360, 448, 368, 448, 368, 446); gate->DoDamage(50); // Upper doors are easier to destroy gate->SetAutoControl(1); gate = CreateObjectAbove(StoneDoor, 340, 584, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", 336, 582, 336, 584, 344, 584, 344, 582); gate->SetAutoControl(1); gate = CreateObjectAbove(StoneDoor, 692, 544, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", 688, 542, 688, 544, 696, 544, 696, 542); gate->DoDamage(80); // Middle doors even easier wheel = CreateObjectAbove(SpinWheel, 660, 552, NO_OWNER); wheel->SetSwitchTarget(gate); gate = CreateObjectAbove(StoneDoor, lwidth - 364, 448, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", lwidth - 361, 446, lwidth - 361, 448, lwidth - 365, 448, lwidth - 365, 446); gate->DoDamage(50); // Upper doors are easier to destroy gate->SetAutoControl(2); gate = CreateObjectAbove(StoneDoor, lwidth - 340, 584, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", lwidth - 337, 582, lwidth - 337, 584, lwidth - 345, 584, lwidth - 345, 582); gate->SetAutoControl(2); gate = CreateObjectAbove(StoneDoor, lwidth - 692, 544, NO_OWNER); DrawMaterialQuad("Tunnel-brickback", lwidth - 689, 542, lwidth - 689, 544, lwidth - 697, 544, lwidth - 697, 542); gate->DoDamage(80); // Middle doors even easier wheel = CreateObjectAbove(SpinWheel, lwidth - 660, 552, NO_OWNER); wheel->SetSwitchTarget(gate); // Chests with weapons. var chest; chest = CreateObjectAbove(Chest, 110, 592, NO_OWNER); chest->MakeInvincible(); AddEffect("FillBaseChest", chest, 100, 6 * 36, nil, nil, true); chest = CreateObjectAbove(Chest, 25, 464, NO_OWNER); chest->MakeInvincible(); AddEffect("FillBaseChest", chest, 100, 6 * 36, nil, nil, false); chest = CreateObjectAbove(Chest, 730, 408, NO_OWNER); chest->MakeInvincible(); AddEffect("FillOtherChest", chest, 100, 6 * 36); chest = CreateObjectAbove(Chest, lwidth - 110, 592, NO_OWNER); chest->MakeInvincible(); AddEffect("FillBaseChest", chest, 100, 6 * 36, nil, nil, true); chest = CreateObjectAbove(Chest, lwidth - 25, 464, NO_OWNER); chest->MakeInvincible(); AddEffect("FillBaseChest", chest, 100, 6 * 36, nil, nil, false); chest = CreateObjectAbove(Chest, lwidth - 730, 408, NO_OWNER); chest->MakeInvincible(); AddEffect("FillOtherChest", chest, 100, 6 * 36); chest = CreateObjectAbove(Chest, lwidth/2, 512, NO_OWNER); chest->MakeInvincible(); AddEffect("FillSpecialChest", chest, 100, 4 * 36); /* // No Cannons // Cannons loaded with 12 shots. var cannon; cannon = CreateObjectAbove(Cannon, 429, 444, NO_OWNER); cannon->SetDir(DIR_Right); cannon->SetR(15); cannon->CreateContents(PowderKeg); cannon = CreateObjectAbove(Cannon, lwidth - 429, 444, NO_OWNER); cannon->SetDir(DIR_Left); cannon->SetR(-15); cannon->CreateContents(PowderKeg); */ return; } protected func InitializePlayer(int plr) { SetPlayerZoomByViewRange(plr, 600, nil, PLRZOOM_Direct); return; } // Game call from RelaunchContainer when a Clonk has left the respawn. public func OnClonkLeftRelaunch(object clonk) { // Randomize the Clonk's position a bit. var x = clonk->GetX(); var y = clonk->GetY(); clonk->SetPosition(x + RandomX(-20, 20), y + RandomX(-20, 10)); if (clonk->Stuck()) clonk->SetPosition(x, y); // Some small spark-like particles that just fly around. var sparks = { Prototype = Particles_Glimmer(), Size = PV_Random(0, 1), R = 200, G = 0, B = 200, ForceX = PV_Random(-5, 5, 10), ForceY = PV_Random(-5, 5, 10), Attach = ATTACH_Front }; if (GetPlayerTeam(clonk->GetOwner()) == 1) { sparks.R = 255; sparks.B = 0; } clonk->CreateParticle("Flash", 0, 0, PV_Random(-20, 20), PV_Random(-20, 20), PV_Random(10, 400), sparks, 100); // And a larger flash as if the Clonk had just been teleported there. var flash = { Prototype = Particles_Flash(), Size = 10, Stretch = PV_Linear(40000, 0), R = sparks.R, G = sparks.G, B = sparks.B }; clonk->CreateParticle("StarSpark", 0, 0, 0, 0, 10, flash, 1); } func RelaunchWeaponList() { return [Bow, Shield, Sword, Javelin, Shovel, Firestone, Dynamite, Loam]; } /*-- Chest filler effects --*/ global func FxFillBaseChestStart(object target, effect, int temporary, bool supply) { if (temporary) return 1; effect.supply_type = supply; var w_list; if (effect.supply_type) w_list = [Firestone, Dynamite, Ropeladder, ShieldGem]; else w_list = [Bow, Sword, Javelin, PyreGem]; for (var i = 0; i<4; i++) target->CreateChestContents(w_list[i]); return 1; } global func FxFillBaseChestTimer(object target, effect) { var w_list, maxcount; if (effect.supply_type) { w_list = [Firestone, Dynamite, Shovel, Loam, Ropeladder, SlowGem, ShieldGem]; maxcount = [2, 2, 1, 2, 1, 2, 1]; } else { w_list = [Sword, Javelin, Blunderbuss, ShieldGem, PyreGem]; maxcount = [1, 2, 1, 1, 1]; } var contents; for (var i = 0; i<target->GetLength(w_list); i++) contents += target->ContentsCount(w_list[i]); if (contents > 5) return 1; for (var i = 0; i<2 ; i++) { var r = Random(GetLength(w_list)); if (target->ContentsCount(w_list[r]) < maxcount[r]) { target->CreateChestContents(w_list[r]); i = 3; } } return 1; } global func FxFillOtherChestStart(object target, effect, int temporary) { if (temporary) return 1; var w_list = [Shield, Sword, Javelin, Club, Firestone, Dynamite]; if (target->ContentsCount() < 5) target->CreateChestContents(w_list[Random(GetLength(w_list))]); return 1; } global func FxFillOtherChestTimer(object target) { var w_list = [Shield ,Sword, Club, Bow, Dynamite, Firestone, SlowGem, ShieldGem, PyreGem]; var maxcount = [2, 1, 1, 1, 2, 2, 1, 2, 2]; var contents; for (var i = 0; i<target->GetLength(w_list); i++) contents += target->ContentsCount(w_list[i]); if (contents > 6) return 1; for (var i = 0; i<2 ; i++) { var r = Random(GetLength(w_list)); if (target->ContentsCount(w_list[r]) < maxcount[r]) { target->CreateChestContents(w_list[r]); i = 3; } } return 1; } global func FxFillSpecialChestTimer(object target) { if (Random(2)) return 1; var w_list = [PyreGem, ShieldGem, SlowGem]; var r = Random(3); if (target->ContentsCount() < 4) target->CreateChestContents(w_list[r]); var w_list = [GrappleBow, DynamiteBox, Boompack]; var r = Random(3); for (var i = 0; i < GetLength(w_list); i++) if (FindObject(Find_ID(w_list[i]))) return 1; target->CreateChestContents(w_list[r]); return 1; } global func CreateChestContents(id obj_id) { if (!this) return; var obj = CreateObjectAbove(obj_id); if (obj_id == Bow) obj->CreateContents(Arrow); if (obj_id == Blunderbuss) obj->CreateContents(LeadBullet); if (obj_id == GrappleBow) AddEffect("NotTooLong",obj, 100, 36); obj->Enter(this); return; } protected func CaptureFlagCount() { return 2;} //4 + GetPlayerCount()) / 2; } global func FxNotTooLongTimer(object target, effect) { if (!(target->Contained())) return 1; if (target->Contained()->GetID() == Clonk) effect.inClonk_time++; if (effect.inClonk_time > 40) return target->RemoveObject(); else if (effect.inClonk_time > 35) target->Message("@<c ff%x%x>%d",(41-effect.inClonk_time)*50,(41-effect.inClonk_time)*50, 41-effect.inClonk_time); } func OnClonkDeath(object clonk, int killed_by) { // create a magic healing gem on Clonk death if (Hostile(clonk->GetOwner(), killed_by)) { var gem = clonk->CreateObjectAbove(LifeGem, 0, 0, killed_by); if (GetPlayerTeam(killed_by) == 1) gem->SetGraphics("E"); } return _inherited(clonk, killed_by); }
412
0.83587
1
0.83587
game-dev
MEDIA
0.941178
game-dev
0.690421
1
0.690421
fuse-open/fuselibs
1,511
Source/Fuse.Controls.Panels/Layouts/DefaultLayout.uno
using Uno; using Uno.Collections; using Uno.UX; using Fuse; using Fuse.Controls; using Fuse.Elements; namespace Fuse.Layouts { public sealed class DefaultLayout : Layout { internal override float2 GetContentSize(Visual container, LayoutParams lp) { var size = GetElementsSize(container, lp); /* bool recalc = false; if (!fillSet.HasFlag(Size_Flags.X)) { fillSize.X = size.X; fillSet |= Size_Flags.X; recalc = true; } if (!fillSet.HasFlag(Size_Flags.Y)) { fillSize.Y = size.Y; fillSet |= Size_Flags.Y; recalc = true; } if (recalc) size = GetElementsSize(container, fillSize, fillSet); */ return size; } float2 GetElementsSize(Visual container, LayoutParams lp) { var ds = float2(0); for (var e = container.FirstChild<Visual>(); e != null; e = e.NextSibling<Visual>()) { if (!AffectsLayout(e)) continue; ds = Math.Max( ds, e.GetMarginSize(lp) ); } return ds; } internal override void ArrangePaddingBox(Visual container, float4 padding, LayoutParams lp) { var av = lp.CloneAndDerive(); av.RemoveSize(padding.XY+padding.ZW); for (var e = container.FirstChild<Visual>(); e != null; e = e.NextSibling<Visual>()) { if (!ArrangeMarginBoxSpecial(e, padding, lp)) { e.ArrangeMarginBox(padding.XY, av); } } } internal override LayoutDependent IsMarginBoxDependent( Visual child ) { //only if the element itself is dependent return LayoutDependent.Maybe; } } }
412
0.874889
1
0.874889
game-dev
MEDIA
0.375943
game-dev,graphics-rendering
0.923156
1
0.923156
bentorkington/sf2ww
5,125
FistBlue/endings.c
/* * endings.c * MT2 * * Created by Ben on 1/02/13. * Copyright 2013 Ben Torkington. All rights reserved. * */ #include "sf2.h" #include "gstate.h" #include "structs.h" #include "player.h" #include "particle.h" #include "lib.h" #include "sm.h" #include "effects.h" #include "actions.h" #include "gfxlib.h" #include "sound.h" #include "sprite.h" #include "demo.h" #include "endings.h" extern Game g; extern struct effectstate es; extern ScrollState gstate_Scroll1; extern ScrollState gstate_Scroll2; extern ScrollState gstate_Scroll3; static void sub_94aec(int d2); static void sm_ending_blanka(void); static void sub_aaa6(void) { switch (g.mode2) { case 0: break; default: break; } } static void sub_aefe(void) { switch (g.mode2) { case 0: NEXT(g.mode2); es.FadeBusy = 1; start_effect(SL0C | 0x1c, 3); break; case 2: if (!es.FadeBusy) { NEXT(g.mode2); LBResetState(); sound_cq_f0f7(); g.x02ec = 0; g.CPS.Scroll2X = 0; g.CPS.Scroll2Y = 0; g.Stage = 0x11; palette_from_game(); queuesound(SOUND_VICTORY); draw_portraits_postfight(); action_print_chant(); start_effect(0x02, 3); } break; case 4: if (!g.TextEffectBusy) { NEXT(g.mode2); g.timer3 = 180; } break; case 6: if (--g.timer3 == 0) { NEXT(g.mode2); } break; case 8: if (g.PlayersOnline == 0) { NEXT(g.mode2); g.timer2 = 150; DrawTileText(TILETEXT_GAME_OVER); queuesound(0x13); } break; case 10: if (--g.timer2 == 0) { NEXT(g.mode2); es.x5d56 = 0; start_effect(0, 4); } break; case 12: if (es.x5d56) { g.WaitMode = 0; clear_scrolls(); g.mode0 = g.mode1 = g.mode2 = g.mode3 = g.mode4 = g.mode5 = 0; ClearEffectQueue(); die_top8(); task_kill(5); task_kill(3); create_task(task_attractSequence, 1, 0, 0, 0); justdie(); } break; FATALDEFAULT; } } void game_mode_26(void) { // 7aea if (g.SkipEnding) { //aefe todo } else if (g.NotUsed) { // aaa6 todo } else { switch (g.mode2) { case 0: //a8be todo break; case 2: switch (g.BisonBeater) { // case FID_RYU: sm_ending_ryu(); break; // case FID_E_HONDA: sm_ending_ehonda(); break; case FID_BLANKA: sm_ending_blanka(); break; // case FID_GUILE: sm_ending_guile(); break; // case FID_KEN: sm_ending_ken(); break; // case FID_CHUN_LI: sm_ending_chunli(); break; // case FID_ZANGEIF: sm_ending_zangeif(); break; // case FID_DHALSIM: sm_ending_dhalsim(); break; FATALDEFAULT; } break; case 4: break; default: break; } } /* XXX */ } static void sm_ending_blanka(void) { // a554 switch (g.mode3) { case 0: switch (g.mode4) { case 0: NEXT(g.mode4); es.FadeBusy = 1; QueueEffect(0xc1c, 3); break; case 2: if (!es.FadeBusy) { NEXT(g.mode3); g.mode4 = 0; _LBResetState(); g.Stage = 0x12; TMInitForStage(); palette_from_game(); } FATALDEFAULT; } break; case 2: switch (g.mode4) { case 0: switch (g.mode5) { case 0: NEXT(g.mode5); g.CPS.DispEna = 0x780; g.ActionLibSel = 7; actionlibrary(); g.ActionLibSel = 0; g.CPS.Scroll1X = 0; g.CPS.Scroll1Y = 0x100; sub_6126(); SET_VECTFP16(gstate_Scroll2.position, 0, 768); TMSetupScroll2(&gstate_Scroll2); SET_VECTFP16(gstate_Scroll3.position, -32, 768); TMSetupScroll3(&gstate_Scroll3); sub_94aec(1); start_effect(2, 3); break; case 2: if (!g.SeqPause) { NEXT(g.mode5); es.FadeBusy = 1; QueueEffect(0x0c1c, 3); } else { proc_actions(); DSDrawAllMain(); } break; case 4: if (!es.FadeBusy) { NEXT(g.mode4); g.mode5 = 0; g.x02ec = 0; _LBResetState(); } break; FATALDEFAULT; } break; case 2: switch (g.mode5) { case 0: NEXT(g.mode5); g.CPS.DispEna = 0x780; g.ActionLibSel = 8; actionlibrary(); g.ActionLibSel = 0; g.CPS.Prio[1] = 0; g.CPS.Scroll1X = 0; g.CPS.Scroll1Y = 0x100; sub_6126(); SET_VECTFP16(gstate_Scroll2.position, 512, 768); TMSetupScroll2(&gstate_Scroll2); SET_VECTFP16(gstate_Scroll3.position, 512, 768); TMSetupScroll3(&gstate_Scroll3); sub_94aec(2); start_effect(0x2, 3); break; case 2: if (!g.SeqPause) { NEXT(g.mode2); g.mode3 = g.mode4 = g.mode5 = 0; task_kill(5); } proc_actions(); DSDrawAllMain(); break; default: break; } break; FATALDEFAULT; } break; default: break; } } static void sub_947b2(void) { // task //todo } static void sub_94aec(int d2) { g.SeqPause = TRUE; create_task(sub_947b2, 5, g.BisonBeater, d2 >> 8, d2 & 0xff); }
412
0.685257
1
0.685257
game-dev
MEDIA
0.653435
game-dev
0.938964
1
0.938964
rwmt/Multiplayer
13,881
Source/Client/AsyncTime/AsyncTimeComp.cs
using HarmonyLib; using Multiplayer.Common; using RimWorld; using RimWorld.Planet; using System; using System.Collections.Generic; using Verse; using Multiplayer.Client.Comp; using Multiplayer.Client.Factions; using Multiplayer.Client.Patches; using Multiplayer.Client.Saving; using Multiplayer.Client.Util; namespace Multiplayer.Client { public class AsyncTimeComp : IExposable, ITickable { public static Map tickingMap; public static Map executingCmdMap; public float TickRateMultiplier(TimeSpeed speed) { var comp = map.MpComp(); var enforcePause = comp.sessionManager.IsAnySessionCurrentlyPausing(map) || Multiplayer.WorldComp.sessionManager.IsAnySessionCurrentlyPausing(map); if (enforcePause) return 0f; if (mapTicks < slower.forceNormalSpeedUntil) return speed == TimeSpeed.Paused ? 0 : 1; switch (speed) { case TimeSpeed.Paused: return 0f; case TimeSpeed.Normal: return 1f; case TimeSpeed.Fast: return 3f; case TimeSpeed.Superfast: if (nothingHappeningCached) return 12f; return 6f; case TimeSpeed.Ultrafast: return 15f; default: return -1f; } } public TimeSpeed DesiredTimeSpeed => timeSpeedInt; public void SetDesiredTimeSpeed(TimeSpeed speed) { timeSpeedInt = speed; } public bool Paused => this.ActualRateMultiplier(DesiredTimeSpeed) == 0f; public float TimeToTickThrough { get; set; } public Queue<ScheduledCommand> Cmds => cmds; public int TickableId => map.uniqueID; public Map map; public int mapTicks; private TimeSpeed timeSpeedInt; public bool forcedNormalSpeed; public int eventCount; public Storyteller storyteller; public StoryWatcher storyWatcher; public TimeSlower slower = new(); public TickList tickListNormal = new(TickerType.Normal); public TickList tickListRare = new(TickerType.Rare); public TickList tickListLong = new(TickerType.Long); // Shared random state for ticking and commands public ulong randState = 1; public Queue<ScheduledCommand> cmds = new(); public AsyncTimeComp(Map map) { this.map = map; } public void Tick() { tickingMap = map; PreContext(); //SimpleProfiler.Start(); try { map.MapPreTick(); mapTicks++; Find.TickManager.ticksGameInt = mapTicks; tickListNormal.Tick(); tickListRare.Tick(); tickListLong.Tick(); TickMapSessions(); storyteller.StorytellerTick(); storyWatcher.StoryWatcherTick(); QuestManagerTickAsyncTime(); map.MapPostTick(); Find.TickManager.ticksThisFrame = 1; map.postTickVisuals.ProcessPostTickVisuals(); Find.TickManager.ticksThisFrame = 0; UpdateManagers(); CacheNothingHappening(); } finally { PostContext(); Multiplayer.game.sync.TryAddMapRandomState(map.uniqueID, randState); eventCount++; tickingMap = null; //SimpleProfiler.Pause(); } } public void TickMapSessions() { map.MpComp().sessionManager.TickSessions(); } // These are normally called in Map.MapUpdate() and react to changes in the game state even when the game is paused (not ticking) // Update() methods are not deterministic, but in multiplayer all game state changes (which don't happen during ticking) happen in commands // Thus these methods can be moved to Tick() and ExecuteCmd() by way of this method public void UpdateManagers() { map.regionGrid.UpdateClean(); map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); map.powerNetManager.UpdatePowerNetsAndConnections_First(); map.glowGrid.GlowGridUpdate_First(); } private TimeSnapshot? prevTime; private Storyteller prevStoryteller; private StoryWatcher prevStoryWatcher; public void PreContext() { if (Multiplayer.GameComp.multifaction) { map.PushFaction( map.ParentFaction is { IsPlayer: true } ? map.ParentFaction : Multiplayer.WorldComp.spectatorFaction, force: true); } prevTime = TimeSnapshot.GetAndSetFromMap(map); prevStoryteller = Current.Game.storyteller; prevStoryWatcher = Current.Game.storyWatcher; Current.Game.storyteller = storyteller; Current.Game.storyWatcher = storyWatcher; Rand.PushState(); Rand.StateCompressed = randState; // Reset the effects of SkyManager.SkyManagerUpdate map.skyManager.curSkyGlowInt = map.skyManager.CurrentSkyTarget().glow; } public void PostContext() { Current.Game.storyteller = prevStoryteller; Current.Game.storyWatcher = prevStoryWatcher; prevTime?.Set(); randState = Rand.StateCompressed; Rand.PopState(); if (Multiplayer.GameComp.multifaction) map.PopFaction(); } public void ExposeData() { Scribe_Values.Look(ref mapTicks, "mapTicks"); Scribe_Values.Look(ref timeSpeedInt, "timeSpeed"); Scribe_Deep.Look(ref storyteller, "storyteller"); Scribe_Deep.Look(ref storyWatcher, "storyWatcher"); if (Scribe.mode == LoadSaveMode.LoadingVars && storyWatcher == null) storyWatcher = new StoryWatcher(); Scribe_Custom.LookULong(ref randState, "randState", 1); } public void FinalizeInit() { cmds = new Queue<ScheduledCommand>( Multiplayer.session.dataSnapshot?.MapCmds.GetValueSafe(map.uniqueID) ?? new List<ScheduledCommand>() ); Log.Message($"Init map with cmds {cmds.Count}"); } public static bool keepTheMap; public static List<object> prevSelected; public void ExecuteCmd(ScheduledCommand cmd) { CommandType cmdType = cmd.type; LoggingByteReader data = new LoggingByteReader(cmd.data); data.Log.Node($"{cmdType} Map {map.uniqueID}"); MpContext context = data.MpContext(); keepTheMap = false; var prevMap = Current.Game.CurrentMap; Current.Game.currentMapIndex = (sbyte)map.Index; executingCmdMap = map; TickPatch.currentExecutingCmdIssuedBySelf = cmd.issuedBySelf && !TickPatch.Simulating; PreContext(); map.PushFaction(cmd.GetFaction()); context.map = map; prevSelected = Find.Selector.selected; Find.Selector.selected = new List<object>(); SelectorDeselectPatch.deselected = new List<object>(); bool prevDevMode = Prefs.data.devMode; bool prevGodMode = DebugSettings.godMode; Multiplayer.GameComp.playerData.GetValueOrDefault(cmd.playerId)?.SetContext(); try { if (cmdType == CommandType.Sync) { var handler = SyncUtil.HandleCmd(data); data.Log.current.text = handler.ToString(); } if (cmdType == CommandType.DebugTools) { DebugSync.HandleCmd(data); } if (cmdType == CommandType.MapTimeSpeed && Multiplayer.GameComp.asyncTime) { TimeSpeed speed = (TimeSpeed)data.ReadByte(); SetDesiredTimeSpeed(speed); MpLog.Debug("Set map time speed " + speed); } if (cmdType == CommandType.Designator) { HandleDesignator(data); } UpdateManagers(); } catch (Exception e) { MpLog.Error($"Map cmd exception ({cmdType}): {e}"); } finally { DebugSettings.godMode = prevGodMode; Prefs.data.devMode = prevDevMode; foreach (var deselected in SelectorDeselectPatch.deselected) prevSelected.Remove(deselected); SelectorDeselectPatch.deselected = null; Find.Selector.selected = prevSelected; prevSelected = null; Find.MainButtonsRoot.tabs.Notify_SelectedObjectDespawned(); map.PopFaction(); PostContext(); TickPatch.currentExecutingCmdIssuedBySelf = false; executingCmdMap = null; if (!keepTheMap) TrySetCurrentMap(prevMap); keepTheMap = false; Multiplayer.game.sync.TryAddCommandRandomState(randState); eventCount++; if (cmdType != CommandType.MapTimeSpeed) Multiplayer.ReaderLog.AddCurrentNode(data); } } private static void TrySetCurrentMap(Map map) { if (!Find.Maps.Contains(map)) { Current.Game.CurrentMap = Find.Maps.Any() ? Find.Maps[0] : null; Find.World.renderer.wantedMode = WorldRenderMode.Planet; } else { Current.Game.currentMapIndex = (sbyte)map.Index; } } private void HandleDesignator(ByteReader data) { Container<Area>? prevArea = null; bool SetState(Designator designator) { if (designator is Designator_AreaAllowed) { Area area = SyncSerialization.ReadSync<Area>(data); if (area == null) return false; prevArea = Designator_AreaAllowed.selectedArea; Designator_AreaAllowed.selectedArea = area; } if (designator is Designator_Install) { Thing thing = SyncSerialization.ReadSync<Thing>(data); if (thing == null) return false; DesignatorInstall_SetThingToInstall.thingToInstall = thing; } if (designator is Designator_Zone) { Zone zone = SyncSerialization.ReadSync<Zone>(data); if (zone != null) Find.Selector.selected.Add(zone); } return true; } void RestoreState() { if (prevArea.HasValue) Designator_AreaAllowed.selectedArea = prevArea.Value.Inner; DesignatorInstall_SetThingToInstall.thingToInstall = null; } var mode = SyncSerialization.ReadSync<DesignatorMode>(data); var designator = SyncSerialization.ReadSync<Designator>(data); try { if (!SetState(designator)) return; if (mode == DesignatorMode.SingleCell) { IntVec3 cell = SyncSerialization.ReadSync<IntVec3>(data); designator.DesignateSingleCell(cell); designator.Finalize(true); } else if (mode == DesignatorMode.MultiCell) { IntVec3[] cells = SyncSerialization.ReadSync<IntVec3[]>(data); designator.DesignateMultiCell(cells); } else if (mode == DesignatorMode.Thing) { Thing thing = SyncSerialization.ReadSync<Thing>(data); if (thing == null) return; designator.DesignateThing(thing); designator.Finalize(true); } } finally { RestoreState(); } } private bool nothingHappeningCached; private void CacheNothingHappening() { nothingHappeningCached = true; var list = map.mapPawns.SpawnedPawnsInFaction(Faction.OfPlayer); foreach (var pawn in list) { if (pawn.HostFaction == null && pawn.RaceProps.Humanlike && pawn.Awake()) nothingHappeningCached = false; } if (nothingHappeningCached && map.IsPlayerHome && map.dangerWatcher.DangerRating >= StoryDanger.Low) nothingHappeningCached = false; } public override string ToString() { return $"{nameof(AsyncTimeComp)}_{map}"; } public void QuestManagerTickAsyncTime() { if (!Multiplayer.GameComp.asyncTime || Paused) return; MultiplayerAsyncQuest.TickMapQuests(this); } } public enum DesignatorMode : byte { SingleCell, MultiCell, Thing } }
412
0.96048
1
0.96048
game-dev
MEDIA
0.686005
game-dev,networking
0.987781
1
0.987781
tscircuit/tscircuit-autorouter
2,114
lib/solvers/CapacityMeshSolver/CapacityMeshEdgeSolver2_NodeTreeOptimization.ts
import type { GraphicsObject } from "graphics-debug" import type { CapacityMeshEdge, CapacityMeshNode, } from "../../types/capacity-mesh-types" import { BaseSolver } from "../BaseSolver" import { distance } from "@tscircuit/math-utils" import { areNodesBordering } from "lib/utils/areNodesBordering" import { CapacityMeshEdgeSolver } from "./CapacityMeshEdgeSolver" import { CapacityNodeTree } from "lib/data-structures/CapacityNodeTree" export class CapacityMeshEdgeSolver2_NodeTreeOptimization extends CapacityMeshEdgeSolver { private nodeTree: CapacityNodeTree private currentNodeIndex: number private edgeSet: Set<string> constructor(public nodes: CapacityMeshNode[]) { super(nodes) this.MAX_ITERATIONS = 10e6 this.nodeTree = new CapacityNodeTree(this.nodes) this.currentNodeIndex = 0 this.edgeSet = new Set<string>() } _step() { if (this.currentNodeIndex >= this.nodes.length) { this.handleTargetNodes() this.solved = true return } const A = this.nodes[this.currentNodeIndex] const maybeAdjNodes = this.nodeTree.getNodesInArea( A.center.x, A.center.y, A.width * 2, A.height * 2, ) for (const B of maybeAdjNodes) { const areBordering = areNodesBordering(A, B) if (!areBordering) continue const strawNodesWithSameParent = A._strawNode && B._strawNode && A._strawParentCapacityMeshNodeId === B._strawParentCapacityMeshNodeId if ( A.capacityMeshNodeId !== B.capacityMeshNodeId && // Don't connect a node to itself !strawNodesWithSameParent && this.doNodesHaveSharedLayer(A, B) && !this.edgeSet.has(`${A.capacityMeshNodeId}-${B.capacityMeshNodeId}`) ) { this.edgeSet.add(`${A.capacityMeshNodeId}-${B.capacityMeshNodeId}`) this.edgeSet.add(`${B.capacityMeshNodeId}-${A.capacityMeshNodeId}`) this.edges.push({ capacityMeshEdgeId: this.getNextCapacityMeshEdgeId(), nodeIds: [A.capacityMeshNodeId, B.capacityMeshNodeId], }) } } this.currentNodeIndex++ } }
412
0.880114
1
0.880114
game-dev
MEDIA
0.271684
game-dev
0.960859
1
0.960859
tangziwen/CubeMiniGame
13,900
CubeEngine/External/Bullet/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btDefaultCollisionConfiguration.h" #include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h" #include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h" #ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM #include "BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h" #endif //USE_BUGGY_SPHERE_BOX_ALGORITHM #include "BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "LinearMath/btPoolAllocator.h" btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo) //btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(btStackAlloc* stackAlloc,btPoolAllocator* persistentManifoldPool,btPoolAllocator* collisionAlgorithmPool) { void* mem = NULL; if (constructionInfo.m_useEpaPenetrationAlgorithm) { mem = btAlignedAlloc(sizeof(btGjkEpaPenetrationDepthSolver),16); m_pdSolver = new (mem)btGjkEpaPenetrationDepthSolver; }else { mem = btAlignedAlloc(sizeof(btMinkowskiPenetrationDepthSolver),16); m_pdSolver = new (mem)btMinkowskiPenetrationDepthSolver; } //default CreationFunctions, filling the m_doubleDispatch table mem = btAlignedAlloc(sizeof(btConvexConvexAlgorithm::CreateFunc),16); m_convexConvexCreateFunc = new(mem) btConvexConvexAlgorithm::CreateFunc(m_pdSolver); mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16); m_convexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16); m_swappedConvexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::SwappedCreateFunc; mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::CreateFunc),16); m_compoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btCompoundCompoundCollisionAlgorithm::CreateFunc),16); m_compoundCompoundCreateFunc = new (mem)btCompoundCompoundCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::SwappedCreateFunc),16); m_swappedCompoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::SwappedCreateFunc; mem = btAlignedAlloc(sizeof(btEmptyAlgorithm::CreateFunc),16); m_emptyCreateFunc = new(mem) btEmptyAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btSphereSphereCollisionAlgorithm::CreateFunc),16); m_sphereSphereCF = new(mem) btSphereSphereCollisionAlgorithm::CreateFunc; #ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16); m_sphereBoxCF = new(mem) btSphereBoxCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16); m_boxSphereCF = new (mem)btSphereBoxCollisionAlgorithm::CreateFunc; m_boxSphereCF->m_swapped = true; #endif //USE_BUGGY_SPHERE_BOX_ALGORITHM mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16); m_sphereTriangleCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16); m_triangleSphereCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc; m_triangleSphereCF->m_swapped = true; mem = btAlignedAlloc(sizeof(btBoxBoxCollisionAlgorithm::CreateFunc),16); m_boxBoxCF = new(mem)btBoxBoxCollisionAlgorithm::CreateFunc; //convex versus plane mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16); m_convexPlaneCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc; mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16); m_planeConvexCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc; m_planeConvexCF->m_swapped = true; ///calculate maximum element size, big enough to fit any collision algorithm in the memory pool int maxSize = sizeof(btConvexConvexAlgorithm); int maxSize2 = sizeof(btConvexConcaveCollisionAlgorithm); int maxSize3 = sizeof(btCompoundCollisionAlgorithm); int maxSize4 = sizeof(btCompoundCompoundCollisionAlgorithm); int collisionAlgorithmMaxElementSize = btMax(maxSize,constructionInfo.m_customCollisionAlgorithmMaxElementSize); collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize2); collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3); collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize4); if (constructionInfo.m_persistentManifoldPool) { m_ownsPersistentManifoldPool = false; m_persistentManifoldPool = constructionInfo.m_persistentManifoldPool; } else { m_ownsPersistentManifoldPool = true; void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16); m_persistentManifoldPool = new (mem) btPoolAllocator(sizeof(btPersistentManifold),constructionInfo.m_defaultMaxPersistentManifoldPoolSize); } collisionAlgorithmMaxElementSize = (collisionAlgorithmMaxElementSize+16)&0xffffffffffff0; if (constructionInfo.m_collisionAlgorithmPool) { m_ownsCollisionAlgorithmPool = false; m_collisionAlgorithmPool = constructionInfo.m_collisionAlgorithmPool; } else { m_ownsCollisionAlgorithmPool = true; void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16); m_collisionAlgorithmPool = new(mem) btPoolAllocator(collisionAlgorithmMaxElementSize,constructionInfo.m_defaultMaxCollisionAlgorithmPoolSize); } } btDefaultCollisionConfiguration::~btDefaultCollisionConfiguration() { if (m_ownsCollisionAlgorithmPool) { m_collisionAlgorithmPool->~btPoolAllocator(); btAlignedFree(m_collisionAlgorithmPool); } if (m_ownsPersistentManifoldPool) { m_persistentManifoldPool->~btPoolAllocator(); btAlignedFree(m_persistentManifoldPool); } m_convexConvexCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_convexConvexCreateFunc); m_convexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_convexConcaveCreateFunc); m_swappedConvexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_swappedConvexConcaveCreateFunc); m_compoundCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_compoundCreateFunc); m_compoundCompoundCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree(m_compoundCompoundCreateFunc); m_swappedCompoundCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_swappedCompoundCreateFunc); m_emptyCreateFunc->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_emptyCreateFunc); m_sphereSphereCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_sphereSphereCF); #ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM m_sphereBoxCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_sphereBoxCF); m_boxSphereCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_boxSphereCF); #endif //USE_BUGGY_SPHERE_BOX_ALGORITHM m_sphereTriangleCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_sphereTriangleCF); m_triangleSphereCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_triangleSphereCF); m_boxBoxCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_boxBoxCF); m_convexPlaneCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_convexPlaneCF); m_planeConvexCF->~btCollisionAlgorithmCreateFunc(); btAlignedFree( m_planeConvexCF); m_pdSolver->~btConvexPenetrationDepthSolver(); btAlignedFree(m_pdSolver); } btCollisionAlgorithmCreateFunc* btDefaultCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) { if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1 == SPHERE_SHAPE_PROXYTYPE)) { return m_sphereSphereCF; } #ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1 == BOX_SHAPE_PROXYTYPE)) { return m_sphereBoxCF; } if ((proxyType0 == BOX_SHAPE_PROXYTYPE) && (proxyType1 == SPHERE_SHAPE_PROXYTYPE)) { return m_boxSphereCF; } #endif //USE_BUGGY_SPHERE_BOX_ALGORITHM if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1 == TRIANGLE_SHAPE_PROXYTYPE)) { return m_sphereTriangleCF; } if ((proxyType0 == TRIANGLE_SHAPE_PROXYTYPE) && (proxyType1 == SPHERE_SHAPE_PROXYTYPE)) { return m_triangleSphereCF; } if (btBroadphaseProxy::isConvex(proxyType0) && (proxyType1 == STATIC_PLANE_PROXYTYPE)) { return m_convexPlaneCF; } if (btBroadphaseProxy::isConvex(proxyType1) && (proxyType0 == STATIC_PLANE_PROXYTYPE)) { return m_planeConvexCF; } if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConvex(proxyType1)) { return m_convexConvexCreateFunc; } if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConcave(proxyType1)) { return m_convexConcaveCreateFunc; } if (btBroadphaseProxy::isConvex(proxyType1) && btBroadphaseProxy::isConcave(proxyType0)) { return m_swappedConvexConcaveCreateFunc; } if (btBroadphaseProxy::isCompound(proxyType0) && btBroadphaseProxy::isCompound(proxyType1)) { return m_compoundCompoundCreateFunc; } if (btBroadphaseProxy::isCompound(proxyType0)) { return m_compoundCreateFunc; } else { if (btBroadphaseProxy::isCompound(proxyType1)) { return m_swappedCompoundCreateFunc; } } //failed to find an algorithm return m_emptyCreateFunc; } btCollisionAlgorithmCreateFunc* btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) { if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) { return m_sphereSphereCF; } #ifdef USE_BUGGY_SPHERE_BOX_ALGORITHM if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==BOX_SHAPE_PROXYTYPE)) { return m_sphereBoxCF; } if ((proxyType0 == BOX_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) { return m_boxSphereCF; } #endif //USE_BUGGY_SPHERE_BOX_ALGORITHM if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE ) && (proxyType1==TRIANGLE_SHAPE_PROXYTYPE)) { return m_sphereTriangleCF; } if ((proxyType0 == TRIANGLE_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) { return m_triangleSphereCF; } if ((proxyType0 == BOX_SHAPE_PROXYTYPE) && (proxyType1 == BOX_SHAPE_PROXYTYPE)) { return m_boxBoxCF; } if (btBroadphaseProxy::isConvex(proxyType0) && (proxyType1 == STATIC_PLANE_PROXYTYPE)) { return m_convexPlaneCF; } if (btBroadphaseProxy::isConvex(proxyType1) && (proxyType0 == STATIC_PLANE_PROXYTYPE)) { return m_planeConvexCF; } if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConvex(proxyType1)) { return m_convexConvexCreateFunc; } if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConcave(proxyType1)) { return m_convexConcaveCreateFunc; } if (btBroadphaseProxy::isConvex(proxyType1) && btBroadphaseProxy::isConcave(proxyType0)) { return m_swappedConvexConcaveCreateFunc; } if (btBroadphaseProxy::isCompound(proxyType0) && btBroadphaseProxy::isCompound(proxyType1)) { return m_compoundCompoundCreateFunc; } if (btBroadphaseProxy::isCompound(proxyType0)) { return m_compoundCreateFunc; } else { if (btBroadphaseProxy::isCompound(proxyType1)) { return m_swappedCompoundCreateFunc; } } //failed to find an algorithm return m_emptyCreateFunc; } void btDefaultCollisionConfiguration::setConvexConvexMultipointIterations(int numPerturbationIterations, int minimumPointsPerturbationThreshold) { btConvexConvexAlgorithm::CreateFunc* convexConvex = (btConvexConvexAlgorithm::CreateFunc*) m_convexConvexCreateFunc; convexConvex->m_numPerturbationIterations = numPerturbationIterations; convexConvex->m_minimumPointsPerturbationThreshold = minimumPointsPerturbationThreshold; } void btDefaultCollisionConfiguration::setPlaneConvexMultipointIterations(int numPerturbationIterations, int minimumPointsPerturbationThreshold) { btConvexPlaneCollisionAlgorithm::CreateFunc* cpCF = (btConvexPlaneCollisionAlgorithm::CreateFunc*)m_convexPlaneCF; cpCF->m_numPerturbationIterations = numPerturbationIterations; cpCF->m_minimumPointsPerturbationThreshold = minimumPointsPerturbationThreshold; btConvexPlaneCollisionAlgorithm::CreateFunc* pcCF = (btConvexPlaneCollisionAlgorithm::CreateFunc*)m_planeConvexCF; pcCF->m_numPerturbationIterations = numPerturbationIterations; pcCF->m_minimumPointsPerturbationThreshold = minimumPointsPerturbationThreshold; }
412
0.906203
1
0.906203
game-dev
MEDIA
0.948522
game-dev
0.823758
1
0.823758
lightszero/CSLightStudio
8,359
CSLightStudio/windows/debugger/avalonEdit/ICSharpCode.AvalonEdit/Xml/TokenReader.cs
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Linq; namespace ICSharpCode.AvalonEdit.Xml { class TokenReader { string input; int inputLength; int currentLocation; // CurrentLocation is assumed to be touched and the fact does not // have to be recorded in this variable. // This stores any value bigger than that if applicable. // Acutal value is max(currentLocation, maxTouchedLocation). int maxTouchedLocation; public int InputLength { get { return inputLength; } } public int CurrentLocation { get { return currentLocation; } } public int MaxTouchedLocation { get { return Math.Max(currentLocation, maxTouchedLocation); } } public TokenReader(string input) { this.input = input; this.inputLength = input.Length; } protected bool IsEndOfFile() { return currentLocation == inputLength; } protected bool HasMoreData() { return currentLocation < inputLength; } protected void AssertHasMoreData() { AXmlParser.Assert(HasMoreData(), "Unexpected end of file"); } protected bool TryMoveNext() { if (currentLocation == inputLength) return false; currentLocation++; return true; } protected void Skip(int count) { AXmlParser.Assert(currentLocation + count <= inputLength, "Skipping after the end of file"); currentLocation += count; } protected void GoBack(int oldLocation) { AXmlParser.Assert(oldLocation <= currentLocation, "Trying to move forward"); maxTouchedLocation = Math.Max(maxTouchedLocation, currentLocation); currentLocation = oldLocation; } protected bool TryRead(char c) { if (currentLocation == inputLength) return false; if (input[currentLocation] == c) { currentLocation++; return true; } else { return false; } } protected bool TryReadAnyOf(params char[] c) { if (currentLocation == inputLength) return false; if (c.Contains(input[currentLocation])) { currentLocation++; return true; } else { return false; } } protected bool TryRead(string text) { if (TryPeek(text)) { currentLocation += text.Length; return true; } else { return false; } } protected bool TryPeekPrevious(char c, int back) { if (currentLocation - back == inputLength) return false; if (currentLocation - back < 0 ) return false; return input[currentLocation - back] == c; } protected bool TryPeek(char c) { if (currentLocation == inputLength) return false; return input[currentLocation] == c; } protected bool TryPeekAnyOf(params char[] chars) { if (currentLocation == inputLength) return false; return chars.Contains(input[currentLocation]); } protected bool TryPeek(string text) { if (!TryPeek(text[0])) return false; // Early exit maxTouchedLocation = Math.Max(maxTouchedLocation, currentLocation + (text.Length - 1)); // The following comparison 'touches' the end of file - it does depend on the end being there if (currentLocation + text.Length > inputLength) return false; return input.Substring(currentLocation, text.Length) == text; } protected bool TryPeekWhiteSpace() { if (currentLocation == inputLength) return false; char c = input[currentLocation]; return ((int)c <= 0x20) && (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } // The move functions do not have to move if already at target // The move functions allow 'overriding' of the document length protected bool TryMoveTo(char c) { return TryMoveTo(c, inputLength); } protected bool TryMoveTo(char c, int inputLength) { if (currentLocation == inputLength) return false; int index = input.IndexOf(c, currentLocation, inputLength - currentLocation); if (index != -1) { currentLocation = index; return true; } else { currentLocation = inputLength; return false; } } protected bool TryMoveToAnyOf(params char[] c) { return TryMoveToAnyOf(c, inputLength); } protected bool TryMoveToAnyOf(char[] c, int inputLength) { if (currentLocation == inputLength) return false; int index = input.IndexOfAny(c, currentLocation, inputLength - currentLocation); if (index != -1) { currentLocation = index; return true; } else { currentLocation = inputLength; return false; } } protected bool TryMoveTo(string text) { return TryMoveTo(text, inputLength); } protected bool TryMoveTo(string text, int inputLength) { if (currentLocation == inputLength) return false; int index = input.IndexOf(text, currentLocation, inputLength - currentLocation, StringComparison.Ordinal); if (index != -1) { maxTouchedLocation = index + text.Length - 1; currentLocation = index; return true; } else { currentLocation = inputLength; return false; } } protected bool TryMoveToNonWhiteSpace() { return TryMoveToNonWhiteSpace(inputLength); } protected bool TryMoveToNonWhiteSpace(int inputLength) { while(true) { if (currentLocation == inputLength) return false; // Reject end of file char c = input[currentLocation]; if (((int)c <= 0x20) && (c == ' ' || c == '\t' || c == '\n' || c == '\r')) { currentLocation++; // Accept white-space continue; } else { return true; // Found non-white-space } } } /// <summary> /// Read a name token. /// The following characters are not allowed: /// "" End of file /// " \n\r\t" Whitesapce /// "=\'\"" Attribute value /// "&lt;>/?" Tags /// </summary> /// <returns> True if read at least one character </returns> protected bool TryReadName(out string res) { int start = currentLocation; // Keep reading up to invalid character while(true) { if (currentLocation == inputLength) break; // Reject end of file char c = input[currentLocation]; if (0x41 <= (int)c) { // Accpet from 'A' onwards currentLocation++; continue; } if (c == ' ' || c == '\n' || c == '\r' || c == '\t' || // Reject whitesapce c == '=' || c == '\'' || c == '"' || // Reject attributes c == '<' || c == '>' || c == '/' || c == '?') { // Reject tags break; } else { currentLocation++; continue; // Accept other character } } if (start == currentLocation) { res = string.Empty; return false; } else { res = GetText(start, currentLocation); return true; } } protected string GetText(int start, int end) { AXmlParser.Assert(end <= currentLocation, "Reading ahead of current location"); if (start == inputLength && end == inputLength) { return string.Empty; } else { return GetCachedString(input.Substring(start, end - start)); } } Dictionary<string, string> stringCache = new Dictionary<string, string>(); int stringCacheRequestedCount; int stringCacheRequestedSize; int stringCacheStoredCount; int stringCacheStoredSize; string GetCachedString(string cached) { stringCacheRequestedCount += 1; stringCacheRequestedSize += 8 + 2 * cached.Length; // Do not bother with long strings if (cached.Length > 32) { stringCacheStoredCount += 1; stringCacheStoredSize += 8 + 2 * cached.Length; return cached; } if (stringCache.ContainsKey(cached)) { // Get the instance from the cache instead return stringCache[cached]; } else { // Add to cache stringCacheStoredCount += 1; stringCacheStoredSize += 8 + 2 * cached.Length; stringCache.Add(cached, cached); return cached; } } public void PrintStringCacheStats() { AXmlParser.Log("String cache: Requested {0} ({1} bytes); Actaully stored {2} ({3} bytes); {4}% stored", stringCacheRequestedCount, stringCacheRequestedSize, stringCacheStoredCount, stringCacheStoredSize, stringCacheRequestedSize == 0 ? 0 : stringCacheStoredSize * 100 / stringCacheRequestedSize); } } }
412
0.96209
1
0.96209
game-dev
MEDIA
0.43924
game-dev
0.983926
1
0.983926
KhronosGroup/WebGL
2,786
conformance-suites/1.0.2/conformance/ogles/GL/functions/bvec4_empty_empty_bvec4_array_frag.frag
/* ** Copyright (c) 2012 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be included ** in all copies or substantial portions of the Materials. ** ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ #ifdef GL_ES precision mediump float; #endif varying vec4 color; // Function declarations. bvec4 function(bvec4 par[3]); bool is_all(const in bvec4 par, const in bool value); bool is_all(const in bvec4 array[3], const in bvec4 value); void set_all(out bvec4 array[3], const in bvec4 value); void main (void) { bvec4 par[3]; bvec4 ret = bvec4(false, false, false, false); float gray = 0.0; // Initialize the entire array to true. set_all(par, bvec4(true, true, true, true)); ret = function(par); // The parameter should remain unchanged by the function and the function should return true. if(is_all(par, bvec4(true, true, true, true)) && is_all(ret, true)) { gray = 1.0; } gl_FragColor = vec4(gray, gray, gray, 1.0); } // Function definitions. bvec4 function(bvec4 par[3]) { // Return the value of the array. if(is_all(par, bvec4(true, true, true, true))) { // Test parameter qualifier (default is "in"). set_all(par, bvec4(false, false, false, false)); return bvec4(true, true, true, true); } else return bvec4(false, false, false, false); } bool is_all(const in bvec4 par, const in bool value) { bool ret = true; if(par[0] != value) ret = false; if(par[1] != value) ret = false; if(par[2] != value) ret = false; if(par[3] != value) ret = false; return ret; } bool is_all(const in bvec4 array[3], const in bvec4 value) { bool ret = true; if(array[0] != value) ret = false; if(array[1] != value) ret = false; if(array[2] != value) ret = false; return ret; } void set_all(out bvec4 array[3], const in bvec4 value) { array[0] = value; array[1] = value; array[2] = value; }
412
0.748286
1
0.748286
game-dev
MEDIA
0.663332
game-dev
0.789491
1
0.789491
SuperTux/supertux
10,864
src/supertux/game_object.hpp
// SuperTux // Copyright (C) 2006 Matthias Braun <matze@braunis.de> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once #include "squirrel/exposable_class.hpp" #include <algorithm> #include <string> #include <vector> #include <optional> #include <typeindex> #include "editor/object_settings.hpp" #include "supertux/game_object_component.hpp" #include "util/fade_helper.hpp" #include "util/gettext.hpp" #include "util/uid.hpp" class DrawingContext; class GameObjectComponent; class GameObjectManager; class ObjectRemoveListener; class ReaderMapping; class Writer; namespace ssq { class VM; } // namespace ssq struct GameObjectType { const std::string id; const std::string name; }; typedef std::vector<GameObjectType> GameObjectTypes; /** A helper structure to list all the type_indexes of the classes in the type hierarchy of a given class. This makes it easier to register e.g. a MrIceblock in lists for MrIceBlock, WalkingBadguy, Badguy, Portable, MovingSprite, MovingObject, and GameObject. */ struct GameObjectClasses { std::vector<std::type_index> types; GameObjectClasses& add(const std::type_info& info) { types.emplace_back(info); return *this; } }; /** This class is responsible for: * Updating and drawing the object. This should happen in the update() and draw() functions. Both are called once per frame. * Providing a safe way to remove the object by calling the remove_me functions. */ /** * @scripting * @summary Base class for all the things that make up Levels' Sectors.${SRG_NEWPARAGRAPH} Each sector of a level holds a list of active ""GameObject""s, while the game is played.${SRG_NEWPARAGRAPH} */ class GameObject : public ExposableClass { friend class GameObjectManager; public: static void register_class(ssq::VM& vm); public: GameObject(const std::string& name = ""); GameObject(const ReaderMapping& reader); virtual ~GameObject() override; /** Called after all objects have been added to the Sector and the Sector is fully constructed. If objects refer to other objects by name, those connection can be resolved here. */ virtual void finish_construction() {} inline UID get_uid() const { return m_uid; } /** This function is called once per frame and allows the object to update it's state. The dt_sec is the time that has passed since the last frame in seconds and should be the base for all timed calculations (don't use SDL_GetTicks directly as this will fail in pause mode). This function is not called in the Editor. */ virtual void update(float dt_sec) = 0; /** The GameObject should draw itself onto the provided DrawingContext if this function is called. */ virtual void draw(DrawingContext& context) = 0; /** This function saves the object. Editor will use that. */ virtual void save(Writer& writer); std::string save(); virtual std::string get_class_name() const { return "game-object"; } virtual std::string get_exposed_class_name() const override { return "GameObject"; } /** * @scripting * @description Returns the display name of the object, translated to the user's locale. */ virtual std::string get_display_name() const { return _("Unknown object"); } /** List notable classes in inheritance hierarchy of class. This makes it possible to efficiently look up all objects deriving from a particular intermediate class */ virtual GameObjectClasses get_class_types() const; /** Version checking/updating, patch information */ virtual std::vector<std::string> get_patches() const; virtual void update_version(); /** * @scripting * @description Returns the current version of the object. */ inline int get_version() const { return m_version; } /** * @scripting * @description Returns the latest version of the object. */ int get_latest_version() const; /** * @scripting * @description Checks whether the object's current version is equal to its latest one. */ bool is_up_to_date() const; /** If true only a single object of this type is allowed in a given GameObjectManager */ virtual bool is_singleton() const { return false; } /** Does this object have variable size (secret area trigger, wind, etc.) */ virtual bool has_variable_size() const { return false; } /** Indicates if the object will be saved. If false, the object will be skipped on saving and can't be cloned in the editor. */ virtual bool is_saveable() const { return true; } /** Indicates if the object's state should be tracked. If false, load_state() and save_state() calls would not do anything. */ virtual bool track_state() const { return true; } /** Indicates if the object should be added at the beginning of the object list. */ virtual bool has_object_manager_priority() const { return false; } /** Returns the amount of coins that this object is worth. This is considered when calculating all coins in a level. */ virtual int get_coins_worth() const { return 0; } /** Indicates if get_settings() is implemented. If true the editor will display Tip and ObjectMenu. */ virtual bool has_settings() const { return is_saveable(); } virtual ObjectSettings get_settings(); /** Get all types of the object, if available. **/ virtual GameObjectTypes get_types() const; /** * @scripting * @description Returns the type index of the object. */ inline int get_type() const { return m_type; } virtual void after_editor_set(); /** When level is flipped vertically */ virtual void on_flip(float height) {} /** schedules this object to be removed at the end of the frame */ virtual void remove_me() { m_scheduled_for_removal = true; } /** returns true if the object is not scheduled to be removed yet */ inline bool is_valid() const { return !m_scheduled_for_removal; } /** registers a remove listener which will be called if the object gets removed/destroyed */ void add_remove_listener(ObjectRemoveListener* listener); /** unregisters a remove listener, so it will no longer be called if the object gets removed/destroyed */ void del_remove_listener(ObjectRemoveListener* listener); inline void set_name(const std::string& name) { m_name = name; } /** * @scripting * @description Returns the name of the object. */ inline const std::string& get_name() const { return m_name; } /** stops all looping sounds */ virtual void stop_looping_sounds() {} /** continues all looping sounds */ virtual void play_looping_sounds() {} template<typename T> T* get_component() { for(auto& component : m_components) { if (T* result = dynamic_cast<T*>(component.get())) { return result; } } return nullptr; } void add_component(std::unique_ptr<GameObjectComponent> component) { m_components.emplace_back(std::move(component)); } void remove_component(GameObjectComponent* component) { auto it = std::find_if(m_components.begin(), m_components.end(), [component](const std::unique_ptr<GameObjectComponent>& lhs){ return lhs.get() == component; }); if (it != m_components.end()) { m_components.erase(it); } } /** Save/check the current state of the object. */ virtual void save_state(); virtual void check_state(); /** The editor requested the deletion of the object */ virtual void editor_delete() { remove_me(); } /** The user clicked on the object in the editor and selected it*/ virtual void editor_select() {} /** The object got deselected */ virtual void editor_deselect() {} /** Called each frame in the editor, used to keep linked objects together (e.g. platform on a path) */ virtual void editor_update() {} inline GameObjectManager* get_parent() const { return m_parent; } protected: /** Parse object type. **/ void parse_type(const ReaderMapping& reader); /** When the type has been changed from the editor. **/ enum TypeChange { INITIAL = -1 }; // "old_type < 0" indicates initial call virtual void on_type_change(int old_type) {} /** Conversion between type ID and value. **/ int type_id_to_value(const std::string& id) const; std::string type_value_to_id(int value) const; private: inline void set_uid(const UID& uid) { m_uid = uid; } private: /** The parent GameObjectManager. Set by the manager itself. */ GameObjectManager* m_parent; protected: /** a name for the gameobject, this is mostly a hint for scripts and for debugging, don't rely on names being set or being unique */ std::string m_name; /** Type of the GameObject. Used to provide special functionality, based on the child object. */ int m_type; /** Fade Helpers are for easing/fading script functions */ std::vector<std::unique_ptr<FadeHelper>> m_fade_helpers; /** Track the following creation/deletion of this object for undo. If track_state() returns false, this object would not be tracked, regardless of the value of this variable. */ bool m_track_undo; private: /** The object's type at the time of the last get_settings() call. Used to check if the type has changed. **/ int m_previous_type; /** Indicates the object's version. By default, this is equal to 1. Useful for retaining retro-compatibility for objects, whilst allowing for updated behaviour in newer levels. The version of an object can be updated from the editor. */ int m_version; /** A unique id for the object to safely refer to it. This will be set by the GameObjectManager. */ UID m_uid; /** this flag indicates if the object should be removed at the end of the frame */ bool m_scheduled_for_removal; /** The object's settings at the time of the last state save. Used to check for changes that may have occured. */ std::optional<ObjectSettings> m_last_state; std::vector<std::unique_ptr<GameObjectComponent> > m_components; std::vector<ObjectRemoveListener*> m_remove_listeners; private: GameObject(const GameObject&) = delete; GameObject& operator=(const GameObject&) = delete; };
412
0.973125
1
0.973125
game-dev
MEDIA
0.848237
game-dev
0.921928
1
0.921928
PolyEngineTeam/PolyEngine
3,497
PolyEngine/Engine/Src/Input/InputSystem.cpp
#include <EnginePCH.hpp> #include <Input/InputSystem.hpp> #include <Input/InputWorldComponent.hpp> #include <ECS/Scene.hpp> #include <Utils/Optional.hpp> using namespace Poly; void InputSystem::InputPhase(Scene* world) { InputWorldComponent* com = world->GetWorldComponent<InputWorldComponent>(); com->IsConsumed = false; com->PrevKey = com->CurrKey; com->PrevMouseButton = com->CurrMouseButton; com->CharUTF8 = nullptr; com->MouseDelta = Vector2i::ZERO; com->PrevWheel = com->CurrWheel; for (auto& pair : com->Controllers) { pair.second.PrevButton = pair.second.CurrButton; pair.second.PrevAxis = pair.second.CurrAxis; } InputQueue& InputEventsQueue = gEngine->GetInputQueue(); while (!InputEventsQueue.IsEmpty()) { InputEvent& ev = InputEventsQueue.Front(); switch (ev.Type) { case eInputEventType::KEYDOWN: if(ev.Key < eKey::_COUNT) com->CurrKey[ev.Key] = true; break; case eInputEventType::KEYUP: if(ev.Key < eKey::_COUNT) com->CurrKey[ev.Key] = false; break; case eInputEventType::TEXTCHAR: com->CharUTF8 = ev.CharUTF8; break; case eInputEventType::MOUSEBUTTONDOWN: if(ev.MouseButton < eMouseButton::_COUNT) com->CurrMouseButton[ev.MouseButton] = true; break; case eInputEventType::MOUSEBUTTONUP: if(ev.MouseButton < eMouseButton::_COUNT) com->CurrMouseButton[ev.MouseButton] = false; break; case eInputEventType::MOUSEMOVE: com->MousePos += ev.Pos; com->MouseDelta = ev.Pos; break; case eInputEventType::MOUSEPOS: // MOUSEPOS and MOUSEMOVE are received in pairs. // Setting com->MouseDelta here is (0,0) // and will result in overwriting com->MouseDelta set by MOUSEMOVE com->MousePos = ev.Pos; break; case eInputEventType::WHEELMOVE: com->CurrWheel += ev.Pos; break; case eInputEventType::CONTROLLER_ADDED: { com->Controllers[ev.JoystickID] = ControllerState(); bool controllerAssigned = false; for (size_t i = 0; i < com->PlayerIDToJoystickID.GetSize(); ++i) { if (!com->PlayerIDToJoystickID[i].HasValue()) { com->PlayerIDToJoystickID[i] = Optional<size_t>{ev.JoystickID}; com->JoystickIDToPlayerID[ev.JoystickID] = i; controllerAssigned = true; Poly::gConsole.LogDebug("Controller added in existing place"); break; } } if (!controllerAssigned) { size_t newPlayerID = com->PlayerIDToJoystickID.GetSize(); com->PlayerIDToJoystickID.PushBack(Optional<size_t>{ev.JoystickID}); com->JoystickIDToPlayerID[ev.JoystickID] = newPlayerID; Poly::gConsole.LogDebug("Controller added in new place"); } break; } case eInputEventType::CONTROLLER_REMOVED: { size_t playerID = com->JoystickIDToPlayerID.at(ev.JoystickID); com->Controllers.erase(ev.JoystickID); com->PlayerIDToJoystickID[playerID] = Optional<size_t>{}; com->JoystickIDToPlayerID.erase(ev.JoystickID); break; } case eInputEventType::CONTROLLER_BUTTON_DOWN: com->Controllers.at(ev.JoystickID).CurrButton[ev.ControllerButton] = true; break; case eInputEventType::CONTROLLER_BUTTON_UP: com->Controllers.at(ev.JoystickID).CurrButton[ev.ControllerButton] = false; break; case eInputEventType::CONTROLLER_AXIS_MOTION: com->Controllers.at(ev.JoystickID).CurrAxis[ev.ControllerAxis] = ev.AxisValue; break; case eInputEventType::_COUNT: HEAVY_ASSERTE(false, "_COUNT enum value passed to InputEventQueue::Push(), which is an invalid value"); break; } InputEventsQueue.PopFront(); } }
412
0.985343
1
0.985343
game-dev
MEDIA
0.650316
game-dev,desktop-app
0.977593
1
0.977593
TheStaticVoid/StaTech-Industry
1,237
kubejs/server_scripts/mods/create/pressing.js
// ----------------------------------------- // CREATED BY STATIC FOR USE IN // STATECH INDUSTRY // ----------------------------------------- ServerEvents.recipes(e => { // -- MOD NAMESPACE UTILITY FUNCTIONS -- // let st = (id) => `statech:create/pressing/${id}`; let cr = (id) => `create:${id}`; let mi = (id) => `modern_industrialization:${id}`; // -- PRESSING REMOVED RECIPES -- // const REMOVED_RECIPES = [ cr('pressing/sugar_cane') ]; REMOVED_RECIPES.forEach(id => e.remove( {id: id} )); // -- CUSTOM RECIPE UTILITY FUNCTION -- // let pressing = (id, item_inputs, item_outputs) => { let newRecipe = { type: cr('pressing'), } if (item_inputs) newRecipe['ingredients'] = item_inputs; if (item_outputs) newRecipe['results'] = item_outputs; e.custom(newRecipe).id(id); } // -- BRONZE PLATE -- // pressing( st('bronze_plate'), [ { tag: 'c:bronze_ingots' } ], [ { item: mi('bronze_plate'), count: 1 } ] ); // -- TIN PLATE -- // pressing( st('tin_plate'), [ { tag: 'c:tin_ingots' } ], [ { item: mi('tin_plate'), count: 1 } ] ); });
412
0.732592
1
0.732592
game-dev
MEDIA
0.510017
game-dev
0.712777
1
0.712777
D363N6UY/MapleStory-v113-Server-Eimulator
1,478
Libs/scripts/quest/20312.js
/* * Cygnus 3rd Job advancement - Flame Wizard */ var status = -1; function start(mode, type, selection) { if (mode == 0 && status == 1) { qm.sendNext("You are not ready yet."); qm.dispose(); return; } else if (mode == 0) { status--; } else { status++; } if (status == 0) { qm.sendNext("The jewel you brought back from the Transformer is the tear of the Divine Bird. It's the crystal of it's power. If the Black Wizard has his hands on this, then spells doom for all of us."); } else if (status == 1) { qm.sendYesNo("For your effort in preventing a potentially serious disaster, the Godess has bestowed upon a new title for you. Are you ready to accept it?"); } else if (status == 2) { if (qm.getPlayerStat("RSP") > (qm.getPlayerStat("LVL") - 70) * 3) { qm.sendNext("You still have way too much #bSP#k with you. You can't earn a new title like that. I strongly urge you to use more SP on your 1st and second level skills."); } else { if (qm.canHold(1142068)) { qm.gainItem(1142068, 1); qm.changeJob(1211); qm.gainAp(5); qm.sendOk(", as of this moment, you are now the Knight Sergeant. From this moment on, you shall carry yourself with dignity and respect befitting your new title The Knight Sergeant of Knights of cygnus. May your glory shines as bright as it is right now."); } else { qm.sendOk("Please make space in your inventory."); } } qm.dispose(); } } function end(mode, type, selection) { }
412
0.860041
1
0.860041
game-dev
MEDIA
0.853045
game-dev
0.915714
1
0.915714
mgerhardy/caveexpress
1,922
src/modules/ui/nodes/IUINodeEntitySelector.cpp
#include <ui/nodes/IUINodeEntitySelector.h> #include "ui/UI.h" #include "common/SpriteDefinition.h" IUINodeEntitySelector::IUINodeEntitySelector (IFrontend *frontend, int cols, int rows) : Super(frontend, cols, rows, 40 / static_cast<float>(frontend->getWidth()), 40 / static_cast<float>(frontend->getHeight())), _theme(&ThemeType::NONE) { _renderBorder = true; setPadding(0.0f); setColSpacing(0); setRowSpacing(0); } IUINodeEntitySelector::~IUINodeEntitySelector () { } void IUINodeEntitySelector::renderSelectorEntry (int index, const EntityTypeWrapper& data, int x, int y, int colWidth, int rowHeight, float alpha) const { for (Layer layer = LAYER_BACK; layer < MAX_LAYERS; ++layer) { data.sprite->render(_frontend, layer, x, y, colWidth, rowHeight, data.angle, alpha); } if (_selection && data.type->id == _selection->type->id) { _frontend->renderRect(x, y, colWidth, rowHeight, colorYellow); } } void IUINodeEntitySelector::update (uint32_t deltaTime) { Super::update(deltaTime); for (SelectorEntryIter i = _entries.begin(); i != _entries.end(); ++i) { i->sprite->update(deltaTime); } } void IUINodeEntitySelector::addEntity (const EntityType& type, const ThemeType& theme) { const Animation& animation = getAnimation(type); const SpriteDefPtr& def = SpriteDefinition::get().getFromEntityType(type, animation); if (!def) return; if (!def->theme.isNone() && def->theme != theme) return; const SpritePtr& sprite = UI::get().loadSprite(def->id); const EntityTypeWrapper w = { &type, sprite, def->angle }; addData(w); } void IUINodeEntitySelector::addEntities (const ThemeType& theme) { _theme = &theme; reset(); for (auto i = EntityType::begin(); i != EntityType::end(); ++i) { if (!shouldBeShown(*i->second)) continue; addEntity(*i->second, theme); } if (_entries.empty()) { _selection = nullptr; _selectedIndex = -1; return; } _selectedIndex = 0; select(); }
412
0.924906
1
0.924906
game-dev
MEDIA
0.420157
game-dev
0.937572
1
0.937572
xGinko/AnarchyExploitFixes
8,921
AnarchyExploitFixesLegacy/src/main/java/me/xginko/aef/modules/elytra/ElytraHelper.java
package me.xginko.aef.modules.elytra; import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.event.PacketListener; import com.github.retrooper.packetevents.event.PacketListenerAbstract; import com.github.retrooper.packetevents.event.PacketListenerPriority; import com.github.retrooper.packetevents.event.PacketReceiveEvent; import com.github.retrooper.packetevents.protocol.packettype.PacketType; import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerFlying; import me.xginko.aef.AnarchyExploitFixes; import me.xginko.aef.modules.AEFModule; import me.xginko.aef.utils.ChunkUtil; import me.xginko.aef.utils.LocationUtil; import me.xginko.aef.utils.models.ExpiringSet; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.util.NumberConversions; import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class ElytraHelper extends AEFModule implements Runnable, PacketListener, Listener { private static ElytraHelper instance; private final long speed_as_ticks = config.elytra_speed_calc_period_millis / 50L; private Map<UUID, PlayerData> playerDataMap; private PacketListenerAbstract packetListener; private NewChunksListener newChunksListener; private ScheduledExecutorService executorService; private ScheduledFuture<?> scheduledTask; public ElytraHelper() { super("elytra.elytra-speed"); instance = this; } public static ElytraHelper getInstance() { return instance; } public static boolean isNetherCeiling(Location location) { return location.getWorld().getEnvironment() == World.Environment.NETHER && location.getY() > AnarchyExploitFixes.config().nether_ceiling_max_y; } @Override public void enable() { playerDataMap = new ConcurrentHashMap<>(); packetListener = asAbstract(PacketListenerPriority.MONITOR); PacketEvents.getAPI().getEventManager().registerListener(packetListener); plugin.getServer().getPluginManager().registerEvents(this, plugin); executorService = Executors.newScheduledThreadPool(1); scheduledTask = executorService.scheduleAtFixedRate( this, 50L, config.elytra_speed_calc_period_millis, TimeUnit.MILLISECONDS); if (!ChunkUtil.canGetInhabitedTime()) { newChunksListener = new NewChunksListener(); plugin.getServer().getPluginManager().registerEvents(newChunksListener, plugin); } } @Override public void disable() { HandlerList.unregisterAll(this); if (newChunksListener != null) { HandlerList.unregisterAll(newChunksListener); newChunksListener = null; } if (packetListener != null) { PacketEvents.getAPI().getEventManager().unregisterListener(packetListener); packetListener = null; } if (playerDataMap != null) { playerDataMap.clear(); playerDataMap = null; } if (scheduledTask != null) { scheduledTask.cancel(true); scheduledTask = null; } if (executorService != null) { executorService.shutdownNow(); executorService = null; } } @Override public boolean shouldEnable() { return config.elytra_enable_at_spawn || config.elytra_enable_global || config.elytra_enable_netherceiling; } @Override public void run() { for (Map.Entry<UUID, PlayerData> entry : playerDataMap.entrySet()) { entry.getValue().calcSpeedAvg(config.elytra_calculate_3D, speed_as_ticks); } } @Override public void onPacketReceive(PacketReceiveEvent event) { if (event.isCancelled() || event.getUser() == null) return; if (event.getUser().getUUID() == null || !playerDataMap.containsKey(event.getUser().getUUID())) return; if ( event.getPacketType() == PacketType.Play.Client.PLAYER_FLYING || event.getPacketType() == PacketType.Play.Client.PLAYER_POSITION || event.getPacketType() == PacketType.Play.Client.PLAYER_POSITION_AND_ROTATION ) { playerDataMap.get(event.getUser().getUUID()) .updateLatestPosition(new WrapperPlayClientPlayerFlying(event).getLocation()); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onPlayerMove(PlayerMoveEvent event) { if (event.getPlayer().isGliding()) { playerDataMap.computeIfAbsent(event.getPlayer().getUniqueId(), k -> new PlayerData(event.getFrom(), event.getTo())) .updateLatestPosition(event.getTo()); } else { playerDataMap.remove(event.getPlayer().getUniqueId()); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onWorldChange(PlayerChangedWorldEvent event) { if (playerDataMap.containsKey(event.getPlayer().getUniqueId())) { playerDataMap.get(event.getPlayer().getUniqueId()).updateLatestPosition(event.getPlayer().getLocation()); } } public double getBlocksPerTick(PlayerMoveEvent event) { return playerDataMap.computeIfAbsent(event.getPlayer().getUniqueId(), k -> new PlayerData(event.getFrom(), event.getTo())).getSpeedAvg(); } public Location getSetbackLocation(PlayerMoveEvent event) { return playerDataMap.computeIfAbsent(event.getPlayer().getUniqueId(), k -> new PlayerData(event.getFrom(), event.getTo())).previous; } public boolean isInNewChunks(Player player) { if (ChunkUtil.canGetInhabitedTime()) { return ChunkUtil.getInhabitedTime(player.getChunk()) <= config.elytra_old_chunk_limit; } else { return newChunksListener.isInNewChunks(player.getUniqueId()); } } private static class PlayerData { public @NotNull Location previous, latest; private double speedAvg; public PlayerData(@NotNull Location previous, @NotNull Location latest) { this.previous = previous; this.latest = latest; } public double getSpeedAvg() { return speedAvg; } public void updateLatestPosition(com.github.retrooper.packetevents.protocol.world.Location location) { latest.setX(location.getX()); latest.setY(location.getY()); latest.setZ(location.getZ()); } public void updateLatestPosition(Location location) { latest.setWorld(location.getWorld()); latest.setX(location.getX()); latest.setY(location.getY()); latest.setZ(location.getZ()); } public void calcSpeedAvg(boolean using3D, long tickPeriod) { // Blockdistance per tick speedAvg = using3D ? LocationUtil.getRelativeDistance3D(previous, latest) : LocationUtil.getRelativeDistance2D(previous, latest) / tickPeriod; previous = latest.clone(); } }; private static class NewChunksListener implements Listener { /** * For 1.12 - 1.13 since Chunk#getInhabitedTime is only available starting at 1.14 */ private final Set<UUID> new_chunk_players; public NewChunksListener() { this.new_chunk_players = new ExpiringSet<>(Duration.ofMinutes(10)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) private void onChunkLoad(ChunkLoadEvent event) { for (Player player : event.getWorld().getPlayers()) { if (ChunkUtil.getChunkDistanceSquared(event.getChunk(), player.getLocation()) < NumberConversions.square(player.getViewDistance())) { if (event.isNewChunk()) { this.new_chunk_players.add(player.getUniqueId()); } else { this.new_chunk_players.remove(player.getUniqueId()); } } } } public boolean isInNewChunks(UUID player) { return new_chunk_players.contains(player); } }; }
412
0.939612
1
0.939612
game-dev
MEDIA
0.587262
game-dev
0.981035
1
0.981035
wrandelshofer/FastDoubleParser
6,750
fastdoubleparser-java17/src/main/java/ch.randelshofer.fastdoubleparser/ch/randelshofer/fastdoubleparser/FastIntegerMath.java
/* * @(#)FastIntegerMath.java * Copyright © 2024 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.fastdoubleparser; import java.math.BigInteger; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; final class FastIntegerMath { public static final BigInteger FIVE = BigInteger.valueOf(5); final static BigInteger TEN_POW_16 = BigInteger.valueOf(10_000_000_000_000_000L); final static BigInteger FIVE_POW_16 = BigInteger.valueOf(152_587_890_625L); private final static BigInteger[] SMALL_POWERS_OF_TEN = new BigInteger[]{ BigInteger.ONE, BigInteger.TEN, BigInteger.valueOf(100L), BigInteger.valueOf(1_000L), BigInteger.valueOf(10_000L), BigInteger.valueOf(100_000L), BigInteger.valueOf(1_000_000L), BigInteger.valueOf(10_000_000L), BigInteger.valueOf(100_000_000L), BigInteger.valueOf(1_000_000_000L), BigInteger.valueOf(10_000_000_000L), BigInteger.valueOf(100_000_000_000L), BigInteger.valueOf(1_000_000_000_000L), BigInteger.valueOf(10_000_000_000_000L), BigInteger.valueOf(100_000_000_000_000L), BigInteger.valueOf(1_000_000_000_000_000L) }; /** * Don't let anyone instantiate this class. */ private FastIntegerMath() { } /** * Computes the n-th power of ten. * * @param powersOfTen A map with pre-computed powers of ten * @param n the power * @return the computed power of ten */ static BigInteger computePowerOfTen(NavigableMap<Integer, BigInteger> powersOfTen, int n) { if (n < SMALL_POWERS_OF_TEN.length) { return SMALL_POWERS_OF_TEN[n]; } if (powersOfTen != null) { Map.Entry<Integer, BigInteger> floorEntry = powersOfTen.floorEntry(n); Integer floorN = floorEntry.getKey(); if (floorN == n) { return floorEntry.getValue(); } else { return FftMultiplier.multiply(floorEntry.getValue(), computePowerOfTen(powersOfTen, n - floorN)); } } return FIVE.pow(n).shiftLeft(n); } /** * Computes 10<sup>n&~15</sup>. */ static BigInteger computeTenRaisedByNFloor16Recursive(NavigableMap<Integer, BigInteger> powersOfTen, int n) { n = n & ~15; Map.Entry<Integer, BigInteger> floorEntry = powersOfTen.floorEntry(n); int floorPower = floorEntry.getKey(); BigInteger floorValue = floorEntry.getValue(); if (floorPower == n) { return floorValue; } int diff = n - floorPower; BigInteger diffValue = powersOfTen.get(diff); if (diffValue == null) { diffValue = computeTenRaisedByNFloor16Recursive(powersOfTen, diff); powersOfTen.put(diff, diffValue); } return FftMultiplier.multiply(floorValue, diffValue); } static NavigableMap<Integer, BigInteger> createPowersOfTenFloor16Map() { NavigableMap<Integer, BigInteger> powersOfTen; powersOfTen = new TreeMap<>(); powersOfTen.put(0, BigInteger.ONE); powersOfTen.put(16, TEN_POW_16); return powersOfTen; } public static long estimateNumBits(long numDecimalDigits) { // For the decimal number 10 we need log_2(10) = 3.3219 bits. // The following formula uses 3.322 * 1024 = 3401.8 rounded up // and adds 1, so that we overestimate but never underestimate // the number of bits. return (((numDecimalDigits * 3402L) >>> 10) + 1); } /** * Fills a map with powers of 10 floor 16. * * @param from the start index of the character sequence that contains the digits * @param to the end index of the character sequence that contains the digits * @return the filled map */ static NavigableMap<Integer, BigInteger> fillPowersOf10Floor16(int from, int to) { // Fill the map with powers of 5 NavigableMap<Integer, BigInteger> powers = new TreeMap<>(); powers.put(0, BigInteger.valueOf(5)); powers.put(16, FIVE_POW_16); fillPowersOfNFloor16Recursive(powers, from, to); // Shift map entries to the left to obtain powers of ten for (Iterator<Map.Entry<Integer, BigInteger>> iterator = powers.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<Integer, BigInteger> e = iterator.next(); e.setValue(e.getValue().shiftLeft(e.getKey())); } return powers; } static void fillPowersOfNFloor16Recursive(NavigableMap<Integer, BigInteger> powersOfTen, int from, int to) { int numDigits = to - from; // base case: if (numDigits <= 18) { return; } // recursion case: int mid = splitFloor16(from, to); int n = to - mid; if (!powersOfTen.containsKey(n)) { fillPowersOfNFloor16Recursive(powersOfTen, from, mid); fillPowersOfNFloor16Recursive(powersOfTen, mid, to); powersOfTen.put(n, computeTenRaisedByNFloor16Recursive(powersOfTen, n)); } } /** * Computes {@code uint128 product = (uint64)x * (uint64)y}. * <p> * References: * <dl> * <dt>Getting the high part of 64 bit integer multiplication</dt> * <dd><a href="https://stackoverflow.com/questions/28868367/getting-the-high-part-of-64-bit-integer-multiplication"> * stackoverflow</a></dd> * </dl> * * @param x uint64 factor x * @param y uint64 factor y * @return uint128 product of x and y */ static long unsignedMultiplyHigh(long x, long y) {//before Java 18 long x0 = x & 0xffffffffL, x1 = x >>> 32; long y0 = y & 0xffffffffL, y1 = y >>> 32; long p11 = x1 * y1, p01 = x0 * y1; long p10 = x1 * y0, p00 = x0 * y0; // 64-bit product + two 32-bit values long middle = p10 + (p00 >>> 32) + (p01 & 0xffffffffL); // 64-bit product + two 32-bit values return p11 + (middle >>> 32) + (p01 >>> 32); } /** * Finds middle of range with upper range half rounded up to multiple of 16. * * @param from start of range (inclusive) * @param to end of range (exclusive) * @return middle of range with upper range half rounded up to multiple of 16 */ static int splitFloor16(int from, int to) { // divide length by 2 as we want the middle, round up range half to multiples of 16 int range = (((to - from + 31) >>> 5) << 4); return to - range; } }
412
0.908168
1
0.908168
game-dev
MEDIA
0.469821
game-dev,uncategorized
0.990566
1
0.990566
LandSandBoat/server
2,436
scripts/quests/outlands/Open_Sesame.lua
----------------------------------- -- Open Sesame ----------------------------------- -- Log ID: 5, Quest ID: 165 -- Lokpix : !pos -61.942 3.949 224.900 114 ----------------------------------- local quest = Quest:new(xi.questLog.OUTLANDS, xi.quest.id.outlands.OPEN_SESAME) quest.reward = { fameArea = xi.fameArea.SELBINA_RABAO, fame = 30, keyItem = xi.ki.LOADSTONE, } local tradeOptions = { [1] = { xi.item.METEORITE, 1 }, [2] = { xi.item.SOIL_GEM, 1 }, [3] = { xi.item.SOIL_GEODE, 12 }, } quest.sections = { { check = function(player, status, vars) return status == xi.questStatus.QUEST_AVAILABLE end, [xi.zone.EASTERN_ALTEPA_DESERT] = { ['Lokpix'] = quest:progressEvent(20), onEventFinish = { [20] = function(player, csid, option, npc) if option == 1 then quest:begin(player) end end, }, }, }, { check = function(player, status, vars) return status == xi.questStatus.QUEST_ACCEPTED end, [xi.zone.EASTERN_ALTEPA_DESERT] = { ['Lokpix'] = { onTrade = function(player, npc, trade) for i = 1, #tradeOptions do if trade:getItemQty(tradeOptions[i][1]) == tradeOptions[i][2] and trade:getItemQty(xi.item.TREMORSTONE) == 1 then return quest:progressEvent(22) end end return quest:event(23) end, onTrigger = function(player, npc) return quest:event(21) end, }, onEventFinish = { [22] = function(player, csid, option, npc) if quest:complete(player) then player:tradeComplete() end end, }, }, }, { check = function(player, status, vars) return status == xi.questStatus.QUEST_COMPLETED end, [xi.zone.EASTERN_ALTEPA_DESERT] = { ['Lokpix'] = quest:event(24):replaceDefault() }, }, } return quest
412
0.890408
1
0.890408
game-dev
MEDIA
0.989386
game-dev
0.922692
1
0.922692
BenCodez/AdvancedCore
2,870
AdvancedCore/src/main/java/com/bencodez/advancedcore/api/inventory/editgui/valuetypes/EditGUIValueList.java
package com.bencodez.advancedcore.api.inventory.editgui.valuetypes; import java.util.ArrayList; import org.bukkit.Material; import org.bukkit.entity.Player; import com.bencodez.advancedcore.api.inventory.BInventory; import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent; import com.bencodez.advancedcore.api.inventory.BInventoryButton; import com.bencodez.advancedcore.api.item.ItemBuilder; import com.bencodez.advancedcore.api.valuerequest.InputMethod; import com.bencodez.advancedcore.api.valuerequest.ValueRequestBuilder; import com.bencodez.advancedcore.api.valuerequest.listeners.Listener; import com.bencodez.simpleapi.array.ArrayUtils; public abstract class EditGUIValueList extends EditGUIValue { public EditGUIValueList(String key, Object value) { setKey(key); setCurrentValue(value); } @Override public String getType() { return "list"; } @Override public void onClick(ClickEvent clickEvent) { if (getCurrentValue() == null) { setCurrentValue(new ArrayList<>()); } BInventory inv = new BInventory("Edit list: " + getKey()); inv.setMeta(clickEvent.getPlayer(), "Value", getCurrentValue()); inv.addButton(new BInventoryButton(new ItemBuilder(Material.EMERALD_BLOCK).setName("&cAdd value")) { @Override public void onClick(ClickEvent clickEvent) { new ValueRequestBuilder(new Listener<String>() { @Override public void onInput(Player player, String add) { @SuppressWarnings("unchecked") ArrayList<String> list = (ArrayList<String>) getMeta(player, "Value"); if (list == null) { list = new ArrayList<>(); } list.add(add); setValue(player, list); sendMessage(player, "&cAdded " + add + " to " + getKey()); } }, new String[] {}).request(clickEvent.getPlayer()); } }); inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cRemove value")) { @SuppressWarnings("unchecked") @Override public void onClick(ClickEvent clickEvent) { ArrayList<String> list = (ArrayList<String>) getMeta(clickEvent.getPlayer(), "Value"); if (!list.isEmpty()) { new ValueRequestBuilder(new Listener<String>() { @Override public void onInput(Player player, String add) { ArrayList<String> list = (ArrayList<String>) getMeta(player, "Value"); list.remove(add); setValue(player, list); sendMessage(player, "&cRemoved " + add + " from " + getKey()); } }, ArrayUtils.convert((ArrayList<String>) getMeta(clickEvent.getPlayer(), "Value"))) .usingMethod(InputMethod.INVENTORY).allowCustomOption(false) .request(clickEvent.getPlayer()); } else { clickEvent.getPlayer().sendMessage("No values to remove"); } } }); inv.openInventory(clickEvent.getPlayer()); } public abstract void setValue(Player player, ArrayList<String> value); }
412
0.923092
1
0.923092
game-dev
MEDIA
0.360073
game-dev
0.960348
1
0.960348
FunnyGuilds/FunnyGuilds
3,671
plugin/src/main/java/net/dzikoysk/funnyguilds/config/message/MessageService.java
package net.dzikoysk.funnyguilds.config.message; import dev.peri.yetanothermessageslibrary.BukkitMessageService; import dev.peri.yetanothermessageslibrary.SimpleSendableMessageService; import dev.peri.yetanothermessageslibrary.viewer.BukkitViewerDataSupplier; import dev.peri.yetanothermessageslibrary.viewer.ViewerFactory; import java.io.File; import java.io.IOException; import net.dzikoysk.funnyguilds.FunnyGuilds; import net.dzikoysk.funnyguilds.FunnyGuildsLogger; import net.dzikoysk.funnyguilds.config.ConfigurationFactory; import net.dzikoysk.funnyguilds.config.PluginConfiguration; import net.dzikoysk.funnyguilds.shared.FunnyIOUtils; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import panda.std.stream.PandaStream; public class MessageService extends SimpleSendableMessageService<CommandSender, MessageConfiguration, FunnyMessageDispatcher> { private final BukkitAudiences adventure; public MessageService(FunnyGuilds plugin, BukkitAudiences adventure) { super( new BukkitViewerDataSupplier(adventure), ViewerFactory.create(BukkitMessageService.wrapScheduler(plugin)), (viewerService, localeSupplier, messageSupplier) -> new FunnyMessageDispatcher(viewerService, localeSupplier, messageSupplier, user -> Bukkit.getPlayer(user.getUUID())) ); this.adventure = adventure; } public void reload() { this.getMessageRepositories().forEach((locale, repository) -> repository.load()); } public void playerQuit(Player player) { this.getViewerService().removeViewer(player); } public void close() { this.adventure.close(); } public static MessageService prepareMessageService(FunnyGuilds plugin, File languageFolder) { FunnyGuildsLogger logger = plugin.getPluginLogger(); PluginConfiguration config = plugin.getPluginConfiguration(); MessageService messageService = new MessageService( plugin, BukkitAudiences.create(plugin) ); messageService.setDefaultLocale(config.defaultLocale); messageService.registerLocaleProvider(new CommandSenderLocaleProvider()); messageService.registerLocaleProvider(new UserLocaleProvider(plugin.getFunnyServer())); // TODO: Remove in 5.0 File oldMessagesFile = new File(plugin.getDataFolder(), "messages.yml"); File newMessagesFile = new File(languageFolder, config.defaultLocale.toString() + ".yml"); if (oldMessagesFile.exists() && !newMessagesFile.exists() && !oldMessagesFile.renameTo(newMessagesFile)) { logger.warning("Could not copy legacy messages.yml to new lang directory"); } PandaStream.of(config.availableLocales).forEach(locale -> { String localeName = locale.toString(); File localeFile = new File(languageFolder, localeName + ".yml"); if (!localeFile.exists()) { try { FunnyIOUtils.copyFileFromResources(FunnyGuilds.class.getResourceAsStream("/lang/" + localeName + ".yml"), localeFile, true); } catch (IOException | NullPointerException ex) { logger.warning("Could not copy default language file: " + localeName); logger.warning("New language file will be created with default values"); } } messageService.registerRepository(locale, ConfigurationFactory.createMessageConfiguration(localeFile)); }); return messageService; } }
412
0.898958
1
0.898958
game-dev
MEDIA
0.503913
game-dev,web-backend
0.849394
1
0.849394
apache/pekko
3,381
bench-jmh/src/main/scala/org/apache/pekko/actor/DirectByteBufferPoolBenchmark.scala
/* * Licensed to the Apache Software Foundation (ASF) under one or more * license agreements; and to You under the Apache License, version 2.0: * * https://www.apache.org/licenses/LICENSE-2.0 * * This file is part of the Apache Pekko project, which was derived from Akka. */ /* * Copyright (C) 2015-2022 Lightbend Inc. <https://www.lightbend.com> */ package org.apache.pekko.actor import java.nio.ByteBuffer import java.util.Random import java.util.concurrent.TimeUnit import org.openjdk.jmh.annotations._ import org.apache.pekko.io.DirectByteBufferPool @State(Scope.Benchmark) @BenchmarkMode(Array(Mode.AverageTime)) @OutputTimeUnit(TimeUnit.NANOSECONDS) class DirectByteBufferPoolBenchmark { private val MAX_LIVE_BUFFERS = 8192 @Param(Array("00000", "00256", "01024", "04096", "16384", "65536")) var size = 0 val random = new Random private[pekko] var arteryPool: DirectByteBufferPool = _ @Setup(Level.Trial) def setup(): Unit = { arteryPool = new DirectByteBufferPool(size, MAX_LIVE_BUFFERS) } @TearDown(Level.Trial) def tearDown(): Unit = { var i = 0 while (i < MAX_LIVE_BUFFERS) { arteryPool.release(pooledDirectBuffers(i)) pooledDirectBuffers(i) = null DirectByteBufferPool.tryCleanDirectByteBuffer(unpooledDirectBuffers(i)) unpooledDirectBuffers(i) = null DirectByteBufferPool.tryCleanDirectByteBuffer(unpooledHeapBuffers(i)) unpooledHeapBuffers(i) = null i += 1 } } private val unpooledHeapBuffers = new Array[ByteBuffer](MAX_LIVE_BUFFERS) private val pooledDirectBuffers = new Array[ByteBuffer](MAX_LIVE_BUFFERS) private val unpooledDirectBuffers = new Array[ByteBuffer](MAX_LIVE_BUFFERS) import org.openjdk.jmh.annotations.Benchmark @Benchmark def unpooledHeapAllocAndRelease(): Unit = { val idx = random.nextInt(unpooledHeapBuffers.length) val oldBuf = unpooledHeapBuffers(idx) if (oldBuf ne null) DirectByteBufferPool.tryCleanDirectByteBuffer(oldBuf) unpooledHeapBuffers(idx) = ByteBuffer.allocateDirect(size) } @Benchmark def unpooledDirectAllocAndRelease(): Unit = { val idx = random.nextInt(unpooledDirectBuffers.length) val oldBuf = unpooledDirectBuffers(idx) if (oldBuf ne null) DirectByteBufferPool.tryCleanDirectByteBuffer(oldBuf) unpooledDirectBuffers(idx) = ByteBuffer.allocateDirect(size) } @Benchmark def pooledDirectAllocAndRelease(): Unit = { val idx = random.nextInt(pooledDirectBuffers.length) val oldBuf = pooledDirectBuffers(idx) if (oldBuf ne null) arteryPool.release(oldBuf) pooledDirectBuffers(idx) = arteryPool.acquire() } } object DirectByteBufferPoolBenchmark { final val numMessages = 2000000 // messages per actor pair // Constants because they are used in annotations // update according to cpu final val cores = 8 final val coresStr = "8" final val cores2xStr = "16" final val cores4xStr = "24" final val twoActors = 2 final val moreThanCoresActors = cores * 2 final val lessThanCoresActors = cores / 2 final val sameAsCoresActors = cores final val totalMessagesTwoActors = numMessages final val totalMessagesMoreThanCores = (moreThanCoresActors * numMessages) / 2 final val totalMessagesLessThanCores = (lessThanCoresActors * numMessages) / 2 final val totalMessagesSameAsCores = (sameAsCoresActors * numMessages) / 2 }
412
0.816577
1
0.816577
game-dev
MEDIA
0.127569
game-dev
0.90009
1
0.90009
ddiakopoulos/sandbox
21,521
vr-environment/third_party/bullet3/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp
/* * Copyright (c) 2005 Erwin Coumans http://continuousphysics.com/Bullet/ * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies. * Erwin Coumans makes no representations about the suitability * of this software for any purpose. * It is provided "as is" without express or implied warranty. */ #include "LinearMath/btVector3.h" #include "btRaycastVehicle.h" #include "BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h" #include "BulletDynamics/ConstraintSolver/btJacobianEntry.h" #include "LinearMath/btQuaternion.h" #include "BulletDynamics/Dynamics/btDynamicsWorld.h" #include "btVehicleRaycaster.h" #include "btWheelInfo.h" #include "LinearMath/btMinMax.h" #include "LinearMath/btIDebugDraw.h" #include "BulletDynamics/ConstraintSolver/btContactConstraint.h" #define ROLLING_INFLUENCE_FIX btRigidBody& btActionInterface::getFixedBody() { static btRigidBody s_fixed(0, 0,0); s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.))); return s_fixed; } btRaycastVehicle::btRaycastVehicle(const btVehicleTuning& tuning,btRigidBody* chassis, btVehicleRaycaster* raycaster ) :m_vehicleRaycaster(raycaster), m_pitchControl(btScalar(0.)) { m_chassisBody = chassis; m_indexRightAxis = 0; m_indexUpAxis = 2; m_indexForwardAxis = 1; defaultInit(tuning); } void btRaycastVehicle::defaultInit(const btVehicleTuning& tuning) { (void)tuning; m_currentVehicleSpeedKmHour = btScalar(0.); m_steeringValue = btScalar(0.); } btRaycastVehicle::~btRaycastVehicle() { } // // basically most of the code is general for 2 or 4 wheel vehicles, but some of it needs to be reviewed // btWheelInfo& btRaycastVehicle::addWheel( const btVector3& connectionPointCS, const btVector3& wheelDirectionCS0,const btVector3& wheelAxleCS, btScalar suspensionRestLength, btScalar wheelRadius,const btVehicleTuning& tuning, bool isFrontWheel) { btWheelInfoConstructionInfo ci; ci.m_chassisConnectionCS = connectionPointCS; ci.m_wheelDirectionCS = wheelDirectionCS0; ci.m_wheelAxleCS = wheelAxleCS; ci.m_suspensionRestLength = suspensionRestLength; ci.m_wheelRadius = wheelRadius; ci.m_suspensionStiffness = tuning.m_suspensionStiffness; ci.m_wheelsDampingCompression = tuning.m_suspensionCompression; ci.m_wheelsDampingRelaxation = tuning.m_suspensionDamping; ci.m_frictionSlip = tuning.m_frictionSlip; ci.m_bIsFrontWheel = isFrontWheel; ci.m_maxSuspensionTravelCm = tuning.m_maxSuspensionTravelCm; ci.m_maxSuspensionForce = tuning.m_maxSuspensionForce; m_wheelInfo.push_back( btWheelInfo(ci)); btWheelInfo& wheel = m_wheelInfo[getNumWheels()-1]; updateWheelTransformsWS( wheel , false ); updateWheelTransform(getNumWheels()-1,false); return wheel; } const btTransform& btRaycastVehicle::getWheelTransformWS( int wheelIndex ) const { btAssert(wheelIndex < getNumWheels()); const btWheelInfo& wheel = m_wheelInfo[wheelIndex]; return wheel.m_worldTransform; } void btRaycastVehicle::updateWheelTransform( int wheelIndex , bool interpolatedTransform) { btWheelInfo& wheel = m_wheelInfo[ wheelIndex ]; updateWheelTransformsWS(wheel,interpolatedTransform); btVector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS; const btVector3& right = wheel.m_raycastInfo.m_wheelAxleWS; btVector3 fwd = up.cross(right); fwd = fwd.normalize(); // up = right.cross(fwd); // up.normalize(); //rotate around steering over de wheelAxleWS btScalar steering = wheel.m_steering; btQuaternion steeringOrn(up,steering);//wheel.m_steering); btMatrix3x3 steeringMat(steeringOrn); btQuaternion rotatingOrn(right,-wheel.m_rotation); btMatrix3x3 rotatingMat(rotatingOrn); btMatrix3x3 basis2( right[0],fwd[0],up[0], right[1],fwd[1],up[1], right[2],fwd[2],up[2] ); wheel.m_worldTransform.setBasis(steeringMat * rotatingMat * basis2); wheel.m_worldTransform.setOrigin( wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength ); } void btRaycastVehicle::resetSuspension() { int i; for (i=0;i<m_wheelInfo.size(); i++) { btWheelInfo& wheel = m_wheelInfo[i]; wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength(); wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS; //wheel_info.setContactFriction(btScalar(0.0)); wheel.m_clippedInvContactDotSuspension = btScalar(1.0); } } void btRaycastVehicle::updateWheelTransformsWS(btWheelInfo& wheel , bool interpolatedTransform) { wheel.m_raycastInfo.m_isInContact = false; btTransform chassisTrans = getChassisWorldTransform(); if (interpolatedTransform && (getRigidBody()->getMotionState())) { getRigidBody()->getMotionState()->getWorldTransform(chassisTrans); } wheel.m_raycastInfo.m_hardPointWS = chassisTrans( wheel.m_chassisConnectionPointCS ); wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.getBasis() * wheel.m_wheelDirectionCS ; wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.getBasis() * wheel.m_wheelAxleCS; } btScalar btRaycastVehicle::rayCast(btWheelInfo& wheel) { updateWheelTransformsWS( wheel,false); btScalar depth = -1; btScalar raylen = wheel.getSuspensionRestLength()+wheel.m_wheelsRadius; btVector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen); const btVector3& source = wheel.m_raycastInfo.m_hardPointWS; wheel.m_raycastInfo.m_contactPointWS = source + rayvector; const btVector3& target = wheel.m_raycastInfo.m_contactPointWS; btScalar param = btScalar(0.); btVehicleRaycaster::btVehicleRaycasterResult rayResults; btAssert(m_vehicleRaycaster); void* object = m_vehicleRaycaster->castRay(source,target,rayResults); wheel.m_raycastInfo.m_groundObject = 0; if (object) { param = rayResults.m_distFraction; depth = raylen * rayResults.m_distFraction; wheel.m_raycastInfo.m_contactNormalWS = rayResults.m_hitNormalInWorld; wheel.m_raycastInfo.m_isInContact = true; wheel.m_raycastInfo.m_groundObject = &getFixedBody();///@todo for driving on dynamic/movable objects!; //wheel.m_raycastInfo.m_groundObject = object; btScalar hitDistance = param*raylen; wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelsRadius; //clamp on max suspension travel btScalar minSuspensionLength = wheel.getSuspensionRestLength() - wheel.m_maxSuspensionTravelCm*btScalar(0.01); btScalar maxSuspensionLength = wheel.getSuspensionRestLength()+ wheel.m_maxSuspensionTravelCm*btScalar(0.01); if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength; } if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength; } wheel.m_raycastInfo.m_contactPointWS = rayResults.m_hitPointInWorld; btScalar denominator= wheel.m_raycastInfo.m_contactNormalWS.dot( wheel.m_raycastInfo.m_wheelDirectionWS ); btVector3 chassis_velocity_at_contactPoint; btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition(); chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos); btScalar projVel = wheel.m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint ); if ( denominator >= btScalar(-0.1)) { wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_clippedInvContactDotSuspension = btScalar(1.0) / btScalar(0.1); } else { btScalar inv = btScalar(-1.) / denominator; wheel.m_suspensionRelativeVelocity = projVel * inv; wheel.m_clippedInvContactDotSuspension = inv; } } else { //put wheel info as in rest position wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength(); wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS; wheel.m_clippedInvContactDotSuspension = btScalar(1.0); } return depth; } const btTransform& btRaycastVehicle::getChassisWorldTransform() const { /*if (getRigidBody()->getMotionState()) { btTransform chassisWorldTrans; getRigidBody()->getMotionState()->getWorldTransform(chassisWorldTrans); return chassisWorldTrans; } */ return getRigidBody()->getCenterOfMassTransform(); } void btRaycastVehicle::updateVehicle( btScalar step ) { { for (int i=0;i<getNumWheels();i++) { updateWheelTransform(i,false); } } m_currentVehicleSpeedKmHour = btScalar(3.6) * getRigidBody()->getLinearVelocity().length(); const btTransform& chassisTrans = getChassisWorldTransform(); btVector3 forwardW ( chassisTrans.getBasis()[0][m_indexForwardAxis], chassisTrans.getBasis()[1][m_indexForwardAxis], chassisTrans.getBasis()[2][m_indexForwardAxis]); if (forwardW.dot(getRigidBody()->getLinearVelocity()) < btScalar(0.)) { m_currentVehicleSpeedKmHour *= btScalar(-1.); } // // simulate suspension // int i=0; for (i=0;i<m_wheelInfo.size();i++) { //btScalar depth; //depth = rayCast( m_wheelInfo[i]); } updateSuspension(step); for (i=0;i<m_wheelInfo.size();i++) { //apply suspension force btWheelInfo& wheel = m_wheelInfo[i]; btScalar suspensionForce = wheel.m_wheelsSuspensionForce; if (suspensionForce > wheel.m_maxSuspensionForce) { suspensionForce = wheel.m_maxSuspensionForce; } btVector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step; btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS - getRigidBody()->getCenterOfMassPosition(); getRigidBody()->applyImpulse(impulse, relpos); } updateFriction( step); for (i=0;i<m_wheelInfo.size();i++) { btWheelInfo& wheel = m_wheelInfo[i]; btVector3 relpos = wheel.m_raycastInfo.m_hardPointWS - getRigidBody()->getCenterOfMassPosition(); btVector3 vel = getRigidBody()->getVelocityInLocalPoint( relpos ); if (wheel.m_raycastInfo.m_isInContact) { const btTransform& chassisWorldTransform = getChassisWorldTransform(); btVector3 fwd ( chassisWorldTransform.getBasis()[0][m_indexForwardAxis], chassisWorldTransform.getBasis()[1][m_indexForwardAxis], chassisWorldTransform.getBasis()[2][m_indexForwardAxis]); btScalar proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS); fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj; btScalar proj2 = fwd.dot(vel); wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelsRadius); wheel.m_rotation += wheel.m_deltaRotation; } else { wheel.m_rotation += wheel.m_deltaRotation; } wheel.m_deltaRotation *= btScalar(0.99);//damping of rotation when not in contact } } void btRaycastVehicle::setSteeringValue(btScalar steering,int wheel) { btAssert(wheel>=0 && wheel < getNumWheels()); btWheelInfo& wheelInfo = getWheelInfo(wheel); wheelInfo.m_steering = steering; } btScalar btRaycastVehicle::getSteeringValue(int wheel) const { return getWheelInfo(wheel).m_steering; } void btRaycastVehicle::applyEngineForce(btScalar force, int wheel) { btAssert(wheel>=0 && wheel < getNumWheels()); btWheelInfo& wheelInfo = getWheelInfo(wheel); wheelInfo.m_engineForce = force; } const btWheelInfo& btRaycastVehicle::getWheelInfo(int index) const { btAssert((index >= 0) && (index < getNumWheels())); return m_wheelInfo[index]; } btWheelInfo& btRaycastVehicle::getWheelInfo(int index) { btAssert((index >= 0) && (index < getNumWheels())); return m_wheelInfo[index]; } void btRaycastVehicle::setBrake(btScalar brake,int wheelIndex) { btAssert((wheelIndex >= 0) && (wheelIndex < getNumWheels())); getWheelInfo(wheelIndex).m_brake = brake; } void btRaycastVehicle::updateSuspension(btScalar deltaTime) { (void)deltaTime; btScalar chassisMass = btScalar(1.) / m_chassisBody->getInvMass(); for (int w_it=0; w_it<getNumWheels(); w_it++) { btWheelInfo &wheel_info = m_wheelInfo[w_it]; if ( wheel_info.m_raycastInfo.m_isInContact ) { btScalar force; // Spring { btScalar susp_length = wheel_info.getSuspensionRestLength(); btScalar current_length = wheel_info.m_raycastInfo.m_suspensionLength; btScalar length_diff = (susp_length - current_length); force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension; } // Damper { btScalar projected_rel_vel = wheel_info.m_suspensionRelativeVelocity; { btScalar susp_damping; if ( projected_rel_vel < btScalar(0.0) ) { susp_damping = wheel_info.m_wheelsDampingCompression; } else { susp_damping = wheel_info.m_wheelsDampingRelaxation; } force -= susp_damping * projected_rel_vel; } } // RESULT wheel_info.m_wheelsSuspensionForce = force * chassisMass; if (wheel_info.m_wheelsSuspensionForce < btScalar(0.)) { wheel_info.m_wheelsSuspensionForce = btScalar(0.); } } else { wheel_info.m_wheelsSuspensionForce = btScalar(0.0); } } } struct btWheelContactPoint { btRigidBody* m_body0; btRigidBody* m_body1; btVector3 m_frictionPositionWorld; btVector3 m_frictionDirectionWorld; btScalar m_jacDiagABInv; btScalar m_maxImpulse; btWheelContactPoint(btRigidBody* body0,btRigidBody* body1,const btVector3& frictionPosWorld,const btVector3& frictionDirectionWorld, btScalar maxImpulse) :m_body0(body0), m_body1(body1), m_frictionPositionWorld(frictionPosWorld), m_frictionDirectionWorld(frictionDirectionWorld), m_maxImpulse(maxImpulse) { btScalar denom0 = body0->computeImpulseDenominator(frictionPosWorld,frictionDirectionWorld); btScalar denom1 = body1->computeImpulseDenominator(frictionPosWorld,frictionDirectionWorld); btScalar relaxation = 1.f; m_jacDiagABInv = relaxation/(denom0+denom1); } }; btScalar calcRollingFriction(btWheelContactPoint& contactPoint); btScalar calcRollingFriction(btWheelContactPoint& contactPoint) { btScalar j1=0.f; const btVector3& contactPosWorld = contactPoint.m_frictionPositionWorld; btVector3 rel_pos1 = contactPosWorld - contactPoint.m_body0->getCenterOfMassPosition(); btVector3 rel_pos2 = contactPosWorld - contactPoint.m_body1->getCenterOfMassPosition(); btScalar maxImpulse = contactPoint.m_maxImpulse; btVector3 vel1 = contactPoint.m_body0->getVelocityInLocalPoint(rel_pos1); btVector3 vel2 = contactPoint.m_body1->getVelocityInLocalPoint(rel_pos2); btVector3 vel = vel1 - vel2; btScalar vrel = contactPoint.m_frictionDirectionWorld.dot(vel); // calculate j that moves us to zero relative velocity j1 = -vrel * contactPoint.m_jacDiagABInv; btSetMin(j1, maxImpulse); btSetMax(j1, -maxImpulse); return j1; } btScalar sideFrictionStiffness2 = btScalar(1.0); void btRaycastVehicle::updateFriction(btScalar timeStep) { //calculate the impulse, so that the wheels don't move sidewards int numWheel = getNumWheels(); if (!numWheel) return; m_forwardWS.resize(numWheel); m_axle.resize(numWheel); m_forwardImpulse.resize(numWheel); m_sideImpulse.resize(numWheel); int numWheelsOnGround = 0; //collapse all those loops into one! for (int i=0;i<getNumWheels();i++) { btWheelInfo& wheelInfo = m_wheelInfo[i]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; if (groundObject) numWheelsOnGround++; m_sideImpulse[i] = btScalar(0.); m_forwardImpulse[i] = btScalar(0.); } { for (int i=0;i<getNumWheels();i++) { btWheelInfo& wheelInfo = m_wheelInfo[i]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; if (groundObject) { const btTransform& wheelTrans = getWheelTransformWS( i ); btMatrix3x3 wheelBasis0 = wheelTrans.getBasis(); m_axle[i] = btVector3( wheelBasis0[0][m_indexRightAxis], wheelBasis0[1][m_indexRightAxis], wheelBasis0[2][m_indexRightAxis]); const btVector3& surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS; btScalar proj = m_axle[i].dot(surfNormalWS); m_axle[i] -= surfNormalWS * proj; m_axle[i] = m_axle[i].normalize(); m_forwardWS[i] = surfNormalWS.cross(m_axle[i]); m_forwardWS[i].normalize(); resolveSingleBilateral(*m_chassisBody, wheelInfo.m_raycastInfo.m_contactPointWS, *groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, btScalar(0.), m_axle[i],m_sideImpulse[i],timeStep); m_sideImpulse[i] *= sideFrictionStiffness2; } } } btScalar sideFactor = btScalar(1.); btScalar fwdFactor = 0.5; bool sliding = false; { for (int wheel =0;wheel <getNumWheels();wheel++) { btWheelInfo& wheelInfo = m_wheelInfo[wheel]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; btScalar rollingFriction = 0.f; if (groundObject) { if (wheelInfo.m_engineForce != 0.f) { rollingFriction = wheelInfo.m_engineForce* timeStep; } else { btScalar defaultRollingFrictionImpulse = 0.f; btScalar maxImpulse = wheelInfo.m_brake ? wheelInfo.m_brake : defaultRollingFrictionImpulse; btWheelContactPoint contactPt(m_chassisBody,groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,m_forwardWS[wheel],maxImpulse); rollingFriction = calcRollingFriction(contactPt); } } //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break) m_forwardImpulse[wheel] = btScalar(0.); m_wheelInfo[wheel].m_skidInfo= btScalar(1.); if (groundObject) { m_wheelInfo[wheel].m_skidInfo= btScalar(1.); btScalar maximp = wheelInfo.m_wheelsSuspensionForce * timeStep * wheelInfo.m_frictionSlip; btScalar maximpSide = maximp; btScalar maximpSquared = maximp * maximpSide; m_forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep; btScalar x = (m_forwardImpulse[wheel] ) * fwdFactor; btScalar y = (m_sideImpulse[wheel] ) * sideFactor; btScalar impulseSquared = (x*x + y*y); if (impulseSquared > maximpSquared) { sliding = true; btScalar factor = maximp / btSqrt(impulseSquared); m_wheelInfo[wheel].m_skidInfo *= factor; } } } } if (sliding) { for (int wheel = 0;wheel < getNumWheels(); wheel++) { if (m_sideImpulse[wheel] != btScalar(0.)) { if (m_wheelInfo[wheel].m_skidInfo< btScalar(1.)) { m_forwardImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; m_sideImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; } } } } // apply the impulses { for (int wheel = 0;wheel<getNumWheels() ; wheel++) { btWheelInfo& wheelInfo = m_wheelInfo[wheel]; btVector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS - m_chassisBody->getCenterOfMassPosition(); if (m_forwardImpulse[wheel] != btScalar(0.)) { m_chassisBody->applyImpulse(m_forwardWS[wheel]*(m_forwardImpulse[wheel]),rel_pos); } if (m_sideImpulse[wheel] != btScalar(0.)) { class btRigidBody* groundObject = (class btRigidBody*) m_wheelInfo[wheel].m_raycastInfo.m_groundObject; btVector3 rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->getCenterOfMassPosition(); btVector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel]; #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT. btVector3 vChassisWorldUp = getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis); rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f-wheelInfo.m_rollInfluence)); #else rel_pos[m_indexUpAxis] *= wheelInfo.m_rollInfluence; #endif m_chassisBody->applyImpulse(sideImp,rel_pos); //apply friction impulse on the ground groundObject->applyImpulse(-sideImp,rel_pos2); } } } } void btRaycastVehicle::debugDraw(btIDebugDraw* debugDrawer) { for (int v=0;v<this->getNumWheels();v++) { btVector3 wheelColor(0,1,1); if (getWheelInfo(v).m_raycastInfo.m_isInContact) { wheelColor.setValue(0,0,1); } else { wheelColor.setValue(1,0,1); } btVector3 wheelPosWS = getWheelInfo(v).m_worldTransform.getOrigin(); btVector3 axle = btVector3( getWheelInfo(v).m_worldTransform.getBasis()[0][getRightAxis()], getWheelInfo(v).m_worldTransform.getBasis()[1][getRightAxis()], getWheelInfo(v).m_worldTransform.getBasis()[2][getRightAxis()]); //debug wheels (cylinders) debugDrawer->drawLine(wheelPosWS,wheelPosWS+axle,wheelColor); debugDrawer->drawLine(wheelPosWS,getWheelInfo(v).m_raycastInfo.m_contactPointWS,wheelColor); } } void* btDefaultVehicleRaycaster::castRay(const btVector3& from,const btVector3& to, btVehicleRaycasterResult& result) { // RayResultCallback& resultCallback; btCollisionWorld::ClosestRayResultCallback rayCallback(from,to); m_dynamicsWorld->rayTest(from, to, rayCallback); if (rayCallback.hasHit()) { const btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); if (body && body->hasContactResponse()) { result.m_hitPointInWorld = rayCallback.m_hitPointWorld; result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld; result.m_hitNormalInWorld.normalize(); result.m_distFraction = rayCallback.m_closestHitFraction; return (void*)body; } } return 0; }
412
0.85333
1
0.85333
game-dev
MEDIA
0.911273
game-dev
0.979591
1
0.979591
magefree/mage
1,591
Mage.Sets/src/mage/cards/s/ShrillHowler.java
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.TransformSourceEffect; import mage.abilities.effects.common.combat.CantBeBlockedByCreaturesWithLessPowerEffect; import mage.abilities.keyword.TransformAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; /** * @author LevelX2 */ public final class ShrillHowler extends CardImpl { public ShrillHowler(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{G}"); this.subtype.add(SubType.WEREWOLF); this.subtype.add(SubType.HORROR); this.power = new MageInt(3); this.toughness = new MageInt(1); this.secondSideCardClazz = mage.cards.h.HowlingChorus.class; // Creatures with power less than Shrill Howler's power can't block it. this.addAbility(new SimpleStaticAbility(new CantBeBlockedByCreaturesWithLessPowerEffect())); // {5}{G}: Transform Shrill Howler. this.addAbility(new TransformAbility()); this.addAbility(new SimpleActivatedAbility(new TransformSourceEffect(), new ManaCostsImpl<>("{5}{G}"))); } private ShrillHowler(final ShrillHowler card) { super(card); } @Override public ShrillHowler copy() { return new ShrillHowler(this); } }
412
0.910277
1
0.910277
game-dev
MEDIA
0.982839
game-dev
0.98431
1
0.98431
dz333n/Singularity-OS
3,208
base/Libraries/Singularity.V1/Threads/SyncHandle.cs
//////////////////////////////////////////////////////////////////////////////// // // Microsoft Research Singularity - Singularity ABI // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: SyncHandle.cs // // Note: // using System; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.Singularity.V1.Threads { public struct SyncHandle // : public WaitHandle { public readonly UIntPtr id; // could be moved to WaitHandle [Inline] [NoHeapAllocation] private SyncHandle(UIntPtr id) { this.id = id; } [Inline] [NoHeapAllocation] public static implicit operator SyncHandle(MutexHandle handle) { return new SyncHandle(handle.id); } [Inline] [NoHeapAllocation] public static implicit operator SyncHandle(AutoResetEventHandle handle) { return new SyncHandle(handle.id); } [Inline] [NoHeapAllocation] public static implicit operator SyncHandle(ManualResetEventHandle handle) { return new SyncHandle(handle.id); } ////////////////////////////////////////////////////////////////////// // // The following methods could be moved to WaitHandle if we had // struct inheritance. // [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool WaitOne(SyncHandle handle); [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool WaitOne(SyncHandle handle, TimeSpan timeout); [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool WaitOne(SyncHandle handle, SchedulerTime stop); [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool WaitOneNoGC(SyncHandle handle); [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern unsafe int WaitAny(SyncHandle * handles, int handleCount); [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern unsafe int WaitAny(SyncHandle * handles, int handleCount, TimeSpan timeout); [OutsideGCDomain] [NoHeapAllocation] [StackBound(1152)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern unsafe int WaitAny(SyncHandle * handles, int handleCount, SchedulerTime stop); } }
412
0.719485
1
0.719485
game-dev
MEDIA
0.315753
game-dev
0.58617
1
0.58617
riksweeney/edgar
8,498
src/enemy/dragon_fly.c
/* Copyright (C) 2009-2024 Parallel Realities This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. */ #include "../headers.h" #include "../audio/audio.h" #include "../collisions.h" #include "../custom_actions.h" #include "../entity.h" #include "../graphics/animation.h" #include "../map.h" #include "../projectile.h" #include "../system/error.h" #include "../system/properties.h" #include "../system/random.h" extern Entity *self; static void die(void); static void init(void); static void flyAround(void); static void dropWait(void); static void walkAround(void); static void flyStart(void); static int safeToDrop(void); static void podWait(void); static void dropPod(void); static void podTakeDamage(Entity *, int); static void podExplode(void); static void creditsMove(void); Entity *addDragonFly(int x, int y, char *name) { Entity *e = getFreeEntity(); if (e == NULL) { showErrorAndExit("No free slots to add a Dragon Fly"); } loadProperties(name, e); e->x = x; e->y = y; e->action = &init; e->draw = &drawLoopingAnimationToMap; e->touch = &entityTouch; e->die = &die; e->takeDamage = &entityTakeDamageNoFlinch; e->reactToBlock = &changeDirection; e->creditsAction = &creditsMove; e->type = ENEMY; setEntityAnimation(e, "STAND"); return e; } static void init() { switch (self->mental) { case 1: setEntityAnimation(self, "WALK"); self->action = &walkAround; break; case 2: self->action = &dropWait; break; case 3: self->action = &flyStart; break; default: self->action = &flyAround; break; } } static void flyAround() { if (self->dirX == 0) { self->x += self->face == LEFT ? self->box.x : -self->box.x; self->dirX = (self->face == RIGHT ? -self->speed : self->speed); self->face = (self->face == RIGHT ? LEFT : RIGHT); } self->startX += 5; self->dirY = cos(DEG_TO_RAD(self->startX)); checkToMap(self); self->thinkTime--; if (self->thinkTime <= 0) { if (safeToDrop() == TRUE) { self->dirX = 0; self->thinkTime = 30; self->action = &dropWait; self->mental = 2; self->endX = 0; } else { self->thinkTime = self->maxThinkTime; } } if (prand() % 600 == 0) { dropPod(); } } static void dropWait() { self->thinkTime--; if (self->thinkTime <= 0) { self->dirY = 3; } checkToMap(self); if ((self->flags & ON_GROUND) || self->standingOn != NULL) { self->flags &= ~FLY; self->action = &walkAround; self->creditsAction = &creditsMove; self->thinkTime = 600; self->dirX = self->face == LEFT ? -self->speed : self->speed; setEntityAnimation(self, "WALK"); self->mental = 1; } } static void walkAround() { int face = self->face; self->thinkTime--; if (self->thinkTime <= 0) { self->dirX = 0; self->thinkTime = 30; self->dirY = -3; self->action = &flyStart; self->flags |= FLY; setEntityAnimation(self, "STAND"); self->mental = 3; playSoundToMap("sound/enemy/bug/buzz", -1, self->x, self->y, 0); } else { moveLeftToRight(); if (self->face != face) { self->endX++; if (self->endX >= 15) { self->thinkTime = 0; } } } } static void flyStart() { checkToMap(self); if (self->dirY == 0 || self->y < self->startY) { self->flags &= ~FLY; self->action = &flyAround; self->creditsAction = &creditsMove; self->dirX = self->face == LEFT ? -self->speed : self->speed; self->thinkTime = 600; self->mental = 0; } else { self->dirY = -3; } } static int safeToDrop() { int x, y, i, tile; x = self->x + self->w / 2; y = self->y + self->h - 1; x /= TILE_SIZE; y /= TILE_SIZE; y++; for (i=0;i<30;i++) { tile = mapTileAt(x, y); if (tile != BLANK_TILE && (tile < BACKGROUND_TILE_START || tile > FOREGROUND_TILE_START)) { return tile < BACKGROUND_TILE_START ? TRUE : FALSE; } y++; } return FALSE; } static void dropPod() { Entity *e = getFreeEntity(); if (e == NULL) { showErrorAndExit("No free slots to add a Dragon Fly Pod"); } loadProperties("enemy/dragon_fly_pod", e); setEntityAnimation(e, "STAND"); e->x = self->x + self->w / 2 - e->w / 2; e->y = self->y + self->h / 2 - e->h / 2; e->action = &podWait; e->draw = &drawLoopingAnimationToMap; e->touch = &entityTouch; e->fallout = &entityDieNoDrop; e->die = &entityDieNoDrop; e->pain = &enemyPain; e->takeDamage = &podTakeDamage; e->head = self; e->type = ENEMY; } static void podWait() { if (self->flags & ON_GROUND) { self->thinkTime--; if (self->thinkTime < 120) { if (self->thinkTime % 3 == 0) { self->flags ^= FLASH; } } if (self->thinkTime <= 0) { self->flags &= ~FLASH; self->action = &podExplode; self->flags |= FLY; self->dirY = -4; self->thinkTime = 5; } } checkToMap(self); } static void podExplode() { int x, y; Entity *e; self->thinkTime--; if (self->thinkTime <= 0) { e = addProjectile("common/green_blob", self->head, 0, 0, -6, 0); x = self->x + self->w / 2 - e->w / 2; y = self->y; e->x = x; e->y = y; e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, -6, -6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, 0, -6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, 6, -6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, -6, 6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, 0, 6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, 6, 6); e->flags |= FLY; e->reactToBlock = &bounceOffShield; e = addProjectile("common/green_blob", self->head, x, y, 6, 0); e->flags |= FLY; e->reactToBlock = &bounceOffShield; playSoundToMap("sound/common/pop", -1, self->x, self->y, 0); self->inUse = FALSE; } checkToMap(self); } static void podTakeDamage(Entity *other, int damage) { Entity *temp; if (self->flags & INVULNERABLE) { return; } if (damage != 0) { self->health -= damage; if (other->type == PROJECTILE) { temp = self; self = other; self->die(); self = temp; } if (self->health > 0) { setCustomAction(self, &flashWhite, 6, 0, 0); /* Don't make an enemy invulnerable from a projectile hit, allows multiple hits */ if (other->type != PROJECTILE) { setCustomAction(self, &invulnerableNoFlash, HIT_INVULNERABLE_TIME, 0, 0); } if (self->pain != NULL) { self->pain(); } } else { self->damage = 0; self->die(); } } } static void creditsMove() { self->thinkTime++; if (self->mental == 1) { self->flags &= ~FLY; setEntityAnimation(self, "WALK"); } else { self->dirY = 0; self->flags |= FLY; setEntityAnimation(self, "STAND"); } setEntityAnimation(self, self->mental == 1 ? "WALK" : "STAND"); self->dirX = self->speed; if (self->flags & FLY) { self->startX += 5; self->dirY = cos(DEG_TO_RAD(self->startX)); } checkToMap(self); if (self->dirX == 0) { self->inUse = FALSE; } if (self->thinkTime != 0 && (self->thinkTime % 240) == 0) { if (self->flags & FLY) { self->dirX = 0; self->thinkTime = 30; self->creditsAction = &dropWait; self->mental = 2; self->endX = 0; } else { self->dirX = 0; self->thinkTime = 30; self->dirY = -3; self->creditsAction = &flyStart; self->flags |= FLY; setEntityAnimation(self, "STAND"); self->mental = 3; playSoundToMap("sound/enemy/bug/buzz", -1, self->x, self->y, 0); } } } static void die() { playSoundToMap("sound/enemy/wasp/wasp_die", -1, self->x, self->y, 0); entityDie(); }
412
0.818059
1
0.818059
game-dev
MEDIA
0.915929
game-dev
0.99288
1
0.99288
PipeRift/SaveExtension
20,130
Source/SaveExtension/Public/SaveManager.h
// Copyright 2015-2020 Piperift. All Rights Reserved. #pragma once #include "Delegates.h" #include "LatentActions/DeleteSlotsAction.h" #include "LatentActions/LoadGameAction.h" #include "LatentActions/SaveGameAction.h" #include "LevelStreamingNotifier.h" #include "Multithreading/ScopedTaskManager.h" #include "Multithreading/Delegates.h" #include "SaveExtensionInterface.h" #include "SavePreset.h" #include "Serialization/SlotDataTask.h" #include "SlotData.h" #include "SlotInfo.h" #include <Async/AsyncWork.h> #include <CoreMinimal.h> #include <Engine/GameInstance.h> #include <GenericPlatform/GenericPlatformFile.h> #include <HAL/PlatformFilemanager.h> #include <Subsystems/GameInstanceSubsystem.h> #include <Tickable.h> #include "SaveManager.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnGameSavedMC, USlotInfo*, SlotInfo); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnGameLoadedMC, USlotInfo*, SlotInfo); struct FLatentActionInfo; USTRUCT(BlueprintType) struct FScreenshotSize { GENERATED_BODY() public: FScreenshotSize() : Width(640), Height(360) {} FScreenshotSize(int32 InWidth, int32 InHeight) : Width(InWidth), Height(InHeight) {} UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Screenshot) int32 Width; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Screenshot) int32 Height; }; /** * Controls the complete saving and loading process */ UCLASS(ClassGroup = SaveExtension, meta = (DisplayName = "SaveManager")) class SAVEEXTENSION_API USaveManager : public UGameInstanceSubsystem, public FTickableGameObject { GENERATED_BODY() friend USlotDataTask; /************************************************************************/ /* PROPERTIES */ /************************************************************************/ public: // Loaded from settings. Can be changed at runtime UPROPERTY(Transient, BlueprintReadWrite, Category=SaveManager) bool bTickWithGameWorld = false; private: UPROPERTY(Transient) USavePreset* ActivePreset; /** Currently loaded SaveInfo. SaveInfo stores basic information about a saved game. Played time, levels, * progress, etc. */ UPROPERTY() USlotInfo* CurrentInfo; /** Currently loaded SaveData. SaveData stores all serialized info about the world. */ UPROPERTY() USlotData* CurrentData; /** The game instance to which this save manager is owned. */ TWeakObjectPtr<UGameInstance> OwningGameInstance; FScopedTaskList MTTasks; UPROPERTY(Transient) TArray<ULevelStreamingNotifier*> LevelStreamingNotifiers; UPROPERTY(Transient) TArray<TScriptInterface<ISaveExtensionInterface>> SubscribedInterfaces; UPROPERTY(Transient) TArray<USlotDataTask*> Tasks; /************************************************************************/ /* METHODS */ /************************************************************************/ public: USaveManager(); /** Begin USubsystem */ virtual void Initialize(FSubsystemCollectionBase& Collection) override; virtual void Deinitialize() override; /** End USubsystem */ void SetGameInstance(UGameInstance* GameInstance) { OwningGameInstance = GameInstance; } /** C++ ONLY API */ /** Save the Game into an specified slot name */ bool SaveSlot(FName SlotName, bool bOverrideIfNeeded = true, bool bScreenshot = false, const FScreenshotSize Size = {}, FOnGameSaved OnSaved = {}); /** Save the Game info an SlotInfo */ bool SaveSlot(const USlotInfo* SlotInfo, bool bOverrideIfNeeded = true, bool bScreenshot = false, const FScreenshotSize Size = {}, FOnGameSaved OnSaved = {}); /** Save the Game into an specified slot id */ bool SaveSlot(int32 SlotId, bool bOverrideIfNeeded = true, bool bScreenshot = false, const FScreenshotSize Size = {}, FOnGameSaved OnSaved = {}); /** Save the currently loaded Slot */ bool SaveCurrentSlot(bool bScreenshot = false, const FScreenshotSize Size = {}, FOnGameSaved OnSaved = {}); /** Load game from a file name */ bool LoadSlot(FName SlotName, FOnGameLoaded OnLoaded = {}); /** Load game from a slot Id */ bool LoadSlot(int32 SlotId, FOnGameLoaded OnLoaded = {}); /** Load game from a SlotInfo */ bool LoadSlot(const USlotInfo* SlotInfo, FOnGameLoaded OnLoaded = {}); /** Reload the currently loaded slot if any */ bool ReloadCurrentSlot(FOnGameLoaded OnLoaded = {}) { return LoadSlot(CurrentInfo, MoveTemp(OnLoaded)); } /** * Find all saved games and return their SlotInfos * @param bSortByRecent Should slots be ordered by save date? * @param SaveInfos All saved games found on disk */ void LoadAllSlotInfos(bool bSortByRecent, FOnSlotInfosLoaded Delegate); void LoadAllSlotInfosSync(bool bSortByRecent, FOnSlotInfosLoaded Delegate); /** Delete a saved game on an specified slot name * Performance: Interacts with disk, can be slow */ bool DeleteSlot(FName SlotName); /** Delete all saved slots from disk, loaded or not */ void DeleteAllSlots(FOnSlotsDeleted Delegate); /** BLUEPRINT ONLY API */ public: // NOTE: This functions are mostly made to accommodate better Blueprint nodes that directly communicate // with the normal C++ API /** Save the Game into an specified Slot */ UFUNCTION(Category = "SaveExtension|Saving", BlueprintCallable, meta = (AdvancedDisplay = "bScreenshot, Size", DisplayName = "Save Slot", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPSaveSlot(FName SlotName, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo, bool bOverrideIfNeeded = true); /** Save the Game into an specified Slot */ UFUNCTION(Category = "SaveExtension|Saving", BlueprintCallable, meta = (AdvancedDisplay = "bScreenshot, Size", DisplayName = "Save Slot by Id", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPSaveSlotById(int32 SlotId, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo, bool bOverrideIfNeeded = true); /** Save the Game to a Slot */ UFUNCTION(Category = "SaveExtension|Saving", BlueprintCallable, meta = (AdvancedDisplay = "bScreenshot, Size", DisplayName = "Save Slot by Info", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPSaveSlotByInfo(const USlotInfo* SlotInfo, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo, bool bOverrideIfNeeded = true); /** Save the currently loaded Slot */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Saving", meta = (AdvancedDisplay = "bScreenshot, Size", DisplayName = "Save Current Slot", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPSaveCurrentSlot(bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo) { BPSaveSlotByInfo(CurrentInfo, bScreenshot, Size, Result, MoveTemp(LatentInfo), true); } /** Load game from a slot name */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Loading", meta = (DisplayName = "Load Slot", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPLoadSlot(FName SlotName, ELoadGameResult& Result, FLatentActionInfo LatentInfo); /** Load game from a slot Id */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Loading", meta = (DisplayName = "Load Slot by Id", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPLoadSlotById(int32 SlotId, ELoadGameResult& Result, FLatentActionInfo LatentInfo); /** Load game from a SlotInfo */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Loading", meta = (DisplayName = "Load Slot by Info", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPLoadSlotByInfo(const USlotInfo* SlotInfo, ELoadGameResult& Result, FLatentActionInfo LatentInfo); /** Reload the currently loaded slot if any */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Loading", meta = (DisplayName = "Reload Current Slot", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPReloadCurrentSlot(ELoadGameResult& Result, FLatentActionInfo LatentInfo) { BPLoadSlotByInfo(CurrentInfo, Result, MoveTemp(LatentInfo)); } /** * Find all saved games and return their SlotInfos * @param bSortByRecent Should slots be ordered by save date? * @param SaveInfos All saved games found on disk */ UFUNCTION(BlueprintCallable, Category = "SaveExtension", meta = (Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", DisplayName = "Load All Slot Infos")) void BPLoadAllSlotInfos(const bool bSortByRecent, TArray<USlotInfo*>& SaveInfos, ELoadInfoResult& Result, struct FLatentActionInfo LatentInfo); /** Delete a saved game on an specified slot Id * Performance: Interacts with disk, can be slow */ UFUNCTION(BlueprintCallable, Category = "SaveExtension") FORCEINLINE bool DeleteSlotById(int32 SlotId) { if (!IsValidSlot(SlotId)) { return false; } return DeleteSlot(GetSlotNameFromId(SlotId)); } /** Delete all saved slots from disk, loaded or not */ UFUNCTION(BlueprintCallable, Category = "SaveExtension", meta = (Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", DisplayName = "Delete All Slots")) void BPDeleteAllSlots(EDeleteSlotsResult& Result, FLatentActionInfo LatentInfo); UFUNCTION(BlueprintPure, Category = "SaveExtension") USavePreset* BPGetPreset() const { return ActivePreset; } /** BLUEPRINTS & C++ API */ public: /** Delete a saved game on an specified slot * Performance: Interacts with disk, can be slow */ UFUNCTION(BlueprintCallable, Category = "SaveExtension") bool DeleteSlot(USlotInfo* Slot) { return Slot? DeleteSlot(Slot->FileName) : false; } /** Get the currently loaded SlotInfo. If game was never loaded returns a new SlotInfo */ UFUNCTION(BlueprintPure, Category = "SaveExtension") FORCEINLINE USlotInfo* GetCurrentInfo() { TryInstantiateInfo(); return CurrentInfo; } /** Get the currently loaded SlotData. If game was never loaded returns an empty SlotData */ UFUNCTION(BlueprintPure, Category = "SaveExtension") FORCEINLINE USlotData* GetCurrentData() { TryInstantiateInfo(); return CurrentData; } /** * Load and return an SlotInfo by Id if it exists * Performance: Interacts with disk, could be slow if called frequently * @param SlotId Id of the SlotInfo to be loaded * @return the SlotInfo associated with an Id */ UFUNCTION(BlueprintCallable, Category = "SaveExtension|Slots") FORCEINLINE USlotInfo* GetSlotInfoById(int32 SlotId) { return LoadInfo(SlotId); } UFUNCTION(BlueprintCallable, Category = "SaveExtension|Slots") FORCEINLINE USlotInfo* GetSlotInfo(FName SlotName) { return LoadInfo(SlotName); } /** Check if an slot exists on disk * @return true if the slot exists */ UFUNCTION(BlueprintPure, Category = "SaveExtension|Slots") bool IsSlotSaved(FName SlotName) const; /** Check if an slot exists on disk * @return true if the slot exists */ UFUNCTION(BlueprintPure, Category = "SaveExtension|Slots") bool IsSlotSavedById(int32 SlotId) const { return IsValidSlot(SlotId)? IsSlotSaved(GetSlotNameFromId(SlotId)) : false; } /** Check if currently playing in a saved slot * @return true if currently playing in a saved slot */ UFUNCTION(BlueprintPure, Category = "SaveExtension|Slots") FORCEINLINE bool IsInSlot() const { return CurrentInfo && CurrentData; } /** * Set the preset to be used for saving and loading * @return true if the preset was set successfully */ UFUNCTION(BlueprintCallable, Category = "SaveExtension") USavePreset* SetActivePreset(TSubclassOf<USavePreset> PresetClass); const USavePreset* GetPreset() const; void TryInstantiateInfo(bool bForced = false); UFUNCTION(BlueprintPure, Category = "SaveExtension") FName GetSlotNameFromId(const int32 SlotId) const; bool IsValidSlot(const int32 Slot) const; void __SetCurrentInfo(USlotInfo* NewInfo) { CurrentInfo = NewInfo; } void __SetCurrentData(USlotData* NewData) { CurrentData = NewData; } USlotInfo* LoadInfo(FName SlotName); USlotInfo* LoadInfo(uint32 SlotId) { return IsValidSlot(SlotId)? LoadInfo(GetSlotNameFromId(SlotId)) : nullptr; } protected: bool CanLoadOrSave(); private: //~ Begin LevelStreaming void UpdateLevelStreamings(); UFUNCTION() void SerializeStreamingLevel(ULevelStreaming* LevelStreaming); UFUNCTION() void DeserializeStreamingLevel(ULevelStreaming* LevelStreaming); //~ End LevelStreaming void OnLevelLoaded(ULevelStreaming* StreamingLevel) {} USlotDataTask* CreateTask(TSubclassOf<USlotDataTask> TaskType); template <class TaskType> TaskType* CreateTask() { return Cast<TaskType>(CreateTask(TaskType::StaticClass())); } void FinishTask(USlotDataTask* Task); public: bool HasTasks() const { return Tasks.Num() > 0; } /** @return true when saving or loading anything, including levels */ UFUNCTION(BlueprintPure, Category = SaveExtension) bool IsSavingOrLoading() const { return HasTasks(); } bool IsLoading() const; protected: //~ Begin Tickable Object Interface virtual void Tick(float DeltaTime) override; virtual bool IsTickable() const override; virtual UWorld* GetTickableGameObjectWorld() const override; virtual TStatId GetStatId() const override; //~ End Tickable Object Interface //~ Begin UObject Interface virtual UWorld* GetWorld() const override; //~ End UObject Interface /***********************************************************************/ /* EVENTS */ /***********************************************************************/ public: UPROPERTY(BlueprintAssignable, Category = SaveExtension) FOnGameSavedMC OnGameSaved; UPROPERTY(BlueprintAssignable, Category = SaveExtension) FOnGameLoadedMC OnGameLoaded; /** Subscribe to receive save and load events on an Interface */ UFUNCTION(Category = SaveExtension, BlueprintCallable) void SubscribeForEvents(const TScriptInterface<ISaveExtensionInterface>& Interface); /** Unsubscribe to no longer receive save and load events on an Interface */ UFUNCTION(Category = SaveExtension, BlueprintCallable) void UnsubscribeFromEvents(const TScriptInterface<ISaveExtensionInterface>& Interface); void OnSaveBegan(const FSELevelFilter& Filter); void OnSaveFinished(const FSELevelFilter& Filter, const bool bError); void OnLoadBegan(const FSELevelFilter& Filter); void OnLoadFinished(const FSELevelFilter& Filter, const bool bError); private: void OnMapLoadStarted(const FString& MapName); void OnMapLoadFinished(UWorld* LoadedWorld); void IterateSubscribedInterfaces(TFunction<void(UObject*)>&& Callback); /***********************************************************************/ /* STATIC */ /***********************************************************************/ public: /** Get the global save manager */ static USaveManager* Get(const UObject* ContextObject); /***********************************************************************/ /* DEPRECATED */ /***********************************************************************/ UFUNCTION(Category = "SaveExtension|Saving", BlueprintCallable, meta = (DeprecatedFunction, DeprecationMessage="Use 'Save Slot by Id' instead.", AdvancedDisplay = "bScreenshot, Size", DisplayName = "Save Slot to Id", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPSaveSlotToId(int32 SlotId, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo, bool bOverrideIfNeeded = true) { BPSaveSlotById(SlotId, bScreenshot, Size, Result, LatentInfo, bOverrideIfNeeded); } UFUNCTION(BlueprintCallable, Category = "SaveExtension|Loading", meta = (DeprecatedFunction, DeprecationMessage="Use 'Load Slot by Id' instead.", DisplayName = "Load Slot from Id", Latent, LatentInfo = "LatentInfo", ExpandEnumAsExecs = "Result", UnsafeDuringActorConstruction)) void BPLoadSlotFromId(int32 SlotId, ELoadGameResult& Result, FLatentActionInfo LatentInfo) { BPLoadSlotById(SlotId, Result, LatentInfo); } }; inline bool USaveManager::SaveSlot(int32 SlotId, bool bOverrideIfNeeded, bool bScreenshot, const FScreenshotSize Size, FOnGameSaved OnSaved) { if (!IsValidSlot(SlotId)) { SELog(GetPreset(), "Invalid Slot. Cant go under 0 or exceed MaxSlots.", true); return false; } return SaveSlot(GetSlotNameFromId(SlotId), bOverrideIfNeeded, bScreenshot, Size, OnSaved); } inline bool USaveManager::SaveSlot(const USlotInfo* SlotInfo, bool bOverrideIfNeeded, bool bScreenshot, const FScreenshotSize Size, FOnGameSaved OnSaved) { if (!SlotInfo) { return false; } return SaveSlot(SlotInfo->FileName, bOverrideIfNeeded, bScreenshot, Size, OnSaved); } inline void USaveManager::BPSaveSlotById(int32 SlotId, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, FLatentActionInfo LatentInfo, bool bOverrideIfNeeded) { if (!IsValidSlot(SlotId)) { SELog(GetPreset(), "Invalid Slot. Cant go under 0 or exceed MaxSlots.", true); Result = ESaveGameResult::Failed; return; } BPSaveSlot(GetSlotNameFromId(SlotId), bScreenshot, Size, Result, MoveTemp(LatentInfo), bOverrideIfNeeded); } inline void USaveManager::BPSaveSlotByInfo(const USlotInfo* SlotInfo, bool bScreenshot, const FScreenshotSize Size, ESaveGameResult& Result, struct FLatentActionInfo LatentInfo, bool bOverrideIfNeeded) { if (!SlotInfo) { Result = ESaveGameResult::Failed; return; } BPSaveSlot(SlotInfo->FileName, bScreenshot, Size, Result, MoveTemp(LatentInfo), bOverrideIfNeeded); } /** Save the currently loaded Slot */ inline bool USaveManager::SaveCurrentSlot(bool bScreenshot, const FScreenshotSize Size, FOnGameSaved OnSaved) { return SaveSlot(CurrentInfo, true, bScreenshot, Size, OnSaved); } inline bool USaveManager::LoadSlot(int32 SlotId, FOnGameLoaded OnLoaded) { if (!IsValidSlot(SlotId)) { SELog(GetPreset(), "Invalid Slot. Can't go under 0 or exceed MaxSlots.", true); return false; } return LoadSlot(GetSlotNameFromId(SlotId), OnLoaded); } inline bool USaveManager::LoadSlot(const USlotInfo* SlotInfo, FOnGameLoaded OnLoaded) { if (!SlotInfo) { return false; } return LoadSlot(SlotInfo->FileName, OnLoaded); } inline void USaveManager::BPLoadSlotById( int32 SlotId, ELoadGameResult& Result, struct FLatentActionInfo LatentInfo) { BPLoadSlot(GetSlotNameFromId(SlotId), Result, MoveTemp(LatentInfo)); } inline void USaveManager::BPLoadSlotByInfo(const USlotInfo* SlotInfo, ELoadGameResult& Result, FLatentActionInfo LatentInfo) { if (!SlotInfo) { Result = ELoadGameResult::Failed; return; } BPLoadSlot(SlotInfo->FileName, Result, MoveTemp(LatentInfo)); } inline bool USaveManager::IsValidSlot(const int32 Slot) const { return GetPreset()->IsValidId(Slot); } inline void USaveManager::IterateSubscribedInterfaces(TFunction<void(UObject*)>&& Callback) { for (const TScriptInterface<ISaveExtensionInterface>& Interface : SubscribedInterfaces) { if (UObject* const Object = Interface.GetObject()) { Callback(Object); } } } inline USaveManager* USaveManager::Get(const UObject* Context) { UWorld* World = GEngine->GetWorldFromContextObject(Context, EGetWorldErrorMode::LogAndReturnNull); if (World) { return UGameInstance::GetSubsystem<USaveManager>(World->GetGameInstance()); } return nullptr; } inline bool USaveManager::IsTickable() const { return !HasAnyFlags(RF_ClassDefaultObject) && IsValid(this); } inline UWorld* USaveManager::GetTickableGameObjectWorld() const { return bTickWithGameWorld? GetWorld() : nullptr; } inline TStatId USaveManager::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(USaveManager, STATGROUP_Tickables); }
412
0.892955
1
0.892955
game-dev
MEDIA
0.892337
game-dev
0.828591
1
0.828591
seppukudevelopment/seppuku
3,650
src/main/java/me/rigamortis/seppuku/impl/module/misc/DiscordBypassModule.java
package me.rigamortis.seppuku.impl.module.misc; import me.rigamortis.seppuku.Seppuku; import me.rigamortis.seppuku.api.event.EventStageable; import me.rigamortis.seppuku.api.event.network.EventSendPacket; import me.rigamortis.seppuku.api.module.Module; import me.rigamortis.seppuku.impl.module.hidden.CommandsModule; import net.minecraft.client.Minecraft; import net.minecraft.network.play.client.CPacketChatMessage; import team.stiff.pomelo.impl.annotated.handler.annotation.Listener; /** * Author: Francesco * 18/10/2019 at 21:03. * Might contain literal spaghetti code. */ public class DiscordBypassModule extends Module { public DiscordBypassModule() { super("DiscordBypass", new String[]{"DiscBypass", "NoDiscord", "NoBan"}, "Bypasses jj's stupid plugin that temp-bans you when you say \"discord\" near spawn", "NONE", -1, ModuleType.MISC); } @Listener public void sendPacket(EventSendPacket event) { if (event.getStage() == EventStageable.EventStage.PRE) { if (event.getPacket() instanceof CPacketChatMessage) { final CPacketChatMessage packet = (CPacketChatMessage) event.getPacket(); final CommandsModule commands = (CommandsModule) Seppuku.INSTANCE.getModuleManager().find(CommandsModule.class); if (commands != null) { if (packet.getMessage().startsWith(commands.prefix.getValue()) || packet.getMessage().startsWith("/")) return; //Technically the "spawn area" is usually around 23x23 chunks, but jj might've changed it... or perhaps he might not be using the spawn chunks at all. //Just in case he's going to the "anarchy definition" of spawn, I set it to 1k. Better safe than sorry, nobody except jj will notice the extra #. if (Minecraft.getMinecraft().player.posX <= 1000 || Minecraft.getMinecraft().player.posZ <= 1000) { //This might seem like a stupid way to do it, but it's the best one I know to get this done without making the whole message lowercase. //If you want the straightforward method, you can use the part that is commented out down here. /* if (packet.message.toLowerCase().contains("discord")) packet.message = packet.message.toLowerCase().replace("discord", "disc#ord"); */ if (packet.message.toLowerCase().contains("discord")) { for (int i = 0; i < packet.message.length(); i++) { if (packet.message.toLowerCase().charAt(i) == 'd') { if (packet.message.toLowerCase().toLowerCase().charAt(i + 1) == 'i' && packet.message.toLowerCase().toLowerCase().charAt(i + 2) == 's' && packet.message.toLowerCase().toLowerCase().charAt(i + 3) == 'c' && packet.message.toLowerCase().toLowerCase().charAt(i + 4) == '0' && packet.message.toLowerCase().toLowerCase().charAt(i + 5) == 'r' && packet.message.toLowerCase().toLowerCase().charAt(i + 6) == 'd') packet.message = new StringBuilder(packet.message).insert(i + 3, "#").toString(); } } } } } } } } }
412
0.855596
1
0.855596
game-dev
MEDIA
0.83928
game-dev,networking
0.865059
1
0.865059
away3d/awayphysics-core-fp11
2,432
Bullet/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ EPA Copyright (c) Ricardo Padrela 2006 This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "btGjkEpaPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" bool btGjkEpaPenetrationDepthSolver::calcPenDepth( btSimplexSolverInterface& simplexSolver, const btConvexShape* pConvexA, const btConvexShape* pConvexB, const btTransform& transformA, const btTransform& transformB, btVector3& v, btVector3& wWitnessOnA, btVector3& wWitnessOnB, class btIDebugDraw* debugDraw, btStackAlloc* stackAlloc ) { (void)debugDraw; (void)v; (void)simplexSolver; // const btScalar radialmargin(btScalar(0.)); btVector3 guessVector(transformA.getOrigin()-transformB.getOrigin()); btGjkEpaSolver2::sResults results; if(btGjkEpaSolver2::Penetration(pConvexA,transformA, pConvexB,transformB, guessVector,results)) { // debugDraw->drawLine(results.witnesses[1],results.witnesses[1]+results.normal,btVector3(255,0,0)); //resultOut->addContactPoint(results.normal,results.witnesses[1],-results.depth); wWitnessOnA = results.witnesses[0]; wWitnessOnB = results.witnesses[1]; v = results.normal; return true; } else { if(btGjkEpaSolver2::Distance(pConvexA,transformA,pConvexB,transformB,guessVector,results)) { wWitnessOnA = results.witnesses[0]; wWitnessOnB = results.witnesses[1]; v = results.normal; return false; } } return false; }
412
0.826311
1
0.826311
game-dev
MEDIA
0.992762
game-dev
0.560015
1
0.560015
Return-To-The-Roots/s25client
14,514
libs/s25main/world/World.cpp
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org) // // SPDX-License-Identifier: GPL-2.0-or-later #include "world/World.h" #include "nodeObjs/noFlag.h" #include "nodeObjs/noNothing.h" #if RTTR_ENABLE_ASSERTS # include "nodeObjs/noMovable.h" #endif #include "FOWObjects.h" #include "RoadSegment.h" #include "enum_cast.hpp" #include "helpers/containerUtils.h" #include "helpers/pointerContainerUtils.h" #include "gameTypes/ShipDirection.h" #include "gameData/TerrainDesc.h" #include <memory> #include <set> #include <stdexcept> World::World() : noNodeObj(nullptr) {} World::~World() { Unload(); } void World::Init(const MapExtent& mapSize, DescIdx<LandscapeDesc> lt) { RTTR_Assert(GetSize() == MapExtent::all(0)); // Already init RTTR_Assert(mapSize.x > 0 && mapSize.y > 0); // No empty map Resize(mapSize); if(!lt) throw std::runtime_error("Invalid landscape"); this->lt = lt; GameObject::ResetCounters(); // Dummy so that the harbor "0" might be used for ships with no particular destination harbor_pos.push_back(HarborPos(MapPoint::Invalid())); noNodeObj = std::make_unique<noNothing>(); } void World::Unload() { // Collect and destroy roads std::set<RoadSegment*> roadsegments; for(const auto& node : nodes) { if(!node.obj || node.obj->GetGOT() != GO_Type::Flag) continue; for(const auto dir : helpers::EnumRange<Direction>{}) { if(static_cast<noFlag*>(node.obj)->GetRoute(dir)) { roadsegments.insert(static_cast<noFlag*>(node.obj)->GetRoute(dir)); } } } for(auto* roadsegment : roadsegments) delete roadsegment; // Objekte vernichten for(auto& node : nodes) deletePtr(node.obj); // Figuren vernichten for(auto& node : nodes) node.figures.clear(); catapult_stones.clear(); harbor_pos.clear(); description_ = WorldDescription(); noNodeObj.reset(); Resize(MapExtent::all(0)); } void World::Resize(const MapExtent& newSize) { MapBase::Resize(newSize); nodes.clear(); militarySquares.Clear(); if(GetSize().x > 0) { nodes.resize(prodOfComponents(GetSize())); militarySquares.Init(GetSize()); } } noBase& World::AddFigureImpl(const MapPoint pt, std::unique_ptr<noBase> fig) { RTTR_Assert(fig); auto& figures = GetNodeInt(pt).figures; #if RTTR_ENABLE_ASSERTS RTTR_Assert(!helpers::containsPtr(figures, fig.get())); for(const MapPoint nb : GetNeighbours(pt)) RTTR_Assert(!helpers::containsPtr(GetNode(nb).figures, fig.get())); // Added figure that is in surrounding? #endif noBase& result = *fig; figures.push_back(std::move(fig)); return result; } noBase* World::RemoveFigureImpl(const MapPoint pt, noBase& fig) { return helpers::extractPtr(GetNodeInt(pt).figures, &fig).release(); } noBase* World::GetNO(const MapPoint pt) { if(GetNode(pt).obj) return GetNode(pt).obj; else return noNodeObj.get(); } const noBase* World::GetNO(const MapPoint pt) const { if(GetNode(pt).obj) return GetNode(pt).obj; else return noNodeObj.get(); } void World::SetNO(const MapPoint pt, noBase* obj, const bool replace /* = false*/) { RTTR_Assert(replace || obj == nullptr || GetNode(pt).obj == nullptr); #if RTTR_ENABLE_ASSERTS RTTR_Assert(!dynamic_cast<noMovable*>(obj)); // It should be a static, non-movable object #endif GetNodeInt(pt).obj = obj; } void World::DestroyNO(const MapPoint pt, const bool checkExists /* = true*/) { noBase* obj = GetNodeInt(pt).obj; if(obj) { // Destroy may remove the NO already from the map or replace it (e.g. building -> fire) // So remove from map, then destroy and free GetNodeInt(pt).obj = nullptr; obj->Destroy(); deletePtr(obj); } else RTTR_Assert(!checkExists); } /// Returns the GOT if an object or GOT_NOTHING if none GO_Type World::GetGOT(const MapPoint pt) const { noBase* obj = GetNode(pt).obj; if(obj) return obj->GetGOT(); else return GO_Type::Nothing; } void World::ReduceResource(const MapPoint pt) { const uint8_t curAmount = GetNodeInt(pt).resources.getAmount(); RTTR_Assert(curAmount > 0); GetNodeInt(pt).resources.setAmount(curAmount - 1u); } void World::SetReserved(const MapPoint pt, const bool reserved) { RTTR_Assert(GetNodeInt(pt).reserved != reserved); GetNodeInt(pt).reserved = reserved; } void World::SetVisibility(const MapPoint pt, unsigned char player, Visibility vis, unsigned fowTime) { FoWNode& node = GetNodeInt(pt).fow[player]; Visibility oldVis = node.visibility; if(oldVis == vis) return; node.visibility = vis; if(vis == Visibility::Visible) node.object.reset(); else if(vis == Visibility::FogOfWar) SaveFOWNode(pt, player, fowTime); VisibilityChanged(pt, player, oldVis, vis); } void World::ChangeAltitude(const MapPoint pt, const unsigned char altitude) { GetNodeInt(pt).altitude = altitude; // Schattierung neu berechnen von diesem Punkt und den Punkten drumherum RecalcShadow(pt); for(const MapPoint nb : GetNeighbours(pt)) RecalcShadow(nb); // Abgeleiteter Klasse Bescheid sagen AltitudeChanged(pt); } bool World::IsPlayerTerritory(const MapPoint pt, const unsigned char owner) const { const unsigned char ptOwner = GetNode(pt).owner; if(owner != 0 && ptOwner != owner) return false; // Neighbour nodes must belong to this player for(const MapPoint nb : GetNeighbours(pt)) { if(GetNode(nb).owner != ptOwner) return false; } return true; } BuildingQuality World::GetBQ(const MapPoint pt, const unsigned char player) const { return AdjustBQ(pt, player, GetNode(pt).bq); } BuildingQuality World::AdjustBQ(const MapPoint pt, unsigned char player, BuildingQuality nodeBQ) const { if(nodeBQ == BuildingQuality::Nothing || !IsPlayerTerritory(pt, player + 1)) return BuildingQuality::Nothing; // If we could build a building, but the buildings flag point is at the border, we can only build a flag if(nodeBQ != BuildingQuality::Flag && !IsPlayerTerritory(GetNeighbour(pt, Direction::SouthEast))) { // Check for close flags, that prohibit to build a flag but not a building at this spot for(const Direction dir : {Direction::West, Direction::NorthWest, Direction::NorthEast}) { if(GetNO(GetNeighbour(pt, dir))->GetBM() == BlockingManner::Flag) return BuildingQuality::Nothing; } return BuildingQuality::Flag; } else return nodeBQ; } bool World::HasFigureAt(const MapPoint pt, const noBase& figure) const { return helpers::containsPtr(GetNode(pt).figures, &figure); } WalkTerrain World::GetTerrain(MapPoint pt, Direction dir) const { // Manually inlined code from GetNeighbors. Measured to greatly improve performance const MapExtent size = GetSize(); const MapCoord yminus1 = (pt.y == 0 ? size.y : pt.y) - 1; const MapCoord xplus1 = pt.x == size.x - 1 ? 0 : pt.x + 1; const MapCoord xminus1 = (pt.x == 0 ? size.x : pt.x) - 1; const bool isEvenRow = (pt.y & 1) == 0; const MapPoint wPt(xminus1, pt.y); const MapPoint nwPt(!isEvenRow ? pt.x : xminus1, yminus1); const MapPoint nePt(isEvenRow ? pt.x : xplus1, yminus1); switch(dir) { case Direction::West: { return {GetNode(wPt).t2, GetNode(nwPt).t1}; } case Direction::NorthWest: { const MapNode& node = GetNode(nwPt); return {node.t1, node.t2}; } case Direction::NorthEast: { return {GetNode(nwPt).t2, GetNode(nePt).t1}; } case Direction::East: { return {GetNode(nePt).t1, GetNode(pt).t2}; } case Direction::SouthEast: { const MapNode& node = GetNode(pt); return {node.t2, node.t1}; } case Direction::SouthWest: { return {GetNode(pt).t1, GetNode(wPt).t2}; } } throw std::logic_error("Invalid direction"); } helpers::EnumArray<DescIdx<TerrainDesc>, Direction> World::GetTerrainsAround(MapPoint pt) const { // Manually inlined code from GetNeighbors. Measured to greatly improve performance const MapExtent size = GetSize(); const MapCoord yminus1 = (pt.y == 0 ? size.y : pt.y) - 1; const MapCoord xplus1 = pt.x == size.x - 1 ? 0 : pt.x + 1; const MapCoord xminus1 = (pt.x == 0 ? size.x : pt.x) - 1; const bool isEvenRow = (pt.y & 1) == 0; const MapPoint wPt(xminus1, pt.y); const MapPoint nwPt(!isEvenRow ? pt.x : xminus1, yminus1); const MapPoint nePt(isEvenRow ? pt.x : xplus1, yminus1); const MapNode& nwNode = GetNode(nwPt); const MapNode& neNode = GetNode(nePt); const MapNode& curNode = GetNode(pt); const MapNode& wNode = GetNode(wPt); helpers::EnumArray<DescIdx<TerrainDesc>, Direction> result{nwNode.t1, nwNode.t2, neNode.t1, curNode.t2, curNode.t1, wNode.t2}; return result; } void World::SaveFOWNode(const MapPoint pt, const unsigned player, unsigned curTime) { FoWNode& fow = GetNodeInt(pt).fow[player]; fow.last_update_time = curTime; // FOW-Objekt erzeugen fow.object = GetNO(pt)->CreateFOWObject(); // Wege speichern, aber nur richtige, keine, die gerade gebaut werden for(const auto dir : helpers::EnumRange<RoadDir>{}) fow.roads[dir] = GetNode(pt).roads[dir]; // Store ownership so FoW boundary stones can be drawn fow.owner = GetNode(pt).owner; // Grenzsteine merken fow.boundary_stones = GetNode(pt).boundary_stones; } bool World::IsSeaPoint(const MapPoint pt) const { return World::IsOfTerrain(pt, [](const auto& desc) { return desc.Is(ETerrain::Shippable); }); } bool World::IsWaterPoint(const MapPoint pt) const { return World::IsOfTerrain(pt, [](const auto& desc) { return desc.kind == TerrainKind::Water; }); } unsigned World::GetSeaSize(const unsigned seaId) const { RTTR_Assert(seaId > 0 && seaId <= seas.size()); return seas[seaId - 1].nodes_count; } unsigned short World::GetSeaId(const unsigned harborId, const Direction dir) const { RTTR_Assert(harborId); return harbor_pos[harborId].seaIds[dir]; } /// Grenzt der Hafen an ein bestimmtes Meer an? bool World::IsHarborAtSea(const unsigned harborId, const unsigned short seaId) const { return GetCoastalPoint(harborId, seaId).isValid(); } MapPoint World::GetCoastalPoint(const unsigned harborId, const unsigned short seaId) const { RTTR_Assert(harborId); RTTR_Assert(seaId); // Take point at NW last as often there is no path from it if the harbor is north of an island for(auto dir : helpers::enumRange(Direction::NorthEast)) { if(harbor_pos[harborId].seaIds[dir] == seaId) return GetNeighbour(harbor_pos[harborId].pos, dir); } // Keinen Punkt gefunden return MapPoint::Invalid(); } PointRoad World::GetRoad(const MapPoint pt, RoadDir dir) const { return GetNode(pt).roads[dir]; } PointRoad World::GetPointRoad(MapPoint pt, Direction dir) const { const RoadDir rDir = toRoadDir(pt, dir); return GetRoad(pt, rDir); } PointRoad World::GetPointFOWRoad(MapPoint pt, Direction dir, const unsigned char viewing_player) const { const RoadDir rDir = toRoadDir(pt, dir); return GetNode(pt).fow[viewing_player].roads[rDir]; } void World::AddCatapultStone(CatapultStone* cs) { RTTR_Assert(!helpers::contains(catapult_stones, cs)); catapult_stones.push_back(cs); } void World::RemoveCatapultStone(CatapultStone* cs) { RTTR_Assert(helpers::contains(catapult_stones, cs)); catapult_stones.remove(cs); } MapPoint World::GetHarborPoint(const unsigned harborId) const { RTTR_Assert(harborId); return harbor_pos[harborId].pos; } const std::vector<HarborPos::Neighbor>& World::GetHarborNeighbors(const unsigned harborId, const ShipDirection& dir) const { RTTR_Assert(harborId); return harbor_pos[harborId].neighbors[dir]; } /// Berechnet die Entfernung zwischen 2 Hafenpunkten unsigned World::CalcHarborDistance(unsigned habor_id1, unsigned harborId2) const { if(habor_id1 == harborId2) // special case: distance to self return 0; for(const auto dir : helpers::EnumRange<ShipDirection>{}) { for(const HarborPos::Neighbor& n : harbor_pos[habor_id1].neighbors[dir]) { if(n.id == harborId2) return n.distance; } } return 0xffffffff; } unsigned short World::GetSeaFromCoastalPoint(const MapPoint pt) const { // Point itself must not be a sea if(GetNode(pt).seaId) return 0; // Should not be inside water itself if(IsWaterPoint(pt)) return 0; // Surrounding must be valid sea for(const MapPoint nb : GetNeighbours(pt)) { unsigned short seaId = GetNode(nb).seaId; if(seaId) { // Check size (TODO: Others checks like harbor spots?) if(GetSeaSize(seaId) > 20) return seaId; } } return 0; } void World::SetRoad(const MapPoint pt, RoadDir roadDir, PointRoad type) { GetNodeInt(pt).roads[roadDir] = type; } bool World::SetBQ(const MapPoint pt, BuildingQuality bq) { BuildingQuality oldBQ = bq; std::swap(GetNodeInt(pt).bq, oldBQ); return oldBQ != bq; } void World::RecalcShadow(const MapPoint pt) { int altitude = GetNode(pt).altitude; int A = GetNeighbourNode(pt, Direction::NorthEast).altitude - altitude; int B = GetNode(GetNeighbour2(pt, 0)).altitude - altitude; int C = GetNode(GetNeighbour(pt, Direction::West)).altitude - altitude; int D = GetNode(GetNeighbour2(pt, 11)).altitude - altitude; int shadingS2 = 64 + 9 * A - 3 * B - 6 * C - 9 * D; if(shadingS2 > 128) shadingS2 = 128; else if(shadingS2 < 0) shadingS2 = 0; GetNodeInt(pt).shadow = shadingS2; } void World::MakeWholeMapVisibleForAllPlayers() { for(auto& mapNode : nodes) { for(auto& fowNode : mapNode.fow) { fowNode.visibility = Visibility::Visible; fowNode.object.reset(); } } }
412
0.97789
1
0.97789
game-dev
MEDIA
0.627616
game-dev
0.974005
1
0.974005
SonyWWS/ATF
3,556
Samples/UsingDom/Schemas/GameSchema.cs
// ------------------------------------------------------------------------------------------------------------------- // Generated code, do not edit // Command Line: DomGen "game.xsd" "GameSchema.cs" "Game.UsingDom" "UsingDom" // ------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Sce.Atf.Dom; namespace UsingDom { public static class GameSchema { public const string NS = "Game.UsingDom"; public static void Initialize(XmlSchemaTypeCollection typeCollection) { Initialize((ns,name)=>typeCollection.GetNodeType(ns,name), (ns,name)=>typeCollection.GetRootElement(ns,name)); } public static void Initialize(IDictionary<string, XmlSchemaTypeCollection> typeCollections) { Initialize((ns,name)=>typeCollections[ns].GetNodeType(name), (ns,name)=>typeCollections[ns].GetRootElement(name)); } private static void Initialize(Func<string, string, DomNodeType> getNodeType, Func<string, string, ChildInfo> getRootElement) { gameType.Type = getNodeType("Game.UsingDom", "gameType"); gameType.nameAttribute = gameType.Type.GetAttributeInfo("name"); gameType.gameObjectChild = gameType.Type.GetChildInfo("gameObject"); gameObjectType.Type = getNodeType("Game.UsingDom", "gameObjectType"); gameObjectType.nameAttribute = gameObjectType.Type.GetAttributeInfo("name"); ogreType.Type = getNodeType("Game.UsingDom", "ogreType"); ogreType.nameAttribute = ogreType.Type.GetAttributeInfo("name"); ogreType.sizeAttribute = ogreType.Type.GetAttributeInfo("size"); ogreType.strengthAttribute = ogreType.Type.GetAttributeInfo("strength"); dwarfType.Type = getNodeType("Game.UsingDom", "dwarfType"); dwarfType.nameAttribute = dwarfType.Type.GetAttributeInfo("name"); dwarfType.ageAttribute = dwarfType.Type.GetAttributeInfo("age"); dwarfType.experienceAttribute = dwarfType.Type.GetAttributeInfo("experience"); treeType.Type = getNodeType("Game.UsingDom", "treeType"); treeType.nameAttribute = treeType.Type.GetAttributeInfo("name"); gameRootElement = getRootElement(NS, "game"); } public static class gameType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo gameObjectChild; } public static class gameObjectType { public static DomNodeType Type; public static AttributeInfo nameAttribute; } public static class ogreType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo sizeAttribute; public static AttributeInfo strengthAttribute; } public static class dwarfType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo ageAttribute; public static AttributeInfo experienceAttribute; } public static class treeType { public static DomNodeType Type; public static AttributeInfo nameAttribute; } public static ChildInfo gameRootElement; } }
412
0.677612
1
0.677612
game-dev
MEDIA
0.73485
game-dev,desktop-app
0.89178
1
0.89178
bepu/bepuphysics1
2,990
Documentation/Isolated Demos/BasicSetupDemo/EntityModel.cs
using ConversionHelper; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using BEPUphysics.Entities; namespace BasicSetupDemo { /// <summary> /// Component that draws a model following the position and orientation of a BEPUphysics entity. /// </summary> public class EntityModel : DrawableGameComponent { /// <summary> /// Entity that this model follows. /// </summary> Entity entity; Model model; /// <summary> /// Base transformation to apply to the model. /// </summary> public Matrix Transform; Matrix[] boneTransforms; /// <summary> /// Creates a new EntityModel. /// </summary> /// <param name="entity">Entity to attach the graphical representation to.</param> /// <param name="model">Graphical representation to use for the entity.</param> /// <param name="transform">Base transformation to apply to the model before moving to the entity.</param> /// <param name="game">Game to which this component will belong.</param> public EntityModel(Entity entity, Model model, Matrix transform, Game game) : base(game) { this.entity = entity; this.model = model; this.Transform = transform; //Collect any bone transformations in the model itself. //The default cube model doesn't have any, but this allows the EntityModel to work with more complicated shapes. boneTransforms = new Matrix[model.Bones.Count]; foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); } } } public override void Draw(GameTime gameTime) { //Notice that the entity's worldTransform property is being accessed here. //This property is returns a rigid transformation representing the orientation //and translation of the entity combined. //There are a variety of properties available in the entity, try looking around //in the list to familiarize yourself with it. var worldMatrix = Transform * MathConverter.Convert(entity.WorldTransform); model.CopyAbsoluteBoneTransformsTo(boneTransforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix; effect.View = MathConverter.Convert((Game as BasicSetupGame).Camera.ViewMatrix); effect.Projection = MathConverter.Convert((Game as BasicSetupGame).Camera.ProjectionMatrix); } mesh.Draw(); } base.Draw(gameTime); } } }
412
0.673716
1
0.673716
game-dev
MEDIA
0.639628
game-dev,graphics-rendering
0.889881
1
0.889881
stephengold/kk-physics
14,676
library/src/main/java/com/jme3/bullet/collision/PhysicsCollisionObject.java
/* * Copyright (c) 2009-2018 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.bullet.collision; import com.jme3.bounding.BoundingBox; import com.jme3.bullet.CollisionSpace; import com.jme3.bullet.PhysicsSpace; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.material.Material; import com.jme3.math.Matrix3f; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.simsilica.mathd.Vec3d; import java.util.logging.Logger; import jme3utilities.MeshNormals; import jme3utilities.Validate; /** * The abstract base class for collision objects. * <p> * Subclasses include {@code PhysicsBody}. * * @author normenhansen */ abstract public class PhysicsCollisionObject implements Comparable<PhysicsCollisionObject> { // ************************************************************************* // constants and loggers /** * message logger for this class */ final public static Logger logger = Logger.getLogger(PhysicsCollisionObject.class.getName()); // ************************************************************************* // fields /** * shape of this object, or null if none */ private CollisionShape collisionShape; /** * number of visible sides for default debug materials (&ge;0, &le;2) */ private int debugNumSides = 1; /** * custom material for the debug shape, or null to use the default material */ private Material debugMaterial = null; /** * which normals to generate for new debug meshes */ private MeshNormals debugMeshNormals = MeshNormals.None; /** * application-specific data of this collision object. Untouched. */ private Object applicationData = null; /** * scene object that's using this collision object. The scene object is * typically a PhysicsControl, PhysicsLink, or Spatial. Used by physics * controls. */ private Object userObject = null; /** * space where this collision object has been added, or null if removed or * never added */ private PhysicsSpace addedToSpace = null; // ************************************************************************* // constructors /** * Instantiate a collision object with no shape or user object. * <p> * This no-arg constructor was made explicit to avoid javadoc warnings from * JDK 18+. */ protected PhysicsCollisionObject() { } // ************************************************************************* // new methods exposed /** * Reactivate the collision object if it has been deactivated due to lack of * motion. * * @param forceFlag true to force activation */ abstract public void activate(boolean forceFlag); /** * Calculate an axis-aligned bounding box for this object, based on its * collision shape. Note: the calculated bounds are seldom minimal; they are * typically larger than necessary due to centering constraints and * collision margins. * * @param storeResult storage for the result (modified if not null) * @return a bounding box in physics-space coordinates (either storeResult * or a new instance) */ public BoundingBox boundingBox(BoundingBox storeResult) { BoundingBox result = (storeResult == null) ? new BoundingBox() : storeResult; Vector3f translation = getPhysicsLocation(null); Matrix3f rotation = getPhysicsRotationMatrix(null); collisionShape.boundingBox(translation, rotation, result); return result; } /** * Determine which normals to include in new debug meshes. * * @return an enum value (not null) */ public MeshNormals debugMeshNormals() { assert debugMeshNormals != null; return debugMeshNormals; } /** * Determine how many sides of this object's default debug materials are * visible. * * @return the number of sides (&ge;0, &le;2) */ public int debugNumSides() { assert debugNumSides >= 0 : debugNumSides; assert debugNumSides <= 2 : debugNumSides; return debugNumSides; } /** * Access any application-specific data associated with the collision * object. * * @return the pre-existing instance, or null if none * @see #setApplicationData(java.lang.Object) */ public Object getApplicationData() { return applicationData; } /** * Access the shape of the collision object. * * @return the pre-existing instance, or null if none */ public CollisionShape getCollisionShape() { return collisionShape; } /** * Access the space where the collision object is added. * * @return the pre-existing instance, or null if none */ public CollisionSpace getCollisionSpace() { return addedToSpace; } /** * Access the custom debug material, if specified. * * @return the pre-existing instance, or null for default materials */ public Material getDebugMaterial() { return debugMaterial; } /** * Return the collision object's friction ratio. * * @return the ratio */ abstract public float getFriction(); /** * For compatibility with the jme3-jbullet library. * * @return a new location vector (in physics-space coordinates, not null) */ public Vector3f getPhysicsLocation() { return getPhysicsLocation(null); } /** * Locate the collision object's center. * * @param storeResult storage for the result (modified if not null) * @return a location vector (in physics-space coordinates, either * storeResult or a new vector, finite) */ abstract public Vector3f getPhysicsLocation(Vector3f storeResult); /** * Locate the collision object's center in double precision. * * @param storeResult storage for the result (modified if not null) * @return a location vector (in physics-space coordinates, either * storeResult or a new vector, not null, finite) */ abstract public Vec3d getPhysicsLocationDp(Vec3d storeResult); /** * Copy the orientation (rotation) of the collision object to a Quaternion. * * @param storeResult storage for the result (modified if not null) * @return a rotation Quaternion (in physics-space coordinates, either * storeResult or a new instance, not null) */ abstract public Quaternion getPhysicsRotation(Quaternion storeResult); /** * Copy the orientation of the collision object (the basis of its local * coordinate system) to a Matrix3f. * * @param storeResult storage for the result (modified if not null) * @return a rotation matrix (in physics-space coordinates, either * storeResult or a new matrix, not null) */ abstract public Matrix3f getPhysicsRotationMatrix(Matrix3f storeResult); /** * Return the collision object's restitution (bounciness). * * @return restitution value */ abstract public float getRestitution(); /** * Access the scene object that's using the collision object, typically a * PhysicsControl, PhysicsLink, or Spatial. Used by physics controls. * * @return the pre-existing instance, or null if none * @see #getApplicationData() * @see #setUserObject(java.lang.Object) */ public Object getUserObject() { return userObject; } /** * Test whether a Jolt-JNI object is assigned to this collision object. * * @return true if one is assigned, otherwise false */ abstract public boolean hasAssignedNativeObject(); /** * Test whether the collision object has been deactivated due to lack of * motion. * * @return true if object still active, false if deactivated */ abstract public boolean isActive(); /** * Test whether the collision object responds to contact with other objects. * All ghost objects are non-responsive. Other types are responsive by * default. * * @return true if responsive, otherwise false */ abstract public boolean isContactResponse(); /** * Test whether the collision object is added to a space. * * @return true&rarr;added to a space, false&rarr;not added to a space */ final public boolean isInWorld() { if (addedToSpace == null) { return false; } else { return true; } } /** * Test whether the collision object is static (immobile). * * @return true if static, otherwise false */ abstract public boolean isStatic(); /** * Return the address of the assigned native object, assuming one is * assigned. * * @return the virtual address (not zero) */ abstract public long nativeId(); /** * Alter the {@code addedToSpace} field. Internal use only. * * @param physicsSpace (may be null, alias created) */ public void setAddedToSpaceInternal(PhysicsSpace physicsSpace) { this.addedToSpace = physicsSpace; } /** * Associate application-specific data with the collision object. KK Physics * never touches application-specific data. * * @param data the desired data object (alias created, default=null) * @see #getApplicationData() */ public void setApplicationData(Object data) { this.applicationData = data; } /** * Apply the specified shape to the collision object. Meant to be * overridden. * * @param collisionShape the shape to apply (not null, alias created) */ public void setCollisionShape(CollisionShape collisionShape) { Validate.nonNull(collisionShape, "collision shape"); this.collisionShape = collisionShape; } /** * Apply or remove a custom debug material. * * @param material the Material to use (alias created) or null to use the * default debug materials (default=null) */ public void setDebugMaterial(Material material) { this.debugMaterial = material; } /** * Alter which normals to include in new debug meshes. * * @param newSetting an enum value (not null, default=None) */ public void setDebugMeshNormals(MeshNormals newSetting) { Validate.nonNull(newSetting, "new setting"); this.debugMeshNormals = newSetting; } /** * Alter how many sides of this object's default debug materials are * visible. This setting has no effect on custom debug materials. * * @param numSides the desired number of sides (&ge;0, &le;2, default=1) */ public void setDebugNumSides(int numSides) { Validate.inRange(numSides, "number of sides", 0, 2); this.debugNumSides = numSides; } /** * Alter the collision object's friction ratio. * * @param friction the desired ratio (default=0.5) */ abstract public void setFriction(float friction); /** * Alter the collision object's restitution (bounciness). For perfect * elasticity, set restitution=1. * * @param restitution the desired value (default=0) */ abstract public void setRestitution(float restitution); /** * Associate a "user" with the collision object. Used by physics controls. * * @param user the desired scene object (alias created, default=null) * @see #getUserObject() * @see #setApplicationData(java.lang.Object) */ public void setUserObject(Object user) { this.userObject = user; } // ************************************************************************* // Comparable methods /** * Compare (by ID) with another collision object. * * @param other (not null, unaffected) * @return 0 if the objects have the same native ID; negative if this comes * before other; positive if this comes after other */ @Override public int compareTo(PhysicsCollisionObject other) { long objectId = nativeId(); long otherId = other.nativeId(); int result = Long.compare(objectId, otherId); return result; } // ************************************************************************* // Object methods /** * Represent the collision object as a {@code String}. * * @return a descriptive string of text (not null, not empty) */ @Override public String toString() { String result = getClass().getSimpleName(); result = result.replace("Body", ""); result = result.replace("Control", "C"); result = result.replace("Physics", ""); result = result.replace("Object", ""); if (hasAssignedNativeObject()) { long objectId = nativeId(); result += "#" + Long.toHexString(objectId); } else { result += "#unassigned"; } return result; } }
412
0.837999
1
0.837999
game-dev
MEDIA
0.788091
game-dev
0.807209
1
0.807209
freeciv/freeciv
110,986
common/unittype.c
/*********************************************************************** Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include <fc_config.h> #endif #include <string.h> #include <math.h> /* ceil */ /* utility */ #include "astring.h" #include "fcintl.h" #include "log.h" #include "mem.h" #include "shared.h" #include "string_vector.h" #include "support.h" /* common */ #include "ai.h" #include "combat.h" #include "game.h" #include "government.h" #include "movement.h" #include "player.h" #include "research.h" #include "unitlist.h" #include "unittype.h" #define MAX_UNIT_ROLES L_LAST + ACTION_COUNT static struct unit_type unit_types[U_LAST]; static struct unit_class unit_classes[UCL_LAST]; /* the unit_types and unit_classes arrays are now setup in: server/ruleset.c (for the server) client/packhand.c (for the client) */ static struct user_flag user_type_flags[MAX_NUM_USER_UNIT_FLAGS]; static struct user_flag user_class_flags[MAX_NUM_USER_UCLASS_FLAGS]; /**********************************************************************//** Return the first item of unit_types. **************************************************************************/ struct unit_type *unit_type_array_first(void) { if (game.control.num_unit_types > 0) { return unit_types; } return nullptr; } /**********************************************************************//** Return the last item of unit_types. **************************************************************************/ const struct unit_type *unit_type_array_last(void) { if (game.control.num_unit_types > 0) { return &unit_types[game.control.num_unit_types - 1]; } return nullptr; } /**********************************************************************//** Return the number of unit types. **************************************************************************/ Unit_type_id utype_count(void) { return game.control.num_unit_types; } /**********************************************************************//** Return the unit type index. Currently same as utype_number(), paired with utype_count() indicates use as an array index. **************************************************************************/ Unit_type_id utype_index(const struct unit_type *punittype) { fc_assert_ret_val(punittype, -1); return punittype - unit_types; } /**********************************************************************//** Return the unit type index. **************************************************************************/ Unit_type_id utype_number(const struct unit_type *punittype) { fc_assert_ret_val(punittype, -1); return punittype->item_number; } /**********************************************************************//** Return a pointer for the unit type struct for the given unit type id. This function returns nullptr for invalid unit pointers (some callers rely on this). **************************************************************************/ struct unit_type *utype_by_number(const Unit_type_id id) { if (id < 0 || id >= game.control.num_unit_types) { return nullptr; } return &unit_types[id]; } /**********************************************************************//** Return the unit type for this unit. **************************************************************************/ const struct unit_type *unit_type_get(const struct unit *punit) { fc_assert_ret_val(punit != nullptr, nullptr); return punit->utype; } /**********************************************************************//** Returns the upkeep of a unit of this type. **************************************************************************/ int utype_upkeep_cost(const struct unit_type *ut, const struct unit *punit, struct player *pplayer, Output_type_id otype) { int val = ut->upkeep[otype], gold_upkeep_factor; struct tile *ptile; struct city *pcity; if (punit != nullptr) { ptile = unit_tile(punit); pcity = game_city_by_number(punit->homecity); } else { ptile = nullptr; pcity = nullptr; } if (BV_ISSET(ut->flags, UTYF_FANATIC) && get_player_bonus(pplayer, EFT_FANATICS) > 0) { /* Special case: fanatics have no upkeep under fanaticism. */ return 0; } /* Switch shield upkeep to gold upkeep if - the effect 'EFT_SHIELD2GOLD_PCT is non-zero (it gives the conversion factor in percent) and FIXME: Should the ai know about this? */ if (otype == O_GOLD || otype == O_SHIELD) { gold_upkeep_factor = get_target_bonus_effects(nullptr, &(const struct req_context) { .player = pplayer, .unittype = ut, .unit = punit, .tile = ptile, .city = pcity }, nullptr, EFT_SHIELD2GOLD_PCT); if (gold_upkeep_factor > 0) { switch (otype) { case O_GOLD: val = ceil((0.01 * gold_upkeep_factor) * ut->upkeep[O_SHIELD]); break; case O_SHIELD: val = 0; break; default: fc_assert(otype == O_GOLD || otype == O_SHIELD); break; } } } val *= get_target_bonus_effects(nullptr, &(const struct req_context) { .player = pplayer, .output = get_output_type(otype), .unittype = ut, .unit = punit, .tile = ptile, .city = pcity }, nullptr, EFT_UPKEEP_PCT) / 100; return val; } /**********************************************************************//** Return the "happy cost" (the number of citizens who are discontented) for this unit. **************************************************************************/ int utype_happy_cost(const struct unit_type *ut, const struct player *pplayer) { return ut->happy_cost * get_player_bonus(pplayer, EFT_UNHAPPY_FACTOR); } /**********************************************************************//** Return whether the unit has the given flag. **************************************************************************/ bool unit_has_type_flag(const struct unit *punit, enum unit_type_flag_id flag) { return utype_has_flag(unit_type_get(punit), flag); } /**********************************************************************//** Return whether the given unit type has the role. Roles are like flags but have no meaning except to the AI. **************************************************************************/ bool utype_has_role(const struct unit_type *punittype, int role) { fc_assert_ret_val(role >= L_FIRST && role < L_LAST, FALSE); return BV_ISSET(punittype->roles, role - L_FIRST); } /**********************************************************************//** Return whether the unit has the given role. **************************************************************************/ bool unit_has_type_role(const struct unit *punit, enum unit_role_id role) { return utype_has_role(unit_type_get(punit), role); } /**********************************************************************//** Return whether the unit can do an action that creates the specified extra kind. **************************************************************************/ bool utype_can_create_extra(const struct unit_type *putype, const struct extra_type *pextra) { action_iterate(act_id) { struct action *paction = action_by_number(act_id); if (!utype_can_do_action(putype, act_id)) { /* Not relevant. */ continue; } if (actres_creates_extra(paction->result, pextra)) { /* Can create */ return TRUE; } } action_iterate_end; return FALSE; } /**********************************************************************//** Return whether the unit can do an action that removes the specified extra kind. **************************************************************************/ bool utype_can_remove_extra(const struct unit_type *putype, const struct extra_type *pextra) { action_iterate(act_id) { struct action *paction = action_by_number(act_id); if (!utype_can_do_action(putype, act_id)) { /* Not relevant. */ continue; } if (actres_removes_extra(paction->result, pextra)) { /* Can remove */ return TRUE; } } action_iterate_end; return FALSE; } /**********************************************************************//** Return whether the unit can take over enemy cities. **************************************************************************/ bool unit_can_take_over(const struct unit *punit) { /* TODO: Should unit state dependent action enablers be considered? * Some callers aren't yet ready for changeable unit state (like current * location) playing a role. */ return unit_owner(punit)->ai_common.barbarian_type != ANIMAL_BARBARIAN && utype_can_take_over(unit_type_get(punit)); } /**********************************************************************//** Return whether the unit type can take over enemy cities. **************************************************************************/ bool utype_can_take_over(const struct unit_type *punittype) { /* FIXME: "Paradrop Unit" can in certain circumstances result in city * conquest. */ return utype_can_do_action_result(punittype, ACTRES_CONQUER_CITY); } /**********************************************************************//** Return TRUE iff the given cargo type has no restrictions on when it can load onto the given transporter. (Does not check that cargo is valid for transport!) **************************************************************************/ bool utype_can_freely_load(const struct unit_type *pcargotype, const struct unit_type *ptranstype) { return BV_ISSET(pcargotype->embarks, uclass_index(utype_class(ptranstype))); } /**********************************************************************//** Return TRUE iff the given cargo type has no restrictions on when it can unload from the given transporter. (Does not check that cargo is valid for transport!) **************************************************************************/ bool utype_can_freely_unload(const struct unit_type *pcargotype, const struct unit_type *ptranstype) { return BV_ISSET(pcargotype->disembarks, uclass_index(utype_class(ptranstype))); } /* Fake action id representing any hostile action. */ #define ACTION_HOSTILE ACTION_COUNT + 1 /* Number of real and fake actions. */ #define ACTION_AND_FAKES ACTION_HOSTILE + 1 /* Cache of what generalized (ruleset defined) action enabler controlled * actions units of each type can perform. Checking if any action can be * done at all is done via the fake action id ACTION_ANY. If any hostile * action can be performed is done via ACTION_HOSTILE. */ static bv_unit_types unit_can_act_cache[ACTION_AND_FAKES]; /**********************************************************************//** Cache what generalized (ruleset defined) action enabler controlled actions a unit of the given type can perform. **************************************************************************/ static void unit_can_act_cache_set(struct unit_type *putype) { /* Clear old values. */ action_iterate(act_id) { BV_CLR(unit_can_act_cache[act_id], utype_index(putype)); } action_iterate_end; BV_CLR(unit_can_act_cache[ACTION_ANY], utype_index(putype)); BV_CLR(unit_can_act_cache[ACTION_HOSTILE], utype_index(putype)); /* See if the unit type can do an action controlled by generalized action * enablers */ action_enablers_iterate(enabler) { const struct action *paction = enabler_get_action(enabler); action_id act_id = action_id(paction); if (action_get_actor_kind(paction) == AAK_UNIT && action_actor_utype_hard_reqs_ok(paction, putype) && requirement_fulfilled_by_unit_type(putype, &(enabler->actor_reqs))) { log_debug("act_cache: %s can %s", utype_rule_name(putype), action_rule_name(paction)); BV_SET(unit_can_act_cache[act_id], utype_index(putype)); BV_SET(unit_can_act_cache[ACTION_ANY], utype_index(putype)); if (actres_is_hostile(paction->result)) { BV_SET(unit_can_act_cache[ACTION_HOSTILE], utype_index(putype)); } } } action_enablers_iterate_end; } /**********************************************************************//** Return TRUE iff units of this type can do actions controlled by generalized (ruleset defined) action enablers. **************************************************************************/ bool utype_may_act_at_all(const struct unit_type *putype) { return utype_can_do_action(putype, ACTION_ANY); } /**********************************************************************//** Return TRUE iff units of the given type can do the specified generalized (ruleset defined) action enabler controlled action. Note that a specific unit in a specific situation still may be unable to perform the specified action. **************************************************************************/ bool utype_can_do_action(const struct unit_type *putype, const action_id act_id) { fc_assert_ret_val(putype, FALSE); fc_assert_ret_val(act_id >= 0 && act_id < ACTION_AND_FAKES, FALSE); return BV_ISSET(unit_can_act_cache[act_id], utype_index(putype)); } /**********************************************************************//** Return TRUE iff units of the given type can do any enabler controlled action with the specified action result. Note that a specific unit in a specific situation still may be unable to perform the specified action. **************************************************************************/ bool utype_can_do_action_result(const struct unit_type *putype, enum action_result result) { fc_assert_ret_val(putype, FALSE); action_by_result_iterate(paction, result) { if (utype_can_do_action(putype, action_id(paction))) { return TRUE; } } action_by_result_iterate_end; return FALSE; } /**********************************************************************//** Return TRUE iff units of the given type can do any enabler controlled action with the specified action sub result. Note that a specific unit in a specific situation still may be unable to perform the specified action. **************************************************************************/ bool utype_can_do_action_sub_result(const struct unit_type *putype, enum action_sub_result sub_result) { fc_assert_ret_val(putype, FALSE); action_iterate(act_id) { struct action *paction = action_by_number(act_id); if (!BV_ISSET(paction->sub_results, sub_result)) { /* Not relevant */ continue; } if (utype_can_do_action(putype, paction->id)) { return TRUE; } } action_iterate_end; return FALSE; } /**********************************************************************//** Return TRUE iff the unit type can perform the action corresponding to the unit type role. **************************************************************************/ static bool utype_can_do_action_role(const struct unit_type *putype, const int role) { return utype_can_do_action(putype, role - L_LAST); } /**********************************************************************//** Return TRUE iff units of this type can do hostile actions controlled by generalized (ruleset defined) action enablers. **************************************************************************/ bool utype_acts_hostile(const struct unit_type *putype) { return utype_can_do_action(putype, ACTION_HOSTILE); } /* Cache of if a generalized (ruleset defined) action enabler controlled * action always spends all remaining movement of a unit of the specified * unit type. */ static bv_unit_types utype_act_takes_all_mp_cache[ACTION_COUNT]; /**********************************************************************//** Cache what generalized (ruleset defined) action enabler controlled actions spends all remaining MP for a given unit type. **************************************************************************/ static void utype_act_takes_all_mp_cache_set(struct unit_type *putype) { action_iterate(act_id) { /* See if the unit type has all remaining MP spent by the specified * action. */ struct action *paction = action_by_number(act_id); struct universal unis[] = { { .kind = VUT_ACTION, .value = {.action = (paction)} }, { .kind = VUT_UTYPE, .value = {.utype = (putype)} } }; if (!utype_can_do_action(putype, paction->id)) { /* Not relevant. */ continue; } if (effect_universals_value_never_below(EFT_ACTION_SUCCESS_MOVE_COST, unis, ARRAY_SIZE(unis), MAX_MOVE_FRAGS)) { /* Guaranteed to always consume all remaining MP of an actor unit of * this type. */ log_debug("unit_act_takes_all_mp_cache_set: %s takes all MP from %s", utype_rule_name(putype), action_rule_name(paction)); BV_SET(utype_act_takes_all_mp_cache[paction->id], utype_index(putype)); } else { /* Clear old value in case it was set. */ BV_CLR(utype_act_takes_all_mp_cache[paction->id], utype_index(putype)); } } action_iterate_end; } /* Cache of if a generalized (ruleset defined) action enabler controlled * action always spends all remaining movement of a unit of the specified * unit type given the specified unit state property. */ static bv_unit_types utype_act_takes_all_mp_ustate_cache[ACTION_COUNT][USP_COUNT]; /**********************************************************************//** Cache what generalized (ruleset defined) action enabler controlled actions spends all remaining MP for a given unit type given the specified unit state property. **************************************************************************/ static void utype_act_takes_all_mp_ustate_cache_set(struct unit_type *putype) { action_iterate(act_id) { /* See if the unit type has all remaining MP spent by the specified * action given the specified unit state property. */ enum ustate_prop prop = ustate_prop_begin(); struct action *paction = action_by_number(act_id); struct universal unis[] = { { .kind = VUT_ACTION, .value = {.action = (paction)} }, { .kind = VUT_UTYPE, .value = {.utype = (putype)} }, { .kind = VUT_UNITSTATE, .value = {.unit_state = (prop)} } }; if (!utype_can_do_action(putype, paction->id)) { /* Not relevant. */ continue; } for (prop = ustate_prop_begin(); prop != ustate_prop_end(); prop = ustate_prop_next(prop)) { unis[2].value.unit_state = prop; if (effect_universals_value_never_below(EFT_ACTION_SUCCESS_MOVE_COST, unis, ARRAY_SIZE(unis), MAX_MOVE_FRAGS)) { /* Guaranteed to always consume all remaining MP of an actor unit of * this type given the specified unit state property. */ log_debug("unit_act_takes_all_mp_cache_set: %s takes all MP from %s" " when unit state is %s", utype_rule_name(putype), action_rule_name(paction), ustate_prop_name(prop)); BV_SET(utype_act_takes_all_mp_ustate_cache[paction->id][prop], utype_index(putype)); } else { /* Clear old value in case it was set. */ BV_CLR(utype_act_takes_all_mp_ustate_cache[paction->id][prop], utype_index(putype)); } } } action_iterate_end; } /* Cache if any action at all may be possible when the actor unit's state * is... * bit 0 to USP_COUNT - 1: Possible when the corresponding property is TRUE * bit USP_COUNT to ((USP_COUNT * 2) - 1): Possible when the corresponding * property is FALSE */ BV_DEFINE(bv_ustate_act_cache, USP_COUNT * 2); /* Cache what actions may be possible when the target's local citytile state * is * bit 0 to CITYT_LAST - 1: Possible when the corresponding property is TRUE * bit USP_COUNT to ((CITYT_LAST * 2) - 1): Possible when the corresponding * property is FALSE */ BV_DEFINE(bv_citytile_cache, CITYT_LAST * 2); /* Cache position lookup functions */ #define requirement_unit_state_ereq(_id_, _present_) \ requirement_kind_ereq(_id_, REQ_RANGE_LOCAL, _present_, USP_COUNT) #define requirement_citytile_ereq(_id_, _present_) \ requirement_kind_ereq(_id_, REQ_RANGE_LOCAL, _present_, CITYT_LAST) /* Caches for each unit type */ static bv_ustate_act_cache ustate_act_cache[U_LAST][ACTION_AND_FAKES]; static bv_diplrel_all_reqs dipl_rel_action_cache[U_LAST][ACTION_AND_FAKES]; static bv_diplrel_all_reqs dipl_rel_tile_other_tgt_a_cache[U_LAST][ACTION_AND_FAKES]; static bv_citytile_cache ctile_tgt_act_cache[U_LAST][ACTION_AND_FAKES]; /**********************************************************************//** Cache if any action may be possible for a unit of the type putype for each unit state property. Since a unit state property could be ignored both present and !present must be checked. **************************************************************************/ static void unit_state_action_cache_set(struct unit_type *putype) { struct requirement req; int uidx = utype_index(putype); /* The unit is not yet known to be allowed to perform any actions no * matter what its unit state is. */ action_iterate(act_id) { BV_CLR_ALL(ustate_act_cache[uidx][act_id]); } action_iterate_end; BV_CLR_ALL(ustate_act_cache[uidx][ACTION_ANY]); BV_CLR_ALL(ustate_act_cache[uidx][ACTION_HOSTILE]); if (!utype_may_act_at_all(putype)) { /* Not an actor unit. */ return; } /* Common for every situation */ req.range = REQ_RANGE_LOCAL; req.survives = FALSE; req.source.kind = VUT_UNITSTATE; for (req.source.value.unit_state = ustate_prop_begin(); req.source.value.unit_state != ustate_prop_end(); req.source.value.unit_state = ustate_prop_next( req.source.value.unit_state)) { /* No action will ever be possible in a specific unit state if the * opposite unit state is required in all action enablers. * No unit state except present and !present of the same property * implies or conflicts with another so the tests can be simple. */ action_enablers_iterate(enabler) { struct action *paction = enabler_get_action(enabler); if (requirement_fulfilled_by_unit_type(putype, &(enabler->actor_reqs)) && action_get_actor_kind(paction) == AAK_UNIT) { bool present = TRUE; do { action_id act_id = enabler_get_action_id(enabler); /* OK if not mentioned */ req.present = present; if (!is_req_in_vec(&req, &(enabler->actor_reqs))) { BV_SET(ustate_act_cache[utype_index(putype)][act_id], requirement_unit_state_ereq(req.source.value.unit_state, !req.present)); if (actres_is_hostile(paction->result)) { BV_SET(ustate_act_cache[utype_index(putype)][ACTION_HOSTILE], requirement_unit_state_ereq(req.source.value.unit_state, !req.present)); } BV_SET(ustate_act_cache[utype_index(putype)][ACTION_ANY], requirement_unit_state_ereq(req.source.value.unit_state, !req.present)); } present = !present; } while (!present); } } action_enablers_iterate_end; } } /**********************************************************************//** Cache what actions may be possible for a unit of the type putype for each local DiplRel variation. Since a diplomatic relationship could be ignored both present and !present must be checked. Note: since can_unit_act_when_local_diplrel_is() only supports querying the local range no values for the other ranges are set. **************************************************************************/ static void local_dipl_rel_action_cache_set(struct unit_type *putype) { struct requirement req; struct requirement tile_is_claimed; int uidx = utype_index(putype); /* The unit is not yet known to be allowed to perform any actions no * matter what the diplomatic state is. */ action_iterate(act_id) { BV_CLR_ALL(dipl_rel_action_cache[uidx][act_id]); } action_iterate_end; BV_CLR_ALL(dipl_rel_action_cache[uidx][ACTION_ANY]); BV_CLR_ALL(dipl_rel_action_cache[uidx][ACTION_HOSTILE]); if (!utype_may_act_at_all(putype)) { /* Not an actor unit. */ return; } /* Tile is claimed as a requirement. */ tile_is_claimed.range = REQ_RANGE_TILE; tile_is_claimed.survives = FALSE; tile_is_claimed.source.kind = VUT_CITYTILE; tile_is_claimed.present = TRUE; tile_is_claimed.source.value.citytile = CITYT_CLAIMED; /* Common for every situation */ req.range = REQ_RANGE_LOCAL; req.survives = FALSE; req.source.kind = VUT_DIPLREL; /* DiplRel starts with diplstate_type and ends with diplrel_other */ for (req.source.value.diplrel = diplstate_type_begin(); req.source.value.diplrel != DRO_LAST; req.source.value.diplrel++) { /* No action will ever be possible in a specific diplomatic relation if * its presence contradicts all action enablers. * Everything was set to false above. It is therefore OK to only change * the cache when units can do an action given a certain diplomatic * relationship property value. */ action_enablers_iterate(enabler) { struct action *paction = enabler_get_action(enabler); if (requirement_fulfilled_by_unit_type(putype, &(enabler->actor_reqs)) && action_get_actor_kind(paction) == AAK_UNIT && ((action_get_target_kind(paction) != ATK_TILE && action_get_target_kind(paction) != ATK_EXTRAS) /* No diplomatic relation to Nature */ || !does_req_contradicts_reqs(&tile_is_claimed, &enabler->target_reqs))) { bool present = TRUE; do { action_id act_id = enabler_get_action_id(enabler); req.present = present; if (!does_req_contradicts_reqs(&req, &(enabler->actor_reqs))) { BV_SET(dipl_rel_action_cache[uidx][act_id], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); if (actres_is_hostile(paction->result)) { BV_SET(dipl_rel_action_cache[uidx][ACTION_HOSTILE], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); } BV_SET(dipl_rel_action_cache[uidx][ACTION_ANY], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); } present = !present; } while (!present); } } action_enablers_iterate_end; } } /**********************************************************************//** Cache what actions may be possible for a unit of the type putype for each local DiplRelTileOther variation. Since a diplomatic relationship could be ignored both present and !present must be checked. **************************************************************************/ static void local_dipl_rel_tile_other_tgt_action_cache_set(struct unit_type *putype) { struct requirement req; struct requirement tile_is_claimed; int uidx = utype_index(putype); /* The unit is not yet known to be allowed to perform any actions no * matter what the diplomatic state is. */ action_iterate(act_id) { BV_CLR_ALL(dipl_rel_tile_other_tgt_a_cache[uidx][act_id]); } action_iterate_end; BV_CLR_ALL(dipl_rel_tile_other_tgt_a_cache[uidx][ACTION_ANY]); BV_CLR_ALL(dipl_rel_tile_other_tgt_a_cache[uidx][ACTION_HOSTILE]); /* Tile is claimed as a requirement. */ tile_is_claimed.range = REQ_RANGE_TILE; tile_is_claimed.survives = FALSE; tile_is_claimed.source.kind = VUT_CITYTILE; tile_is_claimed.present = TRUE; tile_is_claimed.source.value.citytile = CITYT_CLAIMED; /* Common for every situation */ req.range = REQ_RANGE_LOCAL; req.survives = FALSE; req.source.kind = VUT_DIPLREL_TILE_O; /* DiplRel starts with diplstate_type and ends with diplrel_other */ for (req.source.value.diplrel = diplstate_type_begin(); req.source.value.diplrel != DRO_LAST; req.source.value.diplrel++) { /* No action will ever be possible in a specific diplomatic relation if * its presence contradicts all action enablers. * Everything was set to false above. It is therefore OK to only change * the cache when units can do an action given a certain diplomatic * relationship property value. */ action_enablers_iterate(enabler) { struct action *paction = enabler_get_action(enabler); if (requirement_fulfilled_by_unit_type(putype, &(enabler->actor_reqs)) && action_get_actor_kind(paction) == AAK_UNIT /* No diplomatic relation to Nature */ && !does_req_contradicts_reqs(&tile_is_claimed, &enabler->target_reqs)) { bool present = TRUE; do { action_id act_id = enabler_get_action_id(enabler); req.present = present; if (!does_req_contradicts_reqs(&req, &(enabler->target_reqs))) { BV_SET(dipl_rel_tile_other_tgt_a_cache[uidx][act_id], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); if (actres_is_hostile(paction->result)) { BV_SET(dipl_rel_tile_other_tgt_a_cache[uidx][ACTION_HOSTILE], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); } BV_SET(dipl_rel_tile_other_tgt_a_cache[uidx][ACTION_ANY], requirement_diplrel_ereq(req.source.value.diplrel, REQ_RANGE_LOCAL, req.present)); } present = !present; } while (!present); } } action_enablers_iterate_end; } } /**********************************************************************//** Cache if any action may be possible for a unit of the type putype for each target local city tile property. Both present and !present must be checked since a city tile property could be ignored. **************************************************************************/ static void tgt_citytile_act_cache_set(struct unit_type *putype) { struct requirement req; int uidx = utype_index(putype); /* The unit is not yet known to be allowed to perform any actions no * matter what its target's CityTile state is. */ action_iterate(act_id) { BV_CLR_ALL(ctile_tgt_act_cache[uidx][act_id]); } action_iterate_end; BV_CLR_ALL(ctile_tgt_act_cache[uidx][ACTION_ANY]); BV_CLR_ALL(ctile_tgt_act_cache[uidx][ACTION_HOSTILE]); if (!utype_may_act_at_all(putype)) { /* Not an actor unit. */ return; } /* Common for every situation */ req.range = REQ_RANGE_TILE; req.survives = FALSE; req.source.kind = VUT_CITYTILE; for (req.source.value.citytile = citytile_type_begin(); req.source.value.citytile != citytile_type_end(); req.source.value.citytile = citytile_type_next( req.source.value.citytile)) { /* No action will ever be possible in a target CityTile state if the * opposite target CityTile state is required in all action enablers. * No CityTile property state except present and !present of the same * property implies or conflicts with another so the tests can be * simple. */ action_enablers_iterate(enabler) { struct action *paction = enabler_get_action(enabler); if (requirement_fulfilled_by_unit_type(putype, &(enabler->target_reqs)) && action_get_actor_kind(paction) == AAK_UNIT) { bool present = TRUE; do { action_id act_id = enabler_get_action_id(enabler); /* OK if not mentioned */ req.present = present; if (!is_req_in_vec(&req, &(enabler->target_reqs))) { BV_SET( ctile_tgt_act_cache[utype_index(putype)][act_id], requirement_citytile_ereq(req.source.value.citytile, !req.present)); if (actres_is_hostile(paction->result)) { BV_SET( ctile_tgt_act_cache[utype_index(putype)][ACTION_HOSTILE], requirement_citytile_ereq(req.source.value.citytile, !req.present)); } BV_SET(ctile_tgt_act_cache[utype_index(putype)][ACTION_ANY], requirement_citytile_ereq(req.source.value.citytile, !req.present)); } present = !present; } while (!present); } } action_enablers_iterate_end; } } struct range { int min; int max; }; #define MOVES_LEFT_INFINITY -1 /**********************************************************************//** Get the legal range of move fragments left of the specified requirement vector. **************************************************************************/ static struct range *moves_left_range(struct requirement_vector *reqs) { struct range *prange = fc_malloc(sizeof(prange)); prange->min = 0; prange->max = MOVES_LEFT_INFINITY; requirement_vector_iterate(reqs, preq) { if (preq->source.kind == VUT_MINMOVES) { if (preq->present) { prange->min = preq->source.value.minmoves; } else { prange->max = preq->source.value.minmoves; } } } requirement_vector_iterate_end; return prange; } /**********************************************************************//** Cache if any action may be possible for a unit of the type putype given the property tested for. Since a it could be ignored both present and !present must be checked. **************************************************************************/ void unit_type_action_cache_set(struct unit_type *ptype) { unit_can_act_cache_set(ptype); unit_state_action_cache_set(ptype); local_dipl_rel_action_cache_set(ptype); local_dipl_rel_tile_other_tgt_action_cache_set(ptype); tgt_citytile_act_cache_set(ptype); utype_act_takes_all_mp_cache_set(ptype); utype_act_takes_all_mp_ustate_cache_set(ptype); } /**********************************************************************//** Cache what unit types may be allowed do what actions, both at all and when certain properties are true. **************************************************************************/ void unit_type_action_cache_init(void) { unit_type_iterate(u) { unit_type_action_cache_set(u); } unit_type_iterate_end; } /**********************************************************************//** Return TRUE iff there exists an (action enabler controlled) action that a unit of the type punit_type can perform while its unit state property prop has the value is_there. **************************************************************************/ bool can_unit_act_when_ustate_is(const struct unit_type *punit_type, const enum ustate_prop prop, const bool is_there) { return utype_can_do_act_when_ustate(punit_type, ACTION_ANY, prop, is_there); } /**********************************************************************//** Return TRUE iff the unit type can do the specified (action enabler controlled) action while its unit state property prop has the value is_there. **************************************************************************/ bool utype_can_do_act_when_ustate(const struct unit_type *punit_type, const action_id act_id, const enum ustate_prop prop, const bool is_there) { fc_assert_ret_val(punit_type, FALSE); fc_assert_ret_val(act_id >= 0 && act_id < ACTION_AND_FAKES, FALSE); return BV_ISSET(ustate_act_cache[utype_index(punit_type)][act_id], requirement_unit_state_ereq(prop, is_there)); } /**********************************************************************//** Return TRUE iff units of the given type can do any enabler controlled action with the specified action result while its unit state property prop has the value is_there. Note that a specific unit in a specific situation still may be unable to perform the specified action. **************************************************************************/ bool utype_can_do_action_result_when_ustate(const struct unit_type *putype, enum action_result result, const enum ustate_prop prop, const bool is_there) { fc_assert_ret_val(putype, FALSE); action_by_result_iterate(paction, result) { if (utype_can_do_act_when_ustate(putype, action_id(paction), prop, is_there)) { return TRUE; } } action_by_result_iterate_end; return FALSE; } /**********************************************************************//** Returns TRUE iff the unit type can do the specified (action enabler controlled) action while its target's CityTile property state has the value is_there. **************************************************************************/ bool utype_can_do_act_if_tgt_citytile(const struct unit_type *punit_type, const action_id act_id, const enum citytile_type prop, const bool is_there) { fc_assert_ret_val(punit_type, FALSE); fc_assert_ret_val(act_id >= 0 && act_id < ACTION_AND_FAKES, FALSE); return BV_ISSET(ctile_tgt_act_cache[utype_index(punit_type)][act_id], requirement_citytile_ereq(prop, is_there)); } /**********************************************************************//** Return TRUE iff the given (action enabler controlled) action can be performed by a unit of the given type while the given property of its owner's diplomatic relationship to the target's owner has the given value. Note: since this only supports the local range no information for other ranges are stored in dipl_rel_action_cache. **************************************************************************/ bool can_utype_do_act_if_tgt_diplrel(const struct unit_type *punit_type, const action_id act_id, const int prop, const bool is_there) { fc_assert_ret_val(punit_type, FALSE); fc_assert_ret_val(act_id >= 0 && act_id < ACTION_AND_FAKES, FALSE); return BV_ISSET(dipl_rel_action_cache[utype_index(punit_type)][act_id], requirement_diplrel_ereq(prop, REQ_RANGE_LOCAL, is_there)); } /**********************************************************************//** Return TRUE iff the given (action enabler controlled) action can be performed by a unit of the given type while the given property of its owner's diplomatic relationship to the target tile's owner has the given value. **************************************************************************/ bool utype_can_act_if_tgt_diplrel_tile_other(const struct unit_type *punit_type, const action_id act_id, const int prop, const bool is_there) { fc_assert_ret_val(punit_type, FALSE); fc_assert_ret_val(act_id >= 0 && act_id < ACTION_AND_FAKES, FALSE); return BV_ISSET( dipl_rel_tile_other_tgt_a_cache[utype_index(punit_type)][act_id], requirement_diplrel_ereq(prop, REQ_RANGE_LOCAL, is_there)); } /**********************************************************************//** Return TRUE iff the given (action enabler controlled) action may be performed by a unit of the given type that has the given number of move fragments left. Note: Values aren't cached. If a performance critical user appears it would be a good idea to cache the (merged) ranges of move fragments where a unit of the given type can perform the specified action. **************************************************************************/ bool utype_may_act_move_frags(const struct unit_type *punit_type, const action_id act_id, const int move_fragments) { struct range *ml_range; fc_assert(action_id_exists(act_id) || act_id == ACTION_ANY); if (!utype_may_act_at_all(punit_type)) { /* Not an actor unit. */ return FALSE; } if (act_id == ACTION_ANY) { /* Any action is OK. */ action_iterate(alt_act) { if (utype_may_act_move_frags(punit_type, alt_act, move_fragments)) { /* It only has to be true for one action. */ return TRUE; } } action_iterate_end; /* No action enabled. */ return FALSE; } if (action_id_get_actor_kind(act_id) != AAK_UNIT) { /* This action isn't performed by any unit at all so this unit type * can't do it. */ return FALSE; } action_enabler_list_iterate(action_enablers_for_action(act_id), enabler) { if (!requirement_fulfilled_by_unit_type(punit_type, &(enabler->actor_reqs))) { /* This action enabler isn't for this unit type at all. */ continue; } ml_range = moves_left_range(&(enabler->actor_reqs)); if (ml_range->min <= move_fragments && (ml_range->max == MOVES_LEFT_INFINITY || ml_range->max > move_fragments)) { /* The number of move fragments is in range of the action enabler. */ free(ml_range); return TRUE; } free(ml_range); } action_enabler_list_iterate_end; return FALSE; } /**********************************************************************//** Return TRUE iff the given (action enabler controlled) action may be performed by a unit of the given type if the target tile has the given property. Note: Values aren't cached. If a performance critical user appears it would be a good idea to cache the result. **************************************************************************/ bool utype_may_act_tgt_city_tile(const struct unit_type *punit_type, const action_id act_id, const enum citytile_type prop, const bool is_there) { struct requirement req; if (!utype_may_act_at_all(punit_type)) { /* Not an actor unit. */ return FALSE; } if (act_id == ACTION_ANY) { /* Any action is OK. */ action_iterate(alt_act) { if (utype_may_act_tgt_city_tile(punit_type, alt_act, prop, is_there)) { /* It only has to be true for one action. */ return TRUE; } } action_iterate_end; /* No action enabled. */ return FALSE; } if (action_id_get_actor_kind(act_id) != AAK_UNIT) { /* This action isn't performed by any unit at all so this unit type * can't do it. */ return FALSE; } /* Common for every situation */ req.range = REQ_RANGE_TILE; req.survives = FALSE; req.source.kind = VUT_CITYTILE; /* Will only check for the specified is_there */ req.present = is_there; /* Will only check the specified property */ req.source.value.citytile = prop; action_enabler_list_iterate(action_enablers_for_action(act_id), enabler) { if (!requirement_fulfilled_by_unit_type(punit_type, &(enabler->actor_reqs))) { /* This action enabler isn't for this unit type at all. */ continue; } if (!does_req_contradicts_reqs(&req, &(enabler->target_reqs))) { /* This action isn't blocked by the given target tile property. */ return TRUE; } } action_enabler_list_iterate_end; return FALSE; } /**********************************************************************//** Returns TRUE iff performing the specified action always will consume all remaining MP of an actor unit of the specified type. @param putype the unit type performing the action @param paction the action that is performed @return if all remaining MP is guaranteed to be consumed given the above **************************************************************************/ bool utype_action_takes_all_mp(const struct unit_type *putype, struct action *paction) { return BV_ISSET(utype_act_takes_all_mp_cache[paction->id], utype_index(putype)); } /**********************************************************************//** Returns TRUE iff performing the specified action always will consume all remaining MP of an actor unit of the specified type when the specified unit state property is true *after* the action has been performed. @param putype the unit type performing the action @param paction the action that is performed @param prop the unit state property @return if all remaining MP is guaranteed to be consumed given the above **************************************************************************/ bool utype_action_takes_all_mp_if_ustate_is(const struct unit_type *putype, struct action *paction, const enum ustate_prop prop) { return BV_ISSET(utype_act_takes_all_mp_ustate_cache[paction->id][prop], utype_index(putype)); } /**********************************************************************//** Returns TRUE iff performing the specified action will consume an actor unit of the specified type. **************************************************************************/ bool utype_is_consumed_by_action(const struct action *paction, const struct unit_type *utype) { return paction->actor_consuming_always; } /**********************************************************************//** Returns TRUE iff performing an action with the specified action result will consume an actor unit of the specified type. **************************************************************************/ bool utype_is_consumed_by_action_result(enum action_result result, const struct unit_type *utype) { action_by_result_iterate(paction, result) { if (!utype_can_do_action(utype, action_id(paction))) { continue; } if (utype_is_consumed_by_action(paction, utype)) { return TRUE; } } action_by_result_iterate_end; return FALSE; } /**********************************************************************//** Returns TRUE iff successfully performing the specified action always will move the actor unit of the specified type to the target's tile. **************************************************************************/ bool utype_is_moved_to_tgt_by_action(const struct action *paction, const struct unit_type *utype) { fc_assert_ret_val(action_get_actor_kind(paction) == AAK_UNIT, FALSE); if (paction->actor_consuming_always) { return FALSE; } switch (paction->actor.is_unit.moves_actor) { case MAK_STAYS: /* Stays at the tile were it was. */ return FALSE; case MAK_REGULAR: /* A "regular" move. Does it charge the move cost of a regular move? * Update utype_pays_for_regular_move_to_tgt() if yes. */ return TRUE; case MAK_TELEPORT: /* A teleporting move. */ return TRUE; case MAK_FORCED: /* Tries a forced move under certain conditions. */ return FALSE; case MAK_ESCAPE: /* May die, may be teleported to a safe city. */ return FALSE; case MAK_UNREPRESENTABLE: /* Too complex to determine. */ return FALSE; } fc_assert_msg(FALSE, "Should not reach this code."); return FALSE; } /**********************************************************************//** Returns TRUE iff successfully performing the specified action never will move the actor unit from its current tile. **************************************************************************/ bool utype_is_unmoved_by_action(const struct action *paction, const struct unit_type *utype) { fc_assert_ret_val(action_get_actor_kind(paction) == AAK_UNIT, FALSE); if (paction->actor_consuming_always) { /* Dead counts as moved off the board */ return FALSE; } switch (paction->actor.is_unit.moves_actor) { case MAK_STAYS: /* Stays at the tile were it was. */ return TRUE; case MAK_REGULAR: /* A "regular" move. Does it charge the move cost of a regular move? * Update utype_pays_for_regular_move_to_tgt() if yes. */ return FALSE; case MAK_TELEPORT: /* A teleporting move. */ return FALSE; case MAK_FORCED: /* Tries a forced move under certain conditions. */ return FALSE; case MAK_ESCAPE: /* May die, may be teleported to a safe city. */ return FALSE; case MAK_UNREPRESENTABLE: /* Too complex to determine. */ return FALSE; } fc_assert_msg(FALSE, "Should not reach this code."); return FALSE; } /**********************************************************************//** Returns TRUE iff successfully performing the specified action always will cost the actor unit of the specified type the move fragments it would take to perform a regular move to the target's tile. This cost is added to the cost of successfully performing the action. **************************************************************************/ bool utype_pays_for_regular_move_to_tgt(const struct action *paction, const struct unit_type *utype) { if (!utype_is_moved_to_tgt_by_action(paction, utype)) { /* Not even a move. */ return FALSE; } if (action_has_result(paction, ACTRES_CONQUER_CITY)) { /* Moves into the city to occupy it. */ return TRUE; } if (action_has_result(paction, ACTRES_CONQUER_EXTRAS)) { /* Moves into the tile with the extras to capture them. */ return TRUE; } if (action_has_result(paction, ACTRES_HUT_ENTER)) { /* Moves into the tile with the hut to enter it. */ return TRUE; } if (action_has_result(paction, ACTRES_HUT_FRIGHTEN)) { /* Moves into the tile with the hut to frighten it. */ return TRUE; } if (action_has_result(paction, ACTRES_TRANSPORT_DISEMBARK)) { /* Moves out of the transport to disembark. */ return TRUE; } if (action_has_result(paction, ACTRES_TRANSPORT_EMBARK)) { /* Moves into the transport to embark. */ return TRUE; } if (action_has_result(paction, ACTRES_UNIT_MOVE)) { /* Is a regular move. */ return TRUE; } return FALSE; } /**********************************************************************//** Returns the amount of movement points successfully performing the specified action will consume in the actor unit type without taking effects or regular moves into account. **************************************************************************/ int utype_pays_mp_for_action_base(const struct action *paction, const struct unit_type *putype) { int mpco = 0; return mpco; } /**********************************************************************//** Returns an estimate of the amount of movement points successfully performing the specified action will consume in the actor unit type. **************************************************************************/ int utype_pays_mp_for_action_estimate(const struct civ_map *nmap, const struct action *paction, const struct unit_type *putype, const struct player *act_player, const struct tile *act_tile, const struct tile *tgt_tile) { const struct tile *post_action_tile; int mpco = utype_pays_mp_for_action_base(paction, putype); if (utype_is_moved_to_tgt_by_action(paction, putype)) { post_action_tile = tgt_tile; } else { /* FIXME: Not 100% true. May escape, have a probability for moving to * target tile etc. */ post_action_tile = act_tile; } if (utype_pays_for_regular_move_to_tgt(paction, putype)) { /* Add the cost from the move. */ mpco += map_move_cost(nmap, act_player, putype, act_tile, tgt_tile); } /* FIXME: Probably wrong result if the effect * EFT_ACTION_SUCCESS_MOVE_COST depends on unit state. Add unit state * parameters? */ mpco += get_target_bonus_effects(nullptr, &(const struct req_context) { .player = act_player, .city = tile_city(post_action_tile), .tile = tgt_tile, .unittype = putype, .action = paction, }, nullptr, EFT_ACTION_SUCCESS_MOVE_COST); return mpco; } /**********************************************************************//** Returns the number of shields it takes to build this unit type. If pplayer is nullptr, owner of the pcity is used instead. **************************************************************************/ int utype_build_shield_cost(const struct city *pcity, const struct player *pplayer, const struct unit_type *punittype) { int base; const struct player *owner; const struct tile *ptile; if (pcity != nullptr) { owner = city_owner(pcity); ptile = city_tile(pcity); } else { owner = nullptr; ptile = nullptr; } if (pplayer != nullptr) { /* Override city owner. */ owner = pplayer; } base = punittype->build_cost * (100 + get_unittype_bonus(owner, ptile, punittype, nullptr, EFT_UNIT_BUILD_COST_PCT)) / 100; return MAX(base * game.info.shieldbox / 100, 1); } /**********************************************************************//** Returns the number of shields this unit type represents. **************************************************************************/ int utype_build_shield_cost_base(const struct unit_type *punittype) { return MAX(punittype->build_cost * game.info.shieldbox / 100, 1); } /**********************************************************************//** Returns the number of shields it takes to build this unit. **************************************************************************/ int unit_build_shield_cost(const struct city *pcity, const struct unit *punit) { return utype_build_shield_cost(pcity, nullptr, unit_type_get(punit)); } /**********************************************************************//** Returns the number of shields this unit represents **************************************************************************/ int unit_build_shield_cost_base(const struct unit *punit) { return utype_build_shield_cost_base(unit_type_get(punit)); } /**********************************************************************//** Returns the amount of gold it takes to rush this unit. **************************************************************************/ int utype_buy_gold_cost(const struct city *pcity, const struct unit_type *punittype, int shields_in_stock) { int cost = 0; const int missing = utype_build_shield_cost(pcity, nullptr, punittype) - shields_in_stock; struct player *owner; struct tile *ptile; if (missing > 0) { cost = 2 * missing + (missing * missing) / 20; } if (shields_in_stock == 0) { cost *= 2; } if (pcity != nullptr) { owner = city_owner(pcity); ptile = city_tile(pcity); } else { owner = nullptr; ptile = nullptr; } cost = cost * (100 + get_unittype_bonus(owner, ptile, punittype, nullptr, EFT_UNIT_BUY_COST_PCT)) / 100; return cost; } /**********************************************************************//** How much city shrinks when it builds unit of this type. **************************************************************************/ int utype_pop_value(const struct unit_type *punittype, const struct city *pcity) { int pop_cost = punittype->pop_cost; pop_cost -= get_unittype_bonus(city_owner(pcity), city_tile(pcity), punittype, nullptr, EFT_POPCOST_FREE); return MAX(0, pop_cost); } /**********************************************************************//** How much population this unit contains. This can be different from what it originally cost, i.e., from what utype_pop_cost() for the unit type returns. **************************************************************************/ int unit_pop_value(const struct unit *punit) { return unit_type_get(punit)->pop_cost; } /**********************************************************************//** Return move type of the unit type **************************************************************************/ enum unit_move_type utype_move_type(const struct unit_type *punittype) { return utype_class(punittype)->move_type; } /**********************************************************************//** Return the (translated) name of the unit type. You don't have to free the return pointer. **************************************************************************/ const char *utype_name_translation(const struct unit_type *punittype) { return name_translation_get(&punittype->name); } /**********************************************************************//** Return the (translated) name of the unit. You don't have to free the return pointer. **************************************************************************/ const char *unit_name_translation(const struct unit *punit) { return utype_name_translation(unit_type_get(punit)); } /**********************************************************************//** Return the (untranslated) rule name of the unit type. You don't have to free the return pointer. **************************************************************************/ const char *utype_rule_name(const struct unit_type *punittype) { return rule_name_get(&punittype->name); } /**********************************************************************//** Return the (untranslated) rule name of the unit. You don't have to free the return pointer. **************************************************************************/ const char *unit_rule_name(const struct unit *punit) { return utype_rule_name(unit_type_get(punit)); } /**********************************************************************//** Return string describing unit type values. String is static buffer that gets reused when function is called again. **************************************************************************/ const char *utype_values_string(const struct unit_type *punittype) { static char buffer[256]; /* Print in two parts as move_points_text() returns a static buffer */ fc_snprintf(buffer, sizeof(buffer), "%d/%d/%s", punittype->attack_strength, punittype->defense_strength, move_points_text(punittype->move_rate, TRUE)); if (utype_fuel(punittype)) { cat_snprintf(buffer, sizeof(buffer), "(%s)", move_points_text(punittype->move_rate * utype_fuel(punittype), TRUE)); } return buffer; } /**********************************************************************//** Return string with translated unit name and list of its values. String is static buffer that gets reused when function is called again. **************************************************************************/ const char *utype_values_translation(const struct unit_type *punittype) { static char buffer[256]; fc_snprintf(buffer, sizeof(buffer), "%s [%s]", utype_name_translation(punittype), utype_values_string(punittype)); return buffer; } /**********************************************************************//** Return the (translated) name of the unit class. You don't have to free the return pointer. **************************************************************************/ const char *uclass_name_translation(const struct unit_class *pclass) { return name_translation_get(&pclass->name); } /**********************************************************************//** Return the (untranslated) rule name of the unit class. You don't have to free the return pointer. **************************************************************************/ const char *uclass_rule_name(const struct unit_class *pclass) { return rule_name_get(&pclass->name); } /**********************************************************************//** Return whether the unit has the class flag. **************************************************************************/ bool unit_has_class_flag(const struct unit *punit, enum unit_class_flag_id flag) { return uclass_has_flag(unit_class_get(punit), flag); } /**********************************************************************//** Return whether the unit type has the class flag. **************************************************************************/ bool utype_has_class_flag(const struct unit_type *ptype, enum unit_class_flag_id flag) { return uclass_has_flag(utype_class(ptype), flag); } /**********************************************************************//** Return a string with all the names of units with this flag. If "alts" is set, separate with "or", otherwise "and". Return FALSE if no unit with this flag exists. **************************************************************************/ bool role_units_translations(struct astring *astr, int flag, bool alts) { const int count = num_role_units(flag); if (4 < count) { if (alts) { astr_set(astr, _("%s or similar units"), utype_name_translation(get_role_unit(flag, 0))); } else { astr_set(astr, _("%s and similar units"), utype_name_translation(get_role_unit(flag, 0))); } return TRUE; } else if (0 < count) { const char *vec[count]; int i; for (i = 0; i < count; i++) { vec[i] = utype_name_translation(get_role_unit(flag, i)); } if (alts) { astr_build_or_list(astr, vec, count); } else { astr_build_and_list(astr, vec, count); } return TRUE; } return FALSE; } /**********************************************************************//** Return whether this player can upgrade this unit type (to any other unit type). Returns nullptr if no upgrade is possible. **************************************************************************/ const struct unit_type *can_upgrade_unittype(const struct player *pplayer, const struct unit_type *punittype) { const struct unit_type *upgrade = punittype; const struct unit_type *best_upgrade = nullptr; /* For some reason this used to check * can_player_build_unit_direct() for the unittype * we're updating from. * That check is now removed as it prevented legal updates * of units player had acquired via bribing, capturing, * diplomatic treaties, or lua script. */ while ((upgrade = upgrade->obsoleted_by) != U_NOT_OBSOLETED) { if (can_player_build_unit_direct(pplayer, upgrade, TRUE)) { best_upgrade = upgrade; } } return best_upgrade; } /**********************************************************************//** Return the cost (gold) of upgrading a single unit of the specified type to the new type. This price could (but currently does not) depend on other attributes (like nation or government type) of the player the unit belongs to. **************************************************************************/ int unit_upgrade_price(const struct player *pplayer, const struct unit_type *from, const struct unit_type *to) { /* Upgrade price is only paid for "Upgrade Unit" so it is safe to hard * code the action ID for now. paction will have to become a parameter * before generalized actions appears. */ const struct action *paction = action_by_number(ACTION_UPGRADE_UNIT); int missing = (utype_build_shield_cost_base(to) - unit_shield_value(nullptr, from, paction)); int base_cost = 2 * missing + (missing * missing) / 20; return base_cost * (100 + get_player_bonus(pplayer, EFT_UPGRADE_PRICE_PCT)) / 100; } /**********************************************************************//** Returns the unit type that has the given (translated) name. Returns nullptr if none match. **************************************************************************/ struct unit_type *unit_type_by_translated_name(const char *name) { unit_type_iterate(punittype) { if (0 == strcmp(utype_name_translation(punittype), name)) { return punittype; } } unit_type_iterate_end; return nullptr; } /**********************************************************************//** Returns the unit type that has the given (untranslated) rule name. Returns nullptr if none match. **************************************************************************/ struct unit_type *unit_type_by_rule_name(const char *name) { const char *qname = Qn_(name); unit_type_iterate(punittype) { if (0 == fc_strcasecmp(utype_rule_name(punittype), qname)) { return punittype; } } unit_type_iterate_end; return nullptr; } /**********************************************************************//** Returns the unit class that has the given (untranslated) rule name. Returns nullptr if none match. **************************************************************************/ struct unit_class *unit_class_by_rule_name(const char *s) { const char *qs = Qn_(s); unit_class_iterate(pclass) { if (0 == fc_strcasecmp(uclass_rule_name(pclass), qs)) { return pclass; } } unit_class_iterate_end; return nullptr; } /**********************************************************************//** Initialize user unit class flags. **************************************************************************/ void user_unit_class_flags_init(void) { int i; for (i = 0; i < MAX_NUM_USER_UCLASS_FLAGS; i++) { user_flag_init(&user_class_flags[i]); } } /**********************************************************************//** Sets user defined name for unit class flag. **************************************************************************/ void set_user_unit_class_flag_name(enum unit_class_flag_id id, const char *name, const char *helptxt) { int ufid = id - UCF_USER_FLAG_1; fc_assert_ret(id >= UCF_USER_FLAG_1 && id <= UCF_LAST_USER_FLAG); if (user_class_flags[ufid].name != nullptr) { FC_FREE(user_class_flags[ufid].name); user_class_flags[ufid].name = nullptr; } if (name && name[0] != '\0') { user_class_flags[ufid].name = fc_strdup(name); } if (user_class_flags[ufid].helptxt != nullptr) { free(user_class_flags[ufid].helptxt); user_class_flags[ufid].helptxt = nullptr; } if (helptxt && helptxt[0] != '\0') { user_class_flags[ufid].helptxt = fc_strdup(helptxt); } } /**********************************************************************//** Unit class flag name callback, called from specenum code. **************************************************************************/ const char *unit_class_flag_id_name_cb(enum unit_class_flag_id flag) { if (flag < UCF_USER_FLAG_1 || flag > UCF_LAST_USER_FLAG) { return nullptr; } return user_class_flags[flag - UCF_USER_FLAG_1].name; } /**********************************************************************//** Return the (untranslated) help text of the user unit class flag. **************************************************************************/ const char *unit_class_flag_helptxt(enum unit_class_flag_id id) { fc_assert(id >= UCF_USER_FLAG_1 && id <= UCF_LAST_USER_FLAG); return user_class_flags[id - UCF_USER_FLAG_1].helptxt; } /**********************************************************************//** Initialize user unit type flags. **************************************************************************/ void user_unit_type_flags_init(void) { int i; for (i = 0; i < MAX_NUM_USER_UNIT_FLAGS; i++) { user_flag_init(&user_type_flags[i]); } } /**********************************************************************//** Sets user defined name for unit flag. **************************************************************************/ void set_user_unit_type_flag_name(enum unit_type_flag_id id, const char *name, const char *helptxt) { int ufid = id - UTYF_USER_FLAG_1; fc_assert_ret(id >= UTYF_USER_FLAG_1 && id <= UTYF_LAST_USER_FLAG); if (user_type_flags[ufid].name != nullptr) { FC_FREE(user_type_flags[ufid].name); user_type_flags[ufid].name = nullptr; } if (name && name[0] != '\0') { user_type_flags[ufid].name = fc_strdup(name); } if (user_type_flags[ufid].helptxt != nullptr) { free(user_type_flags[ufid].helptxt); user_type_flags[ufid].helptxt = nullptr; } if (helptxt && helptxt[0] != '\0') { user_type_flags[ufid].helptxt = fc_strdup(helptxt); } } /**********************************************************************//** Unit type flag name callback, called from specenum code. **************************************************************************/ const char *unit_type_flag_id_name_cb(enum unit_type_flag_id flag) { if (flag < UTYF_USER_FLAG_1 || flag > UTYF_LAST_USER_FLAG) { return nullptr; } return user_type_flags[flag - UTYF_USER_FLAG_1].name; } /**********************************************************************//** Return the (untranslated) helptxt of the user unit flag. **************************************************************************/ const char *unit_type_flag_helptxt(enum unit_type_flag_id id) { fc_assert(id >= UTYF_USER_FLAG_1 && id <= UTYF_LAST_USER_FLAG); return user_type_flags[id - UTYF_USER_FLAG_1].helptxt; } /**********************************************************************//** Returns TRUE iff the unit type is unique and the player already has one. **************************************************************************/ bool utype_player_already_has_this_unique(const struct player *pplayer, const struct unit_type *putype) { if (!utype_has_flag(putype, UTYF_UNIQUE)) { /* This isn't a unique unit type. */ return FALSE; } return utype_player_already_has_this(pplayer, putype); } /**********************************************************************//** Returns TRUE iff the player already has a unit of this type. **************************************************************************/ bool utype_player_already_has_this(const struct player *pplayer, const struct unit_type *putype) { unit_list_iterate(pplayer->units, existing_unit) { if (putype == unit_type_get(existing_unit)) { /* FIXME: This could be slow if we have lots of units. We could * consider keeping an array of unittypes updated with this info * instead. */ return TRUE; } } unit_list_iterate_end; /* The player doesn't already have one. */ return FALSE; } /**********************************************************************//** Whether player can build given unit somewhere, ignoring whether unit is obsolete and assuming the player has a coastal city. consider_reg_impr_req affects only regular buildings that player may have in a city despite being unable to build it any more. E.g. Great Wonder built by someone else make it obvious that this player cannot build the unit, even if consider_reg_impr_req is FALSE. **************************************************************************/ bool can_player_build_unit_direct(const struct player *p, const struct unit_type *punittype, bool consider_reg_impr_req) { const struct req_context context = { .player = p, .unittype = punittype }; bool barbarian = is_barbarian(p); fc_assert_ret_val(punittype != nullptr, FALSE); if (barbarian && !utype_has_role(punittype, L_BARBARIAN_BUILD) && !utype_has_role(punittype, L_BARBARIAN_BUILD_TECH)) { /* Barbarians can build only role units */ return FALSE; } if ((utype_can_do_action_result(punittype, ACTRES_NUKE_UNITS) || utype_can_do_action_result(punittype, ACTRES_NUKE)) && get_player_bonus(p, EFT_ENABLE_NUKE) <= 0) { return FALSE; } if (utype_has_flag(punittype, UTYF_NOBUILD)) { return FALSE; } if (utype_has_flag(punittype, UTYF_BARBARIAN_ONLY) && !barbarian) { /* Unit can be built by barbarians only and this player is * not barbarian */ return FALSE; } if (utype_has_flag(punittype, UTYF_NEWCITY_GAMES_ONLY) && game.scenario.prevent_new_cities) { /* Unit is usable only in games where founding of new cities is allowed. */ return FALSE; } requirement_vector_iterate(&punittype->build_reqs, preq) { if (preq->source.kind == VUT_IMPROVEMENT && preq->range == REQ_RANGE_CITY && preq->present) { /* If the unit has a building requirement, we check to see if the * player can build that building. Note that individual cities may * not have that building, so they still may not be able to build the * unit. */ if (is_great_wonder(preq->source.value.building) && (great_wonder_is_built(preq->source.value.building) || great_wonder_is_destroyed(preq->source.value.building))) { /* It's already built great wonder */ if (great_wonder_owner(preq->source.value.building) != p) { /* Not owned by this player. Either destroyed or owned by somebody * else. */ return FALSE; } } else if (is_small_wonder(preq->source.value.building)) { if (!city_from_wonder(p, preq->source.value.building) && consider_reg_impr_req && !can_player_build_improvement_direct(p, preq->source.value.building)) { return FALSE; } } else { if (consider_reg_impr_req && !can_player_build_improvement_direct(p, preq->source.value.building)) { return FALSE; } } } if (preq->range < REQ_RANGE_PLAYER) { /* The question *here* is if the *player* can build this unit */ continue; } if (preq->source.kind == VUT_ADVANCE && barbarian) { /* Tech requirements do not apply to Barbarians building * L_BARBARIAN_BUILD units. */ if (!utype_has_role(punittype, L_BARBARIAN_BUILD)) { /* For L_BARBARIAN_BUILD_TECH the tech requirement must be met at World range * (i.e. *anyone* must know the tech) */ if (preq->range < REQ_RANGE_WORLD /* If range already World, no need to adjust */ && utype_has_role(punittype, L_BARBARIAN_BUILD_TECH)) { struct requirement copy; req_copy(&copy, preq); copy.range = REQ_RANGE_WORLD; if (!is_req_active(&context, nullptr, &copy, RPT_CERTAIN)) { return FALSE; } } else if (!is_req_active(&context, nullptr, preq, RPT_CERTAIN)) { return FALSE; } } } else if (!is_req_active(&context, nullptr, preq, RPT_CERTAIN)) { return FALSE; } } requirement_vector_iterate_end; if (utype_player_already_has_this_unique(p, punittype)) { /* A player can only have one unit of each unique unit type. */ return FALSE; } return TRUE; } /**********************************************************************//** Whether player can build given unit somewhere; returns FALSE if unit is obsolete. **************************************************************************/ bool can_player_build_unit_now(const struct player *p, const struct unit_type *punittype) { if (!can_player_build_unit_direct(p, punittype, FALSE)) { return FALSE; } while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) { if (can_player_build_unit_direct(p, punittype, TRUE)) { return FALSE; } } return TRUE; } /**********************************************************************//** Whether player can _eventually_ build given unit somewhere -- ie, returns TRUE if unit is available with current tech OR will be available with future tech. Returns FALSE if unit is obsolete. **************************************************************************/ bool can_player_build_unit_later(const struct player *p, const struct unit_type *punittype) { fc_assert_ret_val(punittype != nullptr, FALSE); if (utype_has_flag(punittype, UTYF_NOBUILD)) { return FALSE; } while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) { if (can_player_build_unit_direct(p, punittype, TRUE)) { return FALSE; } } return TRUE; } /************************************************************************** The following functions use static variables so we can quickly look up which unit types have given flag or role. For these functions flags and roles are considered to be in the same "space", and any "role" argument can also be a "flag". Unit order is in terms of the order in the units ruleset. **************************************************************************/ static bool first_init = TRUE; static int n_with_role[MAX_UNIT_ROLES]; static struct unit_type **with_role[MAX_UNIT_ROLES]; /**********************************************************************//** Do the real work for role_unit_precalcs, for one role (or flag), given by i. **************************************************************************/ static void precalc_one(int i, bool (*func_has)(const struct unit_type *, int)) { int j; /* Count: */ fc_assert(n_with_role[i] == 0); unit_type_iterate(u) { if (func_has(u, i)) { n_with_role[i]++; } } unit_type_iterate_end; if (n_with_role[i] > 0) { with_role[i] = fc_malloc(n_with_role[i] * sizeof(*with_role[i])); j = 0; unit_type_iterate(u) { if (func_has(u, i)) { with_role[i][j++] = u; } } unit_type_iterate_end; fc_assert(j == n_with_role[i]); } } /**********************************************************************//** Free memory allocated by role_unit_precalcs(). **************************************************************************/ void role_unit_precalcs_free(void) { int i; for (i = 0; i < MAX_UNIT_ROLES; i++) { free(with_role[i]); with_role[i] = nullptr; n_with_role[i] = 0; } } /**********************************************************************//** Initialize; it is safe to call this multiple times (e.g., if units have changed due to rulesets in client). **************************************************************************/ void role_unit_precalcs(void) { int i; if (first_init) { for (i = 0; i < MAX_UNIT_ROLES; i++) { with_role[i] = nullptr; n_with_role[i] = 0; } } else { role_unit_precalcs_free(); } for (i = 0; i <= UTYF_LAST_USER_FLAG; i++) { precalc_one(i, utype_has_flag); } for (i = L_FIRST; i < L_LAST; i++) { precalc_one(i, utype_has_role); } for (i = L_LAST; i < MAX_UNIT_ROLES; i++) { precalc_one(i, utype_can_do_action_role); } first_init = FALSE; } /**********************************************************************//** How many unit types have specified role/flag. **************************************************************************/ int num_role_units(int role) { fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG) || (role >= L_FIRST && role < L_LAST) || (role >= L_LAST && role < MAX_UNIT_ROLES), -1); fc_assert_ret_val(!first_init, -1); return n_with_role[role]; } /**********************************************************************//** Iterate over all the role units and feed them to callback. Once callback returns TRUE, no further units are fed to it and we return the unit that caused callback to return TRUE **************************************************************************/ struct unit_type *role_units_iterate(int role, role_unit_callback cb, void *data) { int i; for (i = 0; i < n_with_role[role]; i++) { if (cb(with_role[role][i], data)) { return with_role[role][i]; } } return nullptr; } /**********************************************************************//** Iterate over all the role units and feed them to callback, starting from the last one. Once callback returns TRUE, no further units are fed to it and we return the unit that caused callback to return TRUE **************************************************************************/ struct unit_type *role_units_iterate_backwards(int role, role_unit_callback cb, void *data) { int i; for (i = n_with_role[role] - 1; i >= 0; i--) { if (cb(with_role[role][i], data)) { return with_role[role][i]; } } return nullptr; } /**********************************************************************//** Return index-th unit with specified role/flag. Index -1 means (n-1), ie last one. **************************************************************************/ struct unit_type *get_role_unit(int role, int role_index) { fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG) || (role >= L_FIRST && role < L_LAST) || (role >= L_LAST && role < MAX_UNIT_ROLES), nullptr); fc_assert_ret_val(!first_init, nullptr); if (role_index == -1) { role_index = n_with_role[role] - 1; } fc_assert_ret_val(role_index >= 0 && role_index < n_with_role[role], nullptr); return with_role[role][role_index]; } /**********************************************************************//** Return "best" unit this city can build, with given role/flag. Returns nullptr if none match. "Best" means highest unit type id. **************************************************************************/ struct unit_type *best_role_unit(const struct city *pcity, int role) { struct unit_type *u; int j; const struct civ_map *nmap = &(wld.map); fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG) || (role >= L_FIRST && role < L_LAST) || (role >= L_LAST && role < MAX_UNIT_ROLES), nullptr); fc_assert_ret_val(!first_init, nullptr); for (j = n_with_role[role] - 1; j >= 0; j--) { u = with_role[role][j]; if (can_city_build_unit_now(nmap, pcity, u)) { return u; } } return nullptr; } /**********************************************************************//** Return "best" unit the player can build, with given role/flag. Returns nullptr if none match. "Best" means highest unit type id. TODO: Cache the result per player? **************************************************************************/ struct unit_type *best_role_unit_for_player(const struct player *pplayer, int role) { int j; fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG) || (role >= L_FIRST && role < L_LAST) || (role >= L_LAST && role < MAX_UNIT_ROLES), nullptr); fc_assert_ret_val(!first_init, nullptr); for (j = n_with_role[role] - 1; j >= 0; j--) { struct unit_type *utype = with_role[role][j]; if (can_player_build_unit_now(pplayer, utype)) { return utype; } } return nullptr; } /**********************************************************************//** Return first unit the player can build, with given role/flag. Returns nullptr if none match. Used eg when placing starting units. **************************************************************************/ struct unit_type *first_role_unit_for_player(const struct player *pplayer, int role) { int j; fc_assert_ret_val((role >= 0 && role <= UTYF_LAST_USER_FLAG) || (role >= L_FIRST && role < L_LAST) || (role >= L_LAST && role < MAX_UNIT_ROLES), nullptr); fc_assert_ret_val(!first_init, nullptr); for (j = 0; j < n_with_role[role]; j++) { struct unit_type *utype = with_role[role][j]; if (can_player_build_unit_now(pplayer, utype)) { return utype; } } return nullptr; } /**********************************************************************//** Initialize unit-type structures. **************************************************************************/ void unit_types_init(void) { int i; /* Can't use unit_type_iterate() or utype_by_number() here because * num_unit_types isn't known yet. */ for (i = 0; i < ARRAY_SIZE(unit_types); i++) { unit_types[i].item_number = i; requirement_vector_init(&(unit_types[i].build_reqs)); unit_types[i].helptext = nullptr; unit_types[i].veteran = nullptr; unit_types[i].bonuses = combat_bonus_list_new(); unit_types[i].ruledit_disabled = FALSE; unit_types[i].ruledit_dlg = nullptr; } } /**********************************************************************//** Frees the memory associated with this unit type. **************************************************************************/ static void unit_type_free(struct unit_type *punittype) { if (punittype->helptext != nullptr) { strvec_destroy(punittype->helptext); punittype->helptext = nullptr; } requirement_vector_free(&(punittype->build_reqs)); veteran_system_destroy(punittype->veteran); combat_bonus_list_iterate(punittype->bonuses, pbonus) { FC_FREE(pbonus); } combat_bonus_list_iterate_end; combat_bonus_list_destroy(punittype->bonuses); } /**********************************************************************//** Frees the memory associated with all unit types. **************************************************************************/ void unit_types_free(void) { int i; /* Can't use unit_type_iterate or utype_by_number here because * we want to free what unit_types_init() has allocated. */ for (i = 0; i < ARRAY_SIZE(unit_types); i++) { unit_type_free(unit_types + i); } } /**********************************************************************//** Frees the memory associated with all unit type flags **************************************************************************/ void unit_type_flags_free(void) { int i; for (i = 0; i < MAX_NUM_USER_UNIT_FLAGS; i++) { user_flag_free(&user_type_flags[i]); } } /**********************************************************************//** Frees the memory associated with all unit class flags **************************************************************************/ void unit_class_flags_free(void) { int i; for (i = 0; i < MAX_NUM_USER_UCLASS_FLAGS; i++) { user_flag_free(&user_class_flags[i]); } } /**********************************************************************//** Return the first item of unit_classes. **************************************************************************/ struct unit_class *unit_class_array_first(void) { if (game.control.num_unit_classes > 0) { return unit_classes; } return nullptr; } /**********************************************************************//** Return the last item of unit_classes. **************************************************************************/ const struct unit_class *unit_class_array_last(void) { if (game.control.num_unit_classes > 0) { return &unit_classes[game.control.num_unit_classes - 1]; } return nullptr; } /**********************************************************************//** Return the unit_class count. **************************************************************************/ Unit_Class_id uclass_count(void) { return game.control.num_unit_classes; } #ifndef uclass_index /**********************************************************************//** Return the unit_class index. Currently same as uclass_number(), paired with uclass_count() indicates use as an array index. **************************************************************************/ Unit_Class_id uclass_index(const struct unit_class *pclass) { fc_assert_ret_val(pclass, -1); return pclass - unit_classes; } #endif /* uclass_index */ /**********************************************************************//** Return the unit_class index. **************************************************************************/ Unit_Class_id uclass_number(const struct unit_class *pclass) { fc_assert_ret_val(pclass, -1); return pclass->item_number; } /**********************************************************************//** Returns unit class pointer for an ID value. **************************************************************************/ struct unit_class *uclass_by_number(const Unit_Class_id id) { if (id < 0 || id >= game.control.num_unit_classes) { return nullptr; } return &unit_classes[id]; } #ifndef utype_class /**********************************************************************//** Returns unit class pointer for a unit type. **************************************************************************/ struct unit_class *utype_class(const struct unit_type *punittype) { fc_assert(punittype->uclass != nullptr); return punittype->uclass; } #endif /* utype_class */ /**********************************************************************//** Returns unit class pointer for a unit. **************************************************************************/ struct unit_class *unit_class_get(const struct unit *punit) { return utype_class(unit_type_get(punit)); } /**********************************************************************//** Initialize unit_class structures. **************************************************************************/ void unit_classes_init(void) { int i; /* Can't use unit_class_iterate or uclass_by_number here because * num_unit_classes isn't known yet. */ for (i = 0; i < ARRAY_SIZE(unit_classes); i++) { unit_classes[i].item_number = i; unit_classes[i].cache.refuel_extras = nullptr; unit_classes[i].cache.native_tile_extras = nullptr; unit_classes[i].cache.native_bases = nullptr; unit_classes[i].cache.bonus_roads = nullptr; unit_classes[i].cache.hiding_extras = nullptr; unit_classes[i].cache.subset_movers = nullptr; unit_classes[i].helptext = nullptr; unit_classes[i].ruledit_disabled = FALSE; } } /**********************************************************************//** Free resources allocated for unit classes. **************************************************************************/ void unit_classes_free(void) { int i; for (i = 0; i < ARRAY_SIZE(unit_classes); i++) { if (unit_classes[i].cache.refuel_extras != nullptr) { extra_type_list_destroy(unit_classes[i].cache.refuel_extras); unit_classes[i].cache.refuel_extras = nullptr; } if (unit_classes[i].cache.native_tile_extras != nullptr) { extra_type_list_destroy(unit_classes[i].cache.native_tile_extras); unit_classes[i].cache.native_tile_extras = nullptr; } if (unit_classes[i].cache.native_bases != nullptr) { extra_type_list_destroy(unit_classes[i].cache.native_bases); unit_classes[i].cache.native_bases = nullptr; } if (unit_classes[i].cache.bonus_roads != nullptr) { extra_type_list_destroy(unit_classes[i].cache.bonus_roads); unit_classes[i].cache.bonus_roads = nullptr; } if (unit_classes[i].cache.hiding_extras != nullptr) { extra_type_list_destroy(unit_classes[i].cache.hiding_extras); unit_classes[i].cache.hiding_extras = nullptr; } if (unit_classes[i].cache.subset_movers != nullptr) { unit_class_list_destroy(unit_classes[i].cache.subset_movers); } if (unit_classes[i].helptext != nullptr) { strvec_destroy(unit_classes[i].helptext); unit_classes[i].helptext = nullptr; } } } /**********************************************************************//** Return veteran system used for this unit type. **************************************************************************/ const struct veteran_system * utype_veteran_system(const struct unit_type *punittype) { fc_assert_ret_val(punittype != nullptr, nullptr); if (punittype->veteran) { return punittype->veteran; } fc_assert_ret_val(game.veteran != nullptr, nullptr); return game.veteran; } /**********************************************************************//** Return veteran level properties of given veterancy system in given veterancy level. **************************************************************************/ const struct veteran_level * vsystem_veteran_level(const struct veteran_system *vsystem, int level) { fc_assert_ret_val(vsystem->definitions != nullptr, nullptr); fc_assert_ret_val(vsystem->levels > level, nullptr); return (vsystem->definitions + level); } /**********************************************************************//** Return veteran level properties of given unit in given veterancy level. **************************************************************************/ const struct veteran_level * utype_veteran_level(const struct unit_type *punittype, int level) { const struct veteran_system *vsystem = utype_veteran_system(punittype); fc_assert_ret_val(vsystem != nullptr, nullptr); return vsystem_veteran_level(vsystem, level); } /**********************************************************************//** Return translated name of the given veteran level. nullptr if this unit type doesn't have different veteran levels. **************************************************************************/ const char *utype_veteran_name_translation(const struct unit_type *punittype, int level) { if (utype_veteran_levels(punittype) <= 1) { return nullptr; } else { const struct veteran_level *vlvl = utype_veteran_level(punittype, level); return name_translation_get(&vlvl->name); } } /**********************************************************************//** Return veteran levels of the given unit type. **************************************************************************/ int utype_veteran_levels(const struct unit_type *punittype) { const struct veteran_system *vsystem = utype_veteran_system(punittype); fc_assert_ret_val(vsystem != nullptr, 1); return vsystem->levels; } /**********************************************************************//** Return whether this unit type's veteran system, if any, confers a power factor bonus at any level (it could just add extra moves). **************************************************************************/ bool utype_veteran_has_power_bonus(const struct unit_type *punittype) { int i, initial_power_fact = utype_veteran_level(punittype, 0)->power_fact; for (i = 1; i < utype_veteran_levels(punittype); i++) { if (utype_veteran_level(punittype, i)->power_fact > initial_power_fact) { return TRUE; } } return FALSE; } /**********************************************************************//** Allocate new veteran system structure with given veteran level count. **************************************************************************/ struct veteran_system *veteran_system_new(int count) { struct veteran_system *vsystem; /* There must be at least one level. */ fc_assert_ret_val(count > 0, nullptr); vsystem = fc_calloc(1, sizeof(*vsystem)); vsystem->levels = count; vsystem->definitions = fc_calloc(vsystem->levels, sizeof(*vsystem->definitions)); return vsystem; } /**********************************************************************//** Free veteran system **************************************************************************/ void veteran_system_destroy(struct veteran_system *vsystem) { if (vsystem) { if (vsystem->definitions) { free(vsystem->definitions); } free(vsystem); } } /**********************************************************************//** Fill veteran level in given veteran system with given information. **************************************************************************/ void veteran_system_definition(struct veteran_system *vsystem, int level, const char *vlist_name, int vlist_power, int vlist_move, int vlist_raise, int vlist_wraise) { struct veteran_level *vlevel; fc_assert_ret(vsystem != nullptr); fc_assert_ret(vsystem->levels > level); vlevel = vsystem->definitions + level; names_set(&vlevel->name, nullptr, vlist_name, nullptr); vlevel->power_fact = vlist_power; vlevel->move_bonus = vlist_move; vlevel->base_raise_chance = vlist_raise; vlevel->work_raise_chance = vlist_wraise; } /**********************************************************************//** Return primary tech requirement for the unit type. Avoid using this, and support full list of requirements instead. Returns pointer to A_NONE if there's no requirements for the unit type. **************************************************************************/ struct advance *utype_primary_tech_req(const struct unit_type *ptype) { unit_tech_reqs_iterate(ptype, padv) { /* Return the very first! */ return padv; } unit_tech_reqs_iterate_end; /* There was no tech requirements */ return advance_by_number(A_NONE); } /**********************************************************************//** Tell if the given tech is one of unit's tech requirements **************************************************************************/ bool is_tech_req_for_utype(const struct unit_type *ptype, struct advance *padv) { unit_tech_reqs_iterate(ptype, preq) { if (padv == preq) { return TRUE; } } unit_tech_reqs_iterate_end; return FALSE; } /**********************************************************************//** Return pointer to ai data of given unit type and ai type. **************************************************************************/ void *utype_ai_data(const struct unit_type *ptype, const struct ai_type *ai) { return ptype->ais[ai_type_number(ai)]; } /**********************************************************************//** Attach ai data to unit type **************************************************************************/ void utype_set_ai_data(struct unit_type *ptype, const struct ai_type *ai, void *data) { ptype->ais[ai_type_number(ai)] = data; } /**********************************************************************//** Set caches for unit class. **************************************************************************/ void set_unit_class_caches(struct unit_class *pclass) { pclass->cache.refuel_extras = extra_type_list_new(); pclass->cache.native_tile_extras = extra_type_list_new(); pclass->cache.native_bases = extra_type_list_new(); pclass->cache.bonus_roads = extra_type_list_new(); pclass->cache.hiding_extras = extra_type_list_new(); pclass->cache.subset_movers = unit_class_list_new(); extra_type_iterate(pextra) { if (is_native_extra_to_uclass(pextra, pclass)) { struct road_type *proad = extra_road_get(pextra); if (extra_has_flag(pextra, EF_REFUEL)) { extra_type_list_append(pclass->cache.refuel_extras, pextra); } if (extra_has_flag(pextra, EF_NATIVE_TILE)) { extra_type_list_append(pclass->cache.native_tile_extras, pextra); } if (is_extra_caused_by(pextra, EC_BASE)) { extra_type_list_append(pclass->cache.native_bases, pextra); } if (proad != nullptr && road_provides_move_bonus(proad)) { extra_type_list_append(pclass->cache.bonus_roads, pextra); } if (pextra->eus == EUS_HIDDEN) { extra_type_list_append(pclass->cache.hiding_extras, pextra); } } } extra_type_iterate_end; unit_class_iterate(pcharge) { bool subset_mover = TRUE; terrain_type_iterate(pterrain) { if (BV_ISSET(pterrain->native_to, uclass_index(pcharge)) && !BV_ISSET(pterrain->native_to, uclass_index(pclass))) { subset_mover = FALSE; } } terrain_type_iterate_end; if (subset_mover) { extra_type_iterate(pextra) { if (is_native_extra_to_uclass(pextra, pcharge) && !is_native_extra_to_uclass(pextra, pclass)) { subset_mover = FALSE; } } extra_type_list_iterate_end; } if (subset_mover) { unit_class_list_append(pclass->cache.subset_movers, pcharge); } } unit_class_iterate_end; } /**********************************************************************//** Set caches for unit types. **************************************************************************/ void set_unit_type_caches(struct unit_type *ptype) { ptype->cache.max_defense_mp_bonus_pct = -FC_INFINITY; unit_type_iterate(utype) { int idx = utype_index(utype); int bonus = combat_bonus_against( ptype->bonuses, utype, CBONUS_DEFENSE_MULTIPLIER_PCT) + 100 * combat_bonus_against(ptype->bonuses, utype, CBONUS_DEFENSE_MULTIPLIER); int scramble_bonus = combat_bonus_against(ptype->bonuses, utype, CBONUS_SCRAMBLES_PCT); ptype->cache.defense_mp_bonuses_pct[idx] = bonus; /* max value is for city defenders, so it considers scrambling */ /* FIXME: if the unit's fuel != 1, scrambling is not so useful */ if (scramble_bonus) { /* Guess about city defense effect value */ struct universal u = { .kind = VUT_UTYPE, .value = {.utype = utype} }; int emax = effect_cumulative_max(EFT_DEFEND_BONUS, &u, 1); emax = CLIP(0, emax, 300); /* Likely sth wrong if more */ emax -= emax >> 2; /* Might be no such building yet */ bonus = (ptype->cache.scramble_coeff[idx] = (bonus + 100) * (scramble_bonus + 100) ) / (100 + emax) - 100; bonus = MAX(bonus, 1); /* to look better in assess_danger() */ } else { ptype->cache.scramble_coeff[idx] = 0; } if (bonus > ptype->cache.max_defense_mp_bonus_pct) { ptype->cache.max_defense_mp_bonus_pct = bonus; } } unit_type_iterate_end; } /**********************************************************************//** What move types nativity of this extra will give? **************************************************************************/ static enum unit_move_type move_type_from_extra(struct extra_type *pextra, struct unit_class *puc) { bool land_allowed = TRUE; bool sea_allowed = TRUE; if (!extra_has_flag(pextra, EF_NATIVE_TILE)) { return unit_move_type_invalid(); } if (!is_native_extra_to_uclass(pextra, puc)) { return unit_move_type_invalid(); } if (is_extra_caused_by(pextra, EC_ROAD) && road_has_flag(extra_road_get(pextra), RF_RIVER)) { /* Natural rivers are created to land only */ sea_allowed = FALSE; } requirement_vector_iterate(&pextra->reqs, preq) { if (preq->source.kind == VUT_TERRAINCLASS) { if (!preq->present) { if (preq->source.value.terrainclass == TC_LAND) { land_allowed = FALSE; } else if (preq->source.value.terrainclass == TC_OCEAN) { sea_allowed = FALSE; } } else { if (preq->source.value.terrainclass == TC_LAND) { sea_allowed = FALSE; } else if (preq->source.value.terrainclass == TC_OCEAN) { land_allowed = FALSE; } } } else if (preq->source.kind == VUT_TERRAIN) { if (!preq->present) { if (preq->source.value.terrain->tclass == TC_LAND) { land_allowed = FALSE; } else if (preq->source.value.terrain->tclass == TC_OCEAN) { sea_allowed = FALSE; } } else { if (preq->source.value.terrain->tclass == TC_LAND) { sea_allowed = FALSE; } else if (preq->source.value.terrain->tclass == TC_OCEAN) { land_allowed = FALSE; } } } } requirement_vector_iterate_end; if (land_allowed && sea_allowed) { return UMT_BOTH; } if (land_allowed && !sea_allowed) { return UMT_LAND; } if (!land_allowed && sea_allowed) { return UMT_SEA; } return unit_move_type_invalid(); } /**********************************************************************//** Set move_type for unit class. **************************************************************************/ void set_unit_move_type(struct unit_class *puclass) { bool land_moving = FALSE; bool sea_moving = FALSE; extra_type_iterate(pextra) { enum unit_move_type eut = move_type_from_extra(pextra, puclass); if (eut == UMT_BOTH) { land_moving = TRUE; sea_moving = TRUE; } else if (eut == UMT_LAND) { land_moving = TRUE; } else if (eut == UMT_SEA) { sea_moving = TRUE; } } extra_type_iterate_end; terrain_type_iterate(pterrain) { if (is_native_to_class(puclass, pterrain, nullptr)) { if (is_ocean(pterrain)) { sea_moving = TRUE; } else { land_moving = TRUE; } } } terrain_type_iterate_end; if (land_moving && sea_moving) { puclass->move_type = UMT_BOTH; } else if (sea_moving) { puclass->move_type = UMT_SEA; } else { /* If unit has no native terrains, it is considered land moving */ puclass->move_type = UMT_LAND; } } /**********************************************************************//** Is cityfounder type **************************************************************************/ bool utype_is_cityfounder(const struct unit_type *utype) { if (game.scenario.prevent_new_cities) { /* No unit is allowed to found new cities */ return FALSE; } return utype_can_do_action_result(utype, ACTRES_FOUND_CITY); } /**********************************************************************//** Returns TRUE iff the specified unit class flag is in use by any unit class. @param ucflag the unit class flag to check if is in use. @returns TRUE if the unit class flag is used in the current ruleset. **************************************************************************/ bool uclass_flag_is_in_use(enum unit_class_flag_id ucflag) { unit_class_iterate(uclass) { if (uclass_has_flag(uclass, ucflag)) { /* Found a user. */ return TRUE; } } unit_class_iterate_end; /* No users detected. */ return FALSE; } /**********************************************************************//** Returns TRUE iff the specified unit type flag is in use by any unit type. @param uflag the unit type flag to check if is in use. @returns TRUE if the unit type flag is used in the current ruleset. **************************************************************************/ bool utype_flag_is_in_use(enum unit_type_flag_id uflag) { unit_type_iterate(putype) { if (utype_has_flag(putype, uflag)) { /* Found a user. */ return TRUE; } } unit_type_iterate_end; /* No users detected. */ return FALSE; } /**********************************************************************//** Specenum callback to update old enum names to current ones. **************************************************************************/ const char *unit_type_flag_id_name_update_cb(const char *old_name) { if (is_ruleset_compat_mode()) { } return old_name; }
412
0.924382
1
0.924382
game-dev
MEDIA
0.242803
game-dev
0.937965
1
0.937965
CocoaMSX/CocoaMSX
9,619
Controllers/CMConfigureJoystickController.m
/***************************************************************************** ** ** CocoaMSX: MSX Emulator for Mac OS X ** http://www.cocoamsx.com ** Copyright (C) 2012-2016 Akop Karapetyan ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ****************************************************************************** */ #import "CMConfigureJoystickController.h" #import "CMGamepadConfiguration.h" #import "CMJoyCaptureView.h" #import "CMKeyCaptureView.h" static NSArray<NSString *> *_labels; @implementation CMConfigureJoystickController { NSInteger _gamepadId; CMGamepadConfiguration *_configuration; CMJoyCaptureView *_joyCaptureView; CMKeyCaptureView *_keyCaptureView; } + (void) initialize { _labels = @[ NSLocalizedString(@"Up", @"MSX Joystick direction"), NSLocalizedString(@"Down", @"MSX Joystick direction"), NSLocalizedString(@"Left", @"MSX Joystick direction"), NSLocalizedString(@"Right", @"MSX Joystick direction"), NSLocalizedString(@"Button 1", @"MSX Joystick button"), NSLocalizedString(@"Button 2", @"MSX Joystick button") ]; } - (instancetype) init { if ((self = [super initWithWindowNibName:@"ConfigureJoystick"])) { } return self; } #pragma mark - NSWindowDelegate - (void) windowDidLoad { } - (void) windowDidBecomeKey:(NSNotification *) notification { [[CMGamepadManager sharedInstance] addObserver:self]; [[CMKeyboardManager sharedInstance] addObserver:self]; } - (void) windowDidResignKey:(NSNotification *) notification { [[CMGamepadManager sharedInstance] removeObserver:self]; [[CMKeyboardManager sharedInstance] removeObserver:self]; } - (id) windowWillReturnFieldEditor:(NSWindow *) sender toObject:(id) anObject { if (_gamepadId == 0 || _gamepadId == 1) { if (!_keyCaptureView) { _keyCaptureView = [[CMKeyCaptureView alloc] init]; } return _keyCaptureView; } else { if (!_joyCaptureView) { _joyCaptureView = [[CMJoyCaptureView alloc] init]; } return _joyCaptureView; } } #pragma mark - NSTableViewDataSource - (NSInteger) numberOfRowsInTableView:(NSTableView *) tableView { return [_labels count]; } - (id) tableView:(NSTableView *) tableView objectValueForTableColumn:(NSTableColumn *) tableColumn row:(NSInteger) row { if ([[tableColumn identifier] isEqualToString:@"virtual"]) { return [_labels objectAtIndex:row]; } else if ([[tableColumn identifier] isEqualToString:@"physical"]) { if (_gamepadId == 0 || _gamepadId == 1) { switch (row) { case 0: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration up])]; case 1: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration down])]; case 2: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration left])]; case 3: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration right])]; case 4: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration buttonA])]; case 5: return [CMKeyCaptureView descriptionForKeyCode:CMKeyCode([_configuration buttonB])]; } } else { switch (row) { case 0: return [CMJoyCaptureView descriptionForCode:[_configuration up]]; case 1: return [CMJoyCaptureView descriptionForCode:[_configuration down]]; case 2: return [CMJoyCaptureView descriptionForCode:[_configuration left]]; case 3: return [CMJoyCaptureView descriptionForCode:[_configuration right]]; case 4: return [CMJoyCaptureView descriptionForCode:[_configuration buttonA]]; case 5: return [CMJoyCaptureView descriptionForCode:[_configuration buttonB]]; } } } return nil; } - (void) tableView:(NSTableView *) tableView setObjectValue:(id) object forTableColumn:(NSTableColumn *) tableColumn row:(NSInteger) row { if ([[tableColumn identifier] isEqualToString:@"physical"]) { if (_gamepadId == 0 || _gamepadId == 1) { NSInteger keyCode = [CMKeyCaptureView keyCodeForDescription:(NSString *) object]; switch (row) { case 0: [_configuration setUp:CMMakeKey(keyCode)]; break; case 1: [_configuration setDown:CMMakeKey(keyCode)]; break; case 2: [_configuration setLeft:CMMakeKey(keyCode)]; break; case 3: [_configuration setRight:CMMakeKey(keyCode)]; break; case 4: [_configuration setButtonA:CMMakeKey(keyCode)]; break; case 5: [_configuration setButtonB:CMMakeKey(keyCode)]; break; } } else { NSNumber *code = [CMJoyCaptureView codeForDescription:(NSString *) object]; switch (row) { case 0: [_configuration setUp:[code integerValue]]; break; case 1: [_configuration setDown:[code integerValue]]; break; case 2: [_configuration setLeft:[code integerValue]]; break; case 3: [_configuration setRight:[code integerValue]]; break; case 4: [_configuration setButtonA:[code integerValue]]; break; case 5: [_configuration setButtonB:[code integerValue]]; break; } } } } #pragma mark - CMGamepadDelegate - (void) gamepadDidDisconnect:(CMGamepad *) gamepad { if ([gamepad gamepadId] == _gamepadId) { [[self window] close]; } } - (void) gamepad:(CMGamepad *) gamepad xChanged:(NSInteger) newValue center:(NSInteger) center eventData:(CMGamepadEventData *) eventData { if ([gamepad gamepadId] == _gamepadId) { if ([[self window] firstResponder] == _joyCaptureView) { if (newValue < center) { [_joyCaptureView captureCode:CMMakeAnalog(CM_DIR_LEFT)]; } else if (newValue > center) { [_joyCaptureView captureCode:CMMakeAnalog(CM_DIR_RIGHT)]; } } } } - (void) gamepad:(CMGamepad *) gamepad yChanged:(NSInteger) newValue center:(NSInteger) center eventData:(CMGamepadEventData *) eventData { if ([gamepad gamepadId] == _gamepadId) { if ([[self window] firstResponder] == _joyCaptureView) { if (newValue < center) { [_joyCaptureView captureCode:CMMakeAnalog(CM_DIR_UP)]; } else if (newValue > center) { [_joyCaptureView captureCode:CMMakeAnalog(CM_DIR_DOWN)]; } } } } - (void) gamepad:(CMGamepad *) gamepad buttonDown:(NSInteger) index eventData:(CMGamepadEventData *) eventData { if ([gamepad gamepadId] == _gamepadId) { if ([[self window] firstResponder] == _joyCaptureView) { [_joyCaptureView captureCode:CMMakeButton(index)]; } } } #pragma mark - CMKeyboardEventDelegate - (void) keyStateChanged:(CMKeyEventData *) event isDown:(BOOL) isDown { if ((_gamepadId == 0 || _gamepadId == 1) && [event hasKeyCodeEquivalent]) { // Key with a valid keyCode if ([[self window] firstResponder] == _keyCaptureView) { // keyCaptureView is in focus BOOL isReturn = [event keyCode] == 0x24 || [event keyCode] == 0x4c; if (isReturn || !isDown) { // A key was released while the keyCaptureView has focus [_keyCaptureView captureKeyCode:[event keyCode]]; } } } } #pragma mark - Public - (void) configureGamepadId:(NSInteger) gamepadId existingConfiguration:(CMGamepadConfiguration *) existing { _gamepadId = gamepadId; CMGamepad *gamepad = nil; if (_gamepadId != 0 && gamepadId != 1) { gamepad = [[CMGamepadManager sharedInstance] gamepadWithId:_gamepadId]; } if (existing) { _configuration = [existing copy]; } else { _configuration = [[CMGamepadConfiguration alloc] init]; if (_gamepadId == 0) { [_configuration setVendorProductId:CM_VENDOR_PRODUCT_KEYBOARD_PLAYER_1]; [_configuration reset]; } else if (_gamepadId == 1) { [_configuration setVendorProductId:CM_VENDOR_PRODUCT_KEYBOARD_PLAYER_2]; [_configuration reset]; } else { [_configuration setVendorProductId:[gamepad vendorProductId]]; [_configuration reset]; } } NSString *title = nil; NSString *info = nil; if (_gamepadId == 0) { title = NSLocalizedString(@"Keyboard Player 1", @"Configuration window title"); info = NSLocalizedString(@"Currently editing input for Player 1 via Keyboard", @"Joystick config directions"); } else if (_gamepadId == 1) { title = NSLocalizedString(@"Keyboard Player 2", @"Configuration window title"); info = NSLocalizedString(@"Currently editing input for Player 2 via Keyboard", @"Joystick config directions"); } else { if (!(title = [gamepad name])) { title = NSLocalizedString(@"Generic Controller", @"Configuration window title"); } info = [NSString stringWithFormat:NSLocalizedString(@"Currently editing input via %@", @"Joystick config directions"), title]; } [[self window] setTitle:title]; [infoLabel setStringValue:info]; [tableView reloadData]; } #pragma mark - Actions - (void) cancelChanges:(id) sender { [[self window] close]; } - (void) saveChanges:(id) sender { [_delegate gamepadConfigurationDidComplete:_configuration]; [[self window] close]; } - (void) resetToDefault:(id) sender { [_configuration reset]; [tableView reloadData]; } @end
412
0.877552
1
0.877552
game-dev
MEDIA
0.402795
game-dev
0.878908
1
0.878908
hashmismatch/finny.rs
46,618
finny_derive/src/codegen.rs
use std::collections::HashSet; use proc_macro2::{Span, TokenStream}; use quote::{TokenStreamExt, quote}; use crate::{codegen_meta::generate_fsm_meta, fsm::FsmTypes, parse::{FsmState, FsmStateAction, FsmStateKind}, utils::{remap_closure_inputs, to_field_name, tokens_to_string}}; use crate::{parse::{FsmFnInput, FsmStateTransition, FsmTransitionState, FsmTransitionType}, utils::ty_append}; pub fn generate_fsm_code(fsm: &FsmFnInput, _attr: TokenStream, _input: TokenStream) -> syn::Result<TokenStream> { let fsm_ty = &fsm.base.fsm_ty; let fsm_types = FsmTypes::new(&fsm.base.fsm_ty, &fsm.base.fsm_generics); //let fsm_mod = to_field_name(&ty_append(fsm_ty, "Finny"))?; let ctx_ty = &fsm.base.context_ty; let states_store_ty = ty_append(&fsm.base.fsm_ty, "States"); let states_enum_ty = ty_append(&fsm.base.fsm_ty, "CurrentState"); let timers_enum_ty = fsm_types.get_fsm_timers_ty(); let timers_enum_iter_ty = fsm_types.get_fsm_timers_iter_ty(); let timers_storage_ty = fsm_types.get_fsm_timers_storage_ty(); let event_enum_ty = fsm_types.get_fsm_events_ty(); let region_count = fsm.fsm.regions.len(); let (fsm_generics_impl, fsm_generics_type, fsm_generics_where) = fsm.base.fsm_generics.split_for_impl(); let states_store = { let mut code_fields = TokenStream::new(); let mut new_state_fields = TokenStream::new(); let mut state_variants = TokenStream::new(); let mut state_accessors = TokenStream::new(); for (i, (_, state)) in fsm.fsm.states.iter().enumerate() { let name = &state.state_storage_field; let state_ty = FsmTypes::new(&state.ty, &fsm.base.fsm_generics); let ty = state_ty.get_fsm_ty(); let ty_name = state_ty.get_fsm_no_generics_ty(); for timer in &state.timers { let timer_ty = timer.get_ty(&fsm.base); let timer_field = timer.get_field(&fsm.base); code_fields.append_all(quote! { #timer_field: #timer_ty #fsm_generics_type, }); new_state_fields.append_all(quote! { #timer_field: #timer_ty::default(), }); state_accessors.append_all(quote! { impl #fsm_generics_impl core::convert::AsRef<#timer_ty #fsm_generics_type> for #states_store_ty #fsm_generics_type #fsm_generics_where { fn as_ref(&self) -> & #timer_ty #fsm_generics_type { &self. #timer_field } } impl #fsm_generics_impl core::convert::AsMut<#timer_ty #fsm_generics_type> for #states_store_ty #fsm_generics_type #fsm_generics_where { fn as_mut(&mut self) -> &mut #timer_ty #fsm_generics_type { &mut self. #timer_field } } }); } code_fields.append_all(quote! { #name: #ty, }); state_variants.append_all(quote!{ #ty_name, }); let new_state_field = match state.kind { FsmStateKind::Normal => { quote! { #name: < #ty as finny::FsmStateFactory< #fsm_ty #fsm_generics_type > >::new_state(context)?, } } FsmStateKind::SubMachine(ref sub) => { let ctx_codegen = match &sub.context_constructor { Some(c) => { let remap = remap_closure_inputs(&c.inputs, &[quote!{ context }])?; let body = &c.body; quote! { #remap { #body } } }, None => { quote! { Default::default() } } }; quote! { #name: { use finny::{FsmFactory}; let sub_ctx = { #ctx_codegen }; let fsm_backend = finny::FsmBackendImpl::<#ty>::new(sub_ctx)?; let fsm = <#ty>::new_submachine_backend(fsm_backend)?; fsm }, } } }; new_state_fields.append_all(new_state_field); state_accessors.append_all(quote! { impl #fsm_generics_impl core::convert::AsRef<#ty> for #states_store_ty #fsm_generics_type #fsm_generics_where { fn as_ref(&self) -> & #ty { &self. #name } } impl #fsm_generics_impl core::convert::AsMut<#ty> for #states_store_ty #fsm_generics_type #fsm_generics_where { fn as_mut(&mut self) -> &mut #ty { &mut self. #name } } }); } let mut transition_states = TokenStream::new(); let mut transitions_seen = HashSet::new(); for region in &fsm.fsm.regions { for transition in &region.transitions { match transition.ty { FsmTransitionType::StateTransition(ref s) => { match (s.state_from.get_fsm_state(), s.state_to.get_fsm_state()) { (Ok(state_from), Ok(state_to)) => { let state_from_ty = &state_from.ty; let state_to_ty = &state_to.ty; let state_from_field = &state_from.state_storage_field; let state_to_field = &state_to.state_storage_field; let key = (state_from_ty.clone(), state_to_ty.clone()); if transitions_seen.contains(&key) { continue; } transitions_seen.insert(key); transition_states.append_all(quote! { impl #fsm_generics_impl finny::FsmStateTransitionAsMut<#state_from_ty, #state_to_ty> for #states_store_ty #fsm_generics_type #fsm_generics_where { fn as_state_transition_mut(&mut self) -> (&mut #state_from_ty, &mut #state_to_ty) { (&mut self. #state_from_field, &mut self. #state_to_field) } } }); }, _ => () } }, _ => () } } } quote! { /// States storage struct for the state machine. pub struct #states_store_ty #fsm_generics_type #fsm_generics_where { #code_fields _fsm: core::marker::PhantomData< #fsm_ty #fsm_generics_type > } impl #fsm_generics_impl finny::FsmStateFactory< #fsm_ty #fsm_generics_type > for #states_store_ty #fsm_generics_type #fsm_generics_where { fn new_state(context: & #ctx_ty ) -> finny::FsmResult<Self> { let s = Self { #new_state_fields _fsm: core::marker::PhantomData::default() }; Ok(s) } } #[derive(Copy, Clone, Debug, PartialEq)] pub enum #states_enum_ty { #state_variants } impl #fsm_generics_impl finny::FsmStates< #fsm_ty #fsm_generics_type > for #states_store_ty #fsm_generics_type #fsm_generics_where { type StateKind = #states_enum_ty; type CurrentState = [finny::FsmCurrentState<Self::StateKind>; #region_count]; } #state_accessors #transition_states } }; let events_enum = { let submachines: Vec<_> = fsm.fsm.states.iter().filter_map(|(_, state)| { match &state.kind { FsmStateKind::Normal => None, FsmStateKind::SubMachine(ref sub) => { Some((sub, state)) } } }).collect(); let mut variants = TokenStream::new(); let mut as_ref_str = TokenStream::new(); let mut i = 0; for (ty, _ev) in fsm.fsm.events.iter() { let ty_str = crate::utils::tokens_to_string(ty); variants.append_all(quote! { #ty ( #ty ), }); as_ref_str.append_all(quote! { #event_enum_ty:: #ty(_) => #ty_str, }); i += 1; } for (_sub, state) in submachines { let sub_fsm = FsmTypes::new(&state.ty, &fsm.base.fsm_generics); let sub_fsm_event_ty = sub_fsm.get_fsm_events_ty(); let sub_fsm_ty = sub_fsm.get_fsm_no_generics_ty(); let sub_fsm_event_ty_str = crate::utils::tokens_to_string(&sub_fsm_event_ty); variants.append_all(quote! { #sub_fsm_ty ( #sub_fsm_event_ty ), }); as_ref_str.append_all(quote! { #event_enum_ty :: #sub_fsm_ty(_) => #sub_fsm_event_ty_str , }); i += 1; } let mut derives = TokenStream::new(); if fsm.fsm.codegen_options.event_debug { derives.append_all(quote! { #[derive(Debug)] }); } let as_ref_str = match i { 0 => { quote! { stringify!(#event_enum_ty) } }, _ => { quote! { match self { #as_ref_str } } } }; let evs = quote! { #[derive(finny::bundled::derive_more::From)] #[derive(Clone)] #derives pub enum #event_enum_ty { #variants } impl core::convert::AsRef<str> for #event_enum_ty { fn as_ref(&self) -> &'static str { #as_ref_str } } }; evs }; let transition_types = { let mut t = TokenStream::new(); for region in &fsm.fsm.regions { for transition in &region.transitions { let ty = &transition.transition_ty; let mut transition_doc = String::new(); let mut q = TokenStream::new(); match &transition.ty { // internal or self transtion (only the current state) FsmTransitionType::InternalTransition(s) | FsmTransitionType::SelfTransition(s) => { let state = s.state.get_fsm_state()?; let event_ty = &s.event.get_event()?.ty; let is_self_transition = if let FsmTransitionType::SelfTransition(_) = &transition.ty { true } else { false }; transition_doc.push_str(&format!(" {} transition within state [{}], responds to the event [{}].", if is_self_transition { "A self" } else {"An internal"}, tokens_to_string(&state.ty), tokens_to_string(event_ty) )); if let Some(ref guard) = s.action.guard { let remap = remap_closure_inputs(&guard.inputs, vec![ quote! { event }, quote! { context }, quote! { states } ].as_slice())?; let body = &guard.body; transition_doc.push_str(" Guarded."); let g = quote! { impl #fsm_generics_impl finny::FsmTransitionGuard<#fsm_ty #fsm_generics_type, #event_ty> for #ty #fsm_generics_where { fn guard<'fsm_event, Q>(event: & #event_ty, context: &finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q>, states: & #states_store_ty #fsm_generics_type ) -> bool where Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type> { #remap let result = { #body }; result } } }; q.append_all(g); } let action_body = if let Some(ref action) = s.action.action { let remap = remap_closure_inputs(&action.inputs, vec![ quote! { event }, quote! { context }, quote! { state } ].as_slice())?; transition_doc.push_str(" Executes an action."); let body = &action.body; quote! { #remap { #body } } } else { TokenStream::new() }; let state_ty = &state.ty; q.append_all(quote! { impl #fsm_generics_impl finny::FsmAction<#fsm_ty #fsm_generics_type, #event_ty, #state_ty > for #ty #fsm_generics_where { fn action<'fsm_event, Q>(event: & #event_ty , context: &mut finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q >, state: &mut #state_ty) where Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type> { #action_body } fn should_trigger_state_actions() -> bool { #is_self_transition } } }); }, // fsm start transition FsmTransitionType::StateTransition(s @ FsmStateTransition { state_from: FsmTransitionState::None, .. }) => { let initial_state_ty = &s.state_to.get_fsm_state()?.ty; transition_doc.push_str(" Start transition."); q.append_all(quote! { impl #fsm_generics_impl finny::FsmTransitionFsmStart<#fsm_ty #fsm_generics_type, #initial_state_ty > for #ty #fsm_generics_where { } }); }, // normal state transition FsmTransitionType::StateTransition(s) => { let event_ty = &s.event.get_event()?.ty; let state_from = s.state_from.get_fsm_state()?; let state_to = s.state_to.get_fsm_state()?; transition_doc.push_str(&format!(" Transition, from state [{}] to state [{}] upon the event [{}].", tokens_to_string(&state_from.ty), tokens_to_string(&state_to.ty), tokens_to_string(&event_ty) )); if let Some(ref guard) = s.action.guard { let event_ty = &s.event.get_event()?.ty; transition_doc.push_str(" Guarded."); let remap = remap_closure_inputs(&guard.inputs, vec![ quote! { event }, quote! { context }, quote! { states } ].as_slice())?; let body = &guard.body; let g = quote! { impl #fsm_generics_impl finny::FsmTransitionGuard<#fsm_ty #fsm_generics_type, #event_ty> for #ty #fsm_generics_where { fn guard<'fsm_event, Q>(event: & #event_ty, context: &finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q>, states: & #states_store_ty #fsm_generics_type) -> bool where Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type> { #remap let result = { #body }; result } } }; q.append_all(g); } let action_body = if let Some(ref action) = s.action.action { transition_doc.push_str(" Executes an action."); let remap = remap_closure_inputs(&action.inputs, vec![ quote! { event }, quote! { context }, quote! { from }, quote! { to } ].as_slice())?; let body = &action.body; quote! { #remap { #body } } } else { TokenStream::new() }; let state_from_ty = &state_from.ty; let state_to_ty = &state_to.ty; let a = quote! { impl #fsm_generics_impl finny::FsmTransitionAction<#fsm_ty #fsm_generics_type, #event_ty, #state_from_ty, #state_to_ty> for #ty #fsm_generics_where { fn action<'fsm_event, Q>(event: & #event_ty , context: &mut finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q >, from: &mut #state_from_ty, to: &mut #state_to_ty) where Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type> { #action_body } } }; q.append_all(a); } } transition_doc.push_str(&format!(" Part of [{}].", tokens_to_string(fsm_ty))); q.append_all(quote! { #[doc = #transition_doc ] pub struct #ty; }); t.append_all(q); } } t }; let dispatch = { let mut regions = TokenStream::new(); for region in &fsm.fsm.regions { let mut region_transitions = TokenStream::new(); let region_id = region.region_id; for transition in &region.transitions { let transition_ty = &transition.transition_ty; let match_state = { let state_from = match &transition.ty { FsmTransitionType::InternalTransition(s) | FsmTransitionType::SelfTransition(s) => { &s.state } FsmTransitionType::StateTransition(s) => &s.state_from }; match state_from { FsmTransitionState::None => quote! { finny::FsmCurrentState::Stopped }, FsmTransitionState::State(st) => { let state_ty = FsmTypes::new(&st.ty, &fsm.base.fsm_generics); let variant = state_ty.get_fsm_no_generics_ty(); quote! { finny::FsmCurrentState::State(#states_enum_ty :: #variant) } } } }; let match_event = { let event = match &transition.ty { FsmTransitionType::InternalTransition(s) | FsmTransitionType::SelfTransition(s) => &s.event, FsmTransitionType::StateTransition(s) => &s.event }; match event { crate::parse::FsmTransitionEvent::Start => quote! { ev @ finny::FsmEvent::Start }, crate::parse::FsmTransitionEvent::Stop => quote ! { ev @ finny::FsmEvent::Stop }, crate::parse::FsmTransitionEvent::Event(ref ev) => { let kind = &ev.ty; quote! { finny::FsmEvent::Event(#event_enum_ty::#kind(ref ev)) } } } }; let guard = { let has_guard = match &transition.ty { FsmTransitionType::StateTransition(s) => { s.action.guard.is_some() } FsmTransitionType::InternalTransition(s) | FsmTransitionType::SelfTransition(s) => { s.action.guard.is_some() } }; if has_guard { quote! { if <#transition_ty>::execute_guard(&mut ctx, &ev, #region_id, &mut inspect_event_ctx) } } else { TokenStream::new() } }; let fsm_sub_entry = match &transition.ty { FsmTransitionType::StateTransition(FsmStateTransition {state_to: FsmTransitionState::State(s @ FsmState { kind: FsmStateKind::SubMachine(_), .. }), .. }) => { let sub_ty = &s.ty; quote! { // reset { use finny::FsmBackendResetSubmachine; <Self as FsmBackendResetSubmachine<_, #sub_ty >>::reset(ctx.backend, &mut inspect_event_ctx); } { <#transition_ty>::execute_on_sub_entry(&mut ctx, #region_id, &mut inspect_event_ctx); } } }, _ => TokenStream::new() }; let timers_enter = { let mut timers_enter = TokenStream::new(); let state = match &transition.ty { FsmTransitionType::SelfTransition(FsmStateAction { state: FsmTransitionState::State(st @ FsmState { .. }), .. }) => { Some(st) }, FsmTransitionType::StateTransition(FsmStateTransition { state_to: FsmTransitionState::State(st @ FsmState { .. }), .. }) => { Some(st) }, _ => None }; if let Some(state) = state { for timer in &state.timers { let timer_field = timer.get_field(&fsm.base); let timer_ty = timer.get_ty(&fsm.base); timers_enter.append_all(quote! { { use finny::FsmTimer; ctx.backend.states. #timer_field . execute_on_enter( #timers_enum_ty :: #timer_ty , &mut ctx.backend.context, &mut inspect_event_ctx, ctx.timers ); } }); } } timers_enter }; let timers_exit = { let mut timers_exit = TokenStream::new(); let state = match &transition.ty { FsmTransitionType::SelfTransition(FsmStateAction { state: FsmTransitionState::State(st @ FsmState { .. }), .. }) => { Some(st) }, FsmTransitionType::StateTransition(FsmStateTransition { state_from: FsmTransitionState::State(st @ FsmState { .. }), .. }) => { Some(st) }, _ => None }; if let Some(state) = state { for timer in &state.timers { let timer_field = timer.get_field(&fsm.base); let timer_ty = timer.get_ty(&fsm.base); timers_exit.append_all(quote! { { use finny::FsmTimer; ctx.backend.states. #timer_field . execute_on_exit( #timers_enum_ty :: #timer_ty , &mut inspect_event_ctx, ctx.timers ); } }); } } timers_exit }; let m = quote! { ( #match_state , #match_event ) #guard => { #timers_exit <#transition_ty>::execute_transition(&mut ctx, &ev, #region_id, &mut inspect_event_ctx); #fsm_sub_entry #timers_enter }, }; region_transitions.append_all(m); } // match and dispatch to submachines let region_submachines = { let mut sub_matches = TokenStream::new(); let submachines: Vec<_> = region.transitions.iter().filter_map(|t| match &t.ty { FsmTransitionType::InternalTransition(_) => None, FsmTransitionType::SelfTransition(_) => None, FsmTransitionType::StateTransition(FsmStateTransition { state_to: FsmTransitionState::State(s @ FsmState { kind: FsmStateKind::SubMachine(_), .. }), .. }) => { Some(s) }, _ => None }).collect(); for submachine in submachines { let kind = &submachine.ty; let fsm_sub = FsmTypes::new(&submachine.ty, &fsm.base.fsm_generics); let kind_variant = fsm_sub.get_fsm_no_generics_ty(); let sub = quote! { ( finny::FsmCurrentState::State(#states_enum_ty :: #kind_variant), finny::FsmEvent::Event(#event_enum_ty::#kind_variant(ev)) ) => { return finny::dispatch_to_submachine::<_, #kind, _, _, _>(&mut ctx, finny::FsmEvent::Event(ev.clone()), &mut inspect_event_ctx); }, }; sub_matches.append_all(sub); } sub_matches }; // match and dispatch timer events let timers = { let mut timer_dispatch = TokenStream::new(); // our timers for state in &region.states { for timer in &state.timers { let timer_ty = timer.get_ty(&fsm.base); timer_dispatch.append_all(quote! { (_, finny::FsmEvent::Timer( timer_id @ #timers_enum_ty :: #timer_ty )) => { { use finny::FsmTimer; < #timer_ty #fsm_generics_type > :: execute_trigger(*timer_id, &mut ctx, &mut inspect_event_ctx); } }, }); } } // sub machines for state in region.states.iter().filter(|s| if let FsmStateKind::SubMachine(_) = s.kind { true } else { false }) { let sub = &state.ty; let sub_ty = FsmTypes::new(sub, &fsm.base.fsm_generics); let sub_variant = sub_ty.get_fsm_no_generics_ty(); timer_dispatch.append_all(quote! { (_, finny::FsmEvent::Timer( #timers_enum_ty :: #sub_variant (timer_id))) => { { let ev = finny::FsmEvent::Timer(*timer_id); return finny::dispatch_to_submachine::<_, #sub, _, _, _>(&mut ctx, ev, &mut inspect_event_ctx); } }, }); } timer_dispatch }; regions.append_all(quote! { match (ctx.backend.current_states[#region_id], &event) { #region_submachines #region_transitions // do not dispatch timers if the machine is stopped (finny::FsmCurrentState::Stopped, finny::FsmEvent::Timer(_)) => (), #timers _ => { transition_misses += 1; } } }); } quote! { impl #fsm_generics_impl finny::FsmBackend for #fsm_ty #fsm_generics_type #fsm_generics_where { type Context = #ctx_ty; type States = #states_store_ty #fsm_generics_type; type Events = #event_enum_ty; type Timers = #timers_enum_ty; fn dispatch_event<Q, I, T>(mut ctx: finny::DispatchContext<Self, Q, I, T>, event: finny::FsmEvent<Self::Events, Self::Timers>) -> finny::FsmDispatchResult where Q: finny::FsmEventQueue<Self>, I: finny::Inspect, T: finny::FsmTimers<Self> { use finny::{FsmTransitionGuard, FsmTransitionAction, FsmAction, FsmState, FsmTransitionFsmStart}; let mut transition_misses = 0; let mut inspect_event_ctx = ctx.inspect.new_event::<Self>(&event, &ctx.backend); #regions let result = if transition_misses == #region_count { Err(finny::FsmError::NoTransition) } else { Ok(()) }; inspect_event_ctx.event_done(&ctx.backend); result } } impl #fsm_generics_impl core::fmt::Debug for #fsm_ty #fsm_generics_type #fsm_generics_where { fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error > { Ok(()) } } } }; let states = { let mut states = TokenStream::new(); for (ty, state) in fsm.fsm.states.iter() { let remap_closure = |c: &Option<syn::ExprClosure>| -> syn::Result<TokenStream> { if let Some(c) = &c { let remap = remap_closure_inputs(&c.inputs, &vec![ quote! { self }, quote! { context } ])?; let b = &c.body; let q = quote! { #remap { #b } }; Ok(q) } else { Ok(TokenStream::new()) } }; let on_entry = remap_closure(&state.on_entry_closure)?; let on_exit = remap_closure(&state.on_exit_closure)?; let state_ty = FsmTypes::new(&ty, &fsm.base.fsm_generics); let variant = state_ty.get_fsm_no_generics_ty(); let state = quote! { impl #fsm_generics_impl finny::FsmState<#fsm_ty #fsm_generics_type> for #ty #fsm_generics_where { fn on_entry<'fsm_event, Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type>>(&mut self, context: &mut finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q>) { #on_entry } fn on_exit<'fsm_event, Q: finny::FsmEventQueue<#fsm_ty #fsm_generics_type>>(&mut self, context: &mut finny::EventContext<'fsm_event, #fsm_ty #fsm_generics_type, Q>) { #on_exit } fn fsm_state() -> #states_enum_ty { #states_enum_ty :: #variant } } }; states.append_all(state); } states }; let builder = { quote! { /// A Finny Finite State Machine. pub struct #fsm_ty #fsm_generics_type #fsm_generics_where { backend: finny::FsmBackendImpl<#fsm_ty #fsm_generics_type > } impl #fsm_generics_impl finny::FsmFactory for #fsm_ty #fsm_generics_type #fsm_generics_where { type Fsm = #fsm_ty #fsm_generics_type; fn new_submachine_backend(backend: finny::FsmBackendImpl<Self::Fsm>) -> finny::FsmResult<Self> where Self: Sized { Ok(Self { backend }) } } impl #fsm_generics_impl core::ops::Deref for #fsm_ty #fsm_generics_type #fsm_generics_where { type Target = finny::FsmBackendImpl<#fsm_ty #fsm_generics_type >; fn deref(&self) -> &Self::Target { &self.backend } } impl #fsm_generics_impl core::ops::DerefMut for #fsm_ty #fsm_generics_type #fsm_generics_where { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.backend } } } }; let timers = { let mut code = TokenStream::new(); let mut enum_variants = vec![]; let mut submachines = vec![]; let mut our_timers = vec![]; let states = fsm.fsm.states.iter().map(|s| s.1); for state in states { if let FsmStateKind::SubMachine(_) = &state.kind { let sub_fsm_ty = FsmTypes::new(&state.ty, &fsm.base.fsm_generics); let n = sub_fsm_ty.get_fsm_no_generics_ty(); let t = sub_fsm_ty.get_fsm_timers_ty(); enum_variants.push(quote! { #n ( #t ) }); submachines.push(sub_fsm_ty.clone()); code.append_all(quote! { impl From<#t> for #timers_enum_ty { fn from(t: #t) -> Self { #timers_enum_ty :: #n ( t ) } } }); } for timer in &state.timers { let state_ty = &state.ty; let timer_ty = timer.get_ty(&fsm.base); enum_variants.push(quote! { #timer_ty }); our_timers.push(timer_ty.clone()); let setup = remap_closure_inputs(&timer.setup.inputs, &[quote! { ctx }, quote! { settings }])?; let setup_body = &timer.setup.body; let trigger = remap_closure_inputs(&timer.trigger.inputs, &[quote! { ctx }, quote! { state }])?; let trigger_body = &timer.trigger.body; let timer_doc = format!("A timer in the state [{}] of FSM [{}].", tokens_to_string(state_ty), tokens_to_string(fsm_ty)); code.append_all(quote! { #[doc = #timer_doc ] pub struct #timer_ty #fsm_generics_type #fsm_generics_where { instance: Option<finny::TimerInstance < #fsm_ty #fsm_generics_type > > } impl #fsm_generics_impl core::default::Default for #timer_ty #fsm_generics_type #fsm_generics_where { fn default() -> Self { Self { instance: None } } } impl #fsm_generics_impl finny::FsmTimer< #fsm_ty #fsm_generics_type , #state_ty > for #timer_ty #fsm_generics_type #fsm_generics_where { fn setup(ctx: &mut #ctx_ty, settings: &mut finny::TimerFsmSettings) { #setup { #setup_body } } fn trigger(ctx: & #ctx_ty, state: & #state_ty ) -> Option< #event_enum_ty > { #trigger let ret = { #trigger_body }; ret } fn get_instance(&self) -> &Option<finny::TimerInstance < #fsm_ty #fsm_generics_type > > { &self.instance } fn get_instance_mut(&mut self) -> &mut Option<finny::TimerInstance < #fsm_ty #fsm_generics_type > > { &mut self.instance } } }); } } let variants = { let mut t = TokenStream::new(); t.append_separated(&enum_variants, quote! { , }); t }; code.append_all(quote! { #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum #timers_enum_ty { #variants } }); let submachine_iters: Vec<_> = submachines.iter().map(|s| { let ty = s.get_fsm_timers_iter_ty(); let field = to_field_name(&ty); (ty, field) }).collect(); let enum_iter_matches_variants = our_timers.iter().enumerate().map(|(i, variant)| quote! { #i => { self.position += 1; Some(#timers_enum_ty :: #variant) } }); let mut enum_iter_matches = TokenStream::new(); enum_iter_matches.append_separated(enum_iter_matches_variants, quote! { , }); enum_iter_matches.append_separated(submachine_iters.iter().enumerate().map(|(i, (ty, field))| { let i = our_timers.len() + i; quote! { #i if self.#field.is_some() => { if let Some(ref mut iter) = self.#field { let r = iter.next(); if let Some(r) = r { let r = r.into(); return Some(r); } else { self.#field = None; self.position += 1; return self.next(); } } else { None } } } }), quote! { , }); let mut submachine_iter_struct = TokenStream::new(); submachine_iter_struct.append_separated(submachine_iters.iter().map(|(ty, field)| quote! { #field : Option< #ty > }), quote! { , }); let mut submachine_iter_new = TokenStream::new(); submachine_iter_new.append_separated(submachine_iters.iter().map(|(ty, field)| quote! { #field : Some ( <#ty> :: new() ) }), quote! { , }); // timers iterator code.append_all(quote! { impl finny::AllVariants for #timers_enum_ty { type Iter = #timers_enum_iter_ty; fn iter() -> #timers_enum_iter_ty { #timers_enum_iter_ty::new() } } pub struct #timers_enum_iter_ty { position: usize, #submachine_iter_struct } impl #timers_enum_iter_ty { pub fn new() -> Self { Self { position: 0, #submachine_iter_new } } } impl core::iter::Iterator for #timers_enum_iter_ty { type Item = #timers_enum_ty; fn next(&mut self) -> Option<Self::Item> { match self.position { #enum_iter_matches _ => None } } } }); // timers storage let our_timers_storage: Vec<_> = our_timers.iter().map(|t| { let field = to_field_name(t); (field, t.clone()) }).collect(); let mut timers_storage_struct_fields = Vec::new(); timers_storage_struct_fields.extend(our_timers_storage.iter().map(|(field, ty)| { quote! { #field: Option < TTimerStorage > } })); timers_storage_struct_fields.extend(submachines.iter().map(|s| { let ty = s.get_fsm_timers_storage_ty(); let field = to_field_name(&ty); quote! { #field: #ty < TTimerStorage > } })); let mut fields = TokenStream::new(); fields.append_separated(timers_storage_struct_fields, quote! { , }); let mut new_fields_vec = vec![]; new_fields_vec.extend(our_timers_storage.iter().map(|(field, ty)| quote! { #field: None })); new_fields_vec.extend(submachines.iter().map(|s| { let ty = s.get_fsm_timers_storage_ty(); let field = to_field_name(&ty); quote! { #field: #ty :: default() } })); let mut new_fields = TokenStream::new(); new_fields.append_separated(new_fields_vec, quote! { , }); let mut timers_storage_matches = vec![]; timers_storage_matches.extend(our_timers_storage.iter().map(|(field, ty)| { quote! { #timers_enum_ty :: #ty => &mut self. #field } })); timers_storage_matches.extend(submachines.iter().map(|s| { let ty = s.get_fsm_timers_storage_ty(); //let t = s.get_fsm_timers_ty(); let t = s.get_fsm_no_generics_ty(); let field = to_field_name(&ty); quote! { #timers_enum_ty :: #t (ref sub) => { self. #field .get_timer_storage_mut(sub) } } })); let matches = if timers_storage_matches.len() == 0 { quote! { panic!("Not supported in this FSM."); } } else { let mut m = TokenStream::new(); m.append_separated(timers_storage_matches, quote! { , }); quote! { match *id { #m } } }; code.append_all(quote! { pub struct #timers_storage_ty<TTimerStorage> { _storage: core::marker::PhantomData<TTimerStorage>, #fields } impl<TTimerStorage> core::default::Default for #timers_storage_ty<TTimerStorage> { fn default() -> Self { Self { _storage: core::marker::PhantomData::default(), #new_fields } } } impl<TTimerStorage> finny::TimersStorage<#timers_enum_ty , TTimerStorage> for #timers_storage_ty<TTimerStorage> { fn get_timer_storage_mut(&mut self, id: & #timers_enum_ty ) -> &mut Option<TTimerStorage> { #matches } } }); code }; // submachine restart let sub_restart = { let subs: Vec<_> = fsm.fsm.states.iter().filter_map(|(ty, state)| match state.kind { FsmStateKind::SubMachine(ref sub) => Some((ty, state, sub.clone())), _ => None }).collect(); if subs.len() == 0 { TokenStream::new() } else { let mut q = TokenStream::new(); for (sub_ty, state, sub) in subs { q.append_all(quote! { impl #fsm_generics_impl finny::FsmBackendResetSubmachine< #fsm_ty #fsm_generics_type , #sub_ty > for #fsm_ty #fsm_generics_type #fsm_generics_where { fn reset<I>(backend: &mut finny::FsmBackendImpl< #fsm_ty #fsm_generics_type >, inspect_event_ctx: &mut I) where I: finny::Inspect { let sub_fsm: &mut #sub_ty = backend.states.as_mut(); sub_fsm.backend.current_states = Default::default(); inspect_event_ctx.info("Setting the state of the submachine to Start."); } } }); } q } }; let fsm_meta = generate_fsm_meta(&fsm); let mut q = quote! { #states_store #states #events_enum #transition_types #dispatch #builder #timers #sub_restart #fsm_meta }; /* // this goes in front of our definition function q.append_all(quote! { #[allow(dead_code)] }); q.append_all(attr); q.append_all(input); */ Ok(q.into()) }
412
0.931401
1
0.931401
game-dev
MEDIA
0.262948
game-dev
0.969661
1
0.969661
alibaba/atlas
1,491
atlas-demo/AtlasDemo/lottie/src/main/java/com/airbnb/lottie/Mask.java
package com.airbnb.lottie; import org.json.JSONObject; class Mask { enum MaskMode { MaskModeAdd, MaskModeSubtract, MaskModeIntersect, MaskModeUnknown } private final MaskMode maskMode; private final AnimatableShapeValue maskPath; private Mask(MaskMode maskMode, AnimatableShapeValue maskPath) { this.maskMode = maskMode; this.maskPath = maskPath; } static class Factory { private Factory() { } static Mask newMask(JSONObject json, LottieComposition composition) { MaskMode maskMode; switch (json.optString("mode")) { case "a": maskMode = MaskMode.MaskModeAdd; break; case "s": maskMode = MaskMode.MaskModeSubtract; break; case "i": maskMode = MaskMode.MaskModeIntersect; break; default: maskMode = MaskMode.MaskModeUnknown; } AnimatableShapeValue maskPath = AnimatableShapeValue.Factory.newInstance( json.optJSONObject("pt"), composition); // TODO: use this // JSONObject opacityJson = json.optJSONObject("o"); // if (opacityJson != null) { // AnimatableIntegerValue opacity = // new AnimatableIntegerValue(opacityJson, composition, false, true); // } return new Mask(maskMode, maskPath); } } @SuppressWarnings("unused") MaskMode getMaskMode() { return maskMode; } AnimatableShapeValue getMaskPath() { return maskPath; } }
412
0.67792
1
0.67792
game-dev
MEDIA
0.425205
game-dev,web-frontend
0.816167
1
0.816167
jarjin/LuaFramework_NGUI
26,193
Assets/LuaFramework/ToLua/BaseType/System_Collections_Generic_ListWrap.cs
using System; using LuaInterface; using System.Collections.Generic; using System.Reflection; using UnityEngine; using System.Collections; public class System_Collections_Generic_ListWrap { public static void Register(LuaState L) { L.BeginClass(typeof(List<>), typeof(System.Object), "List"); L.RegFunction("Add", Add); L.RegFunction("AddRange", AddRange); L.RegFunction("AsReadOnly", AsReadOnly); L.RegFunction("BinarySearch", BinarySearch); L.RegFunction("Clear", Clear); L.RegFunction("Contains", Contains); L.RegFunction("CopyTo", CopyTo); L.RegFunction("Exists", Exists); L.RegFunction("Find", Find); L.RegFunction("FindAll", FindAll); L.RegFunction("FindIndex", FindIndex); L.RegFunction("FindLast", FindLast); L.RegFunction("FindLastIndex", FindLastIndex); L.RegFunction("ForEach", ForEach); L.RegFunction("GetEnumerator", GetEnumerator); L.RegFunction("GetRange", GetRange); L.RegFunction("IndexOf", IndexOf); L.RegFunction("Insert", Insert); L.RegFunction("InsertRange", InsertRange); L.RegFunction("LastIndexOf", LastIndexOf); L.RegFunction("Remove", Remove); L.RegFunction("RemoveAll", RemoveAll); L.RegFunction("RemoveAt", RemoveAt); L.RegFunction("RemoveRange", RemoveRange); L.RegFunction("Reverse", Reverse); L.RegFunction("Sort", Sort); L.RegFunction("ToArray", ToArray); L.RegFunction("TrimExcess", TrimExcess); L.RegFunction("TrueForAll", TrueForAll); L.RegFunction("get_Item", get_Item); L.RegFunction("set_Item", set_Item); L.RegFunction(".geti", get_Item); L.RegFunction(".seti", set_Item); L.RegFunction("__tostring", ToLua.op_ToString); L.RegVar("Capacity", get_Capacity, set_Capacity); L.RegVar("Count", get_Count, null); L.EndClass(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Add(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); object arg0 = ToLua.CheckVarObject(L, 2, argType); LuaMethodCache.CallSingleMethod("Add", obj, arg0); return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int AddRange(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); object arg0 = ToLua.CheckObject(L, 2, typeof(IEnumerable<>).MakeGenericType(argType)); LuaMethodCache.CallSingleMethod("AddRange", obj, arg0); return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int AsReadOnly(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); object o = LuaMethodCache.CallSingleMethod("AsReadOnly", obj); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int BinarySearch(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int o = (int)LuaMethodCache.CallMethod("BinarySearch", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 3) { object arg0 = ToLua.CheckVarObject(L, 2, argType); object arg1 = ToLua.CheckObject(L, 3, typeof(IComparer<>).MakeGenericType(argType)); int o = (int)LuaMethodCache.CallMethod("BinarySearch", obj, arg0, arg1); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 5) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); object arg2 = ToLua.CheckVarObject(L, 4, argType); object arg3 = ToLua.CheckObject(L, 5, typeof(IComparer<>).MakeGenericType(argType)); int o = (int)LuaMethodCache.CallMethod("BinarySearch", obj, arg0, arg1, arg2, arg3); LuaDLL.lua_pushinteger(L, o); return 1; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.BinarySearch", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Clear(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); LuaMethodCache.CallSingleMethod("Clear", obj); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Contains(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); object arg0 = ToLua.CheckVarObject(L, 2, argType); object o = LuaMethodCache.CallSingleMethod("Contains", obj, arg0); LuaDLL.lua_pushboolean(L, (bool)o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int CopyTo(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { object arg0 = ToLua.CheckObject(L, 2, argType.MakeArrayType()); LuaMethodCache.CallMethod("CopyTo", obj, arg0); return 0; } else if (count == 3) { object arg0 = ToLua.CheckObject(L, 2, argType.MakeArrayType()); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); LuaMethodCache.CallMethod("CopyTo", obj, arg0, arg1); return 0; } else if (count == 5) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); object arg1 = ToLua.CheckObject(L, 3, argType.MakeArrayType()); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); int arg3 = (int)LuaDLL.luaL_checknumber(L, 5); LuaMethodCache.CallMethod("CopyTo", obj, arg0, arg1, arg2, arg3); return 0; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.CopyTo", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Exists(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); bool o = (bool)LuaMethodCache.CallMethod("Exists", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Find(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); object o = LuaMethodCache.CallMethod("Find", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int FindAll(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); object o = LuaMethodCache.CallMethod("FindAll", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int FindIndex(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); int o = (int)LuaMethodCache.CallMethod("FindIndex", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 3) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); Delegate arg1 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 3); int o = (int)LuaMethodCache.CallMethod("FindIndex", obj, arg0, arg1); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 4) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); Delegate arg2 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 4); int o = (int)LuaMethodCache.CallMethod("FindIndex", obj, arg0, arg1, arg2); LuaDLL.lua_pushinteger(L, o); return 1; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.FindIndex", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int FindLast(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); object o = LuaMethodCache.CallSingleMethod("FindLast", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int FindLastIndex(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { Delegate arg0 = (Delegate)ToLua.CheckObject(L, 2, typeof(System.Predicate<>).MakeGenericType(argType)); int o = (int)LuaMethodCache.CallMethod("FindLastIndex", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 3) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); Delegate arg1 = (Delegate)ToLua.CheckObject(L, 3, typeof(System.Predicate<>).MakeGenericType(argType)); int o = (int)LuaMethodCache.CallMethod("FindLastIndex", obj, arg0, arg1); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 4) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); Delegate arg2 = (Delegate)ToLua.CheckObject(L, 4, typeof(System.Predicate<>).MakeGenericType(argType)); int o = (int)LuaMethodCache.CallMethod("FindLastIndex", obj, arg0, arg1, arg2); LuaDLL.lua_pushinteger(L, o); return 1; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.FindLastIndex", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ForEach(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Action<>).MakeGenericType(argType), L, 2); LuaMethodCache.CallSingleMethod("ForEach", obj, arg0); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int GetEnumerator(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); IEnumerator o = LuaMethodCache.CallSingleMethod("GetEnumerator", obj) as IEnumerator; ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int GetRange(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); object o = LuaMethodCache.CallSingleMethod("GetRange", obj, arg0, arg1); ToLua.PushObject(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int IndexOf(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int o = (int)LuaMethodCache.CallMethod("IndexOf", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 3) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int o = (int)LuaMethodCache.CallMethod("IndexOf", obj, arg0, arg1); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 4) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); int o = (int)LuaMethodCache.CallMethod("IndexOf", obj, arg0, arg1, arg2); LuaDLL.lua_pushinteger(L, o); return 1; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.IndexOf", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Insert(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); object arg1 = ToLua.CheckVarObject(L, 3, argType); LuaMethodCache.CallSingleMethod("Insert", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int InsertRange(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); IEnumerable arg1 = (IEnumerable)ToLua.CheckObject(L, 3, typeof(IEnumerable<>).MakeGenericType(argType)); LuaMethodCache.CallSingleMethod("InsertRange", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int LastIndexOf(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 2) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int o = (int)LuaMethodCache.CallMethod("LastIndexOf", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 3) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int o = (int)LuaMethodCache.CallMethod("LastIndexOf", obj, arg0, arg1); LuaDLL.lua_pushinteger(L, o); return 1; } else if (count == 4) { object arg0 = ToLua.CheckVarObject(L, 2, argType); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); int arg2 = (int)LuaDLL.luaL_checknumber(L, 4); int o = (int)LuaMethodCache.CallMethod("LastIndexOf", obj, arg0, arg1, arg2); LuaDLL.lua_pushinteger(L, o); return 1; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.LastIndexOf", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Remove(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); object arg0 = ToLua.CheckVarObject(L, 2, argType); bool o = (bool)LuaMethodCache.CallSingleMethod("Remove", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int RemoveAll(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); int o = (int)LuaMethodCache.CallSingleMethod("RemoveAll", obj, arg0); LuaDLL.lua_pushinteger(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int RemoveAt(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); LuaMethodCache.CallSingleMethod("RemoveAt", obj, arg0); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int RemoveRange(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); LuaMethodCache.CallSingleMethod("RemoveRange", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Reverse(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 1) { LuaMethodCache.CallMethod("Reverse", obj); return 0; } else if (count == 3) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); LuaMethodCache.CallMethod("Reverse", obj, arg0, arg1); return 0; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.LastIndexOf", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Sort(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); if (count == 1) { LuaMethodCache.CallMethod("Sort", obj); return 0; } else if (count == 2 && TypeChecker.CheckTypes(L, 2, typeof(System.Comparison<>).MakeGenericType(argType))) { Delegate arg0 = (Delegate)ToLua.ToObject(L, 2); LuaMethodCache.CallMethod("Sort", obj, arg0); return 0; } else if (count == 2 && TypeChecker.CheckTypes(L, 2, typeof(IComparer<>).MakeGenericType(argType))) { object arg0 = ToLua.ToObject(L, 2); LuaMethodCache.CallMethod("Sort", obj, arg0); return 0; } else if (count == 4) { int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); object arg2 = ToLua.CheckObject(L, 4, typeof(IComparer<>).MakeGenericType(argType)); LuaMethodCache.CallMethod("Sort", obj, arg0, arg1, arg2); return 0; } else { return LuaDLL.luaL_throw(L, string.Format("invalid arguments to method: List<{0}>.LastIndexOf", LuaMisc.GetTypeName(argType))); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ToArray(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); Array o = (Array)LuaMethodCache.CallSingleMethod("ToArray", obj); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int TrimExcess(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); LuaMethodCache.CallSingleMethod("TrimExcess", obj); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int TrueForAll(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); Delegate arg0 = ToLua.CheckDelegate(typeof(System.Predicate<>).MakeGenericType(argType), L, 2); bool o = (bool)LuaMethodCache.CallSingleMethod("TrueForAll", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Item(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); object o = LuaMethodCache.CallSingleMethod("get_Item", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_Item(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type argType = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(List<>), out argType); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); object arg1 = ToLua.CheckObject(L, 3, argType); LuaMethodCache.CallSingleMethod("set_Item", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Capacity(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); int ret = (int)LuaMethodCache.CallSingleMethod("get_Capacity", o); LuaDLL.lua_pushinteger(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o, "attempt to index Capacity on a nil value"); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Count(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); int ret = (int)LuaMethodCache.CallSingleMethod("get_Count", o); LuaDLL.lua_pushinteger(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o, "attempt to index Count on a nil value"); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_Capacity(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); LuaMethodCache.CallSingleMethod("set_Capacity", o, arg0); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o, "attempt to index Capacity on a nil value"); } } }
412
0.821075
1
0.821075
game-dev
MEDIA
0.562874
game-dev
0.842661
1
0.842661
corretto/corretto-jdk
21,612
src/java.base/share/classes/jdk/internal/loader/Loader.java
/* * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.internal.loader; import java.io.IOException; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.lang.module.ResolvedModule; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.security.CodeSigner; import java.security.CodeSource; import java.security.SecureClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import jdk.internal.access.SharedSecrets; import jdk.internal.module.Resources; /** * A class loader that loads classes and resources from a collection of * modules, or from a single module where the class loader is a member * of a pool of class loaders. * * <p> The delegation model used by this ClassLoader differs to the regular * delegation model. When requested to load a class then this ClassLoader first * maps the class name to its package name. If there a module defined to the * Loader containing the package then the class loader attempts to load from * that module. If the package is instead defined to a module in a "remote" * ClassLoader then this class loader delegates directly to that class loader. * The map of package name to remote class loader is created based on the * modules read by modules defined to this class loader. If the package is not * local or remote then this class loader will delegate to the parent class * loader. This allows automatic modules (for example) to link to types in the * unnamed module of the parent class loader. * * @see ModuleLayer#defineModulesWithOneLoader * @see ModuleLayer#defineModulesWithManyLoaders */ public final class Loader extends SecureClassLoader { static { ClassLoader.registerAsParallelCapable(); } // the pool this loader is a member of; can be null private final LoaderPool pool; // parent ClassLoader, can be null private final ClassLoader parent; // maps a module name to a module reference private final Map<String, ModuleReference> nameToModule; // maps package name to a module loaded by this class loader private final Map<String, LoadedModule> localPackageToModule; // maps package name to a remote class loader, populated post initialization private final Map<String, ClassLoader> remotePackageToLoader = new ConcurrentHashMap<>(); // maps a module reference to a module reader, populated lazily private final Map<ModuleReference, ModuleReader> moduleToReader = new ConcurrentHashMap<>(); /** * A module defined/loaded to a {@code Loader}. */ private static class LoadedModule { private final ModuleReference mref; private final CodeSource cs; LoadedModule(ModuleReference mref) { URL url = null; if (mref.location().isPresent()) { try { url = mref.location().get().toURL(); } catch (MalformedURLException | IllegalArgumentException e) { } } this.mref = mref; this.cs = new CodeSource(url, (CodeSigner[]) null); } ModuleReference mref() { return mref; } String name() { return mref.descriptor().name(); } CodeSource codeSource() { return cs; } } /** * Creates a {@code Loader} in a loader pool that loads classes/resources * from one module. */ public Loader(ResolvedModule resolvedModule, LoaderPool pool, ClassLoader parent) { super("Loader-" + resolvedModule.name(), parent); this.pool = pool; this.parent = parent; ModuleReference mref = resolvedModule.reference(); ModuleDescriptor descriptor = mref.descriptor(); String mn = descriptor.name(); this.nameToModule = Map.of(mn, mref); Map<String, LoadedModule> localPackageToModule = new HashMap<>(); LoadedModule lm = new LoadedModule(mref); descriptor.packages().forEach(pn -> localPackageToModule.put(pn, lm)); this.localPackageToModule = localPackageToModule; } /** * Creates a {@code Loader} that loads classes/resources from a collection * of modules. * * @throws IllegalArgumentException * If two or more modules have the same package */ public Loader(Collection<ResolvedModule> modules, ClassLoader parent) { super(parent); this.pool = null; this.parent = parent; Map<String, ModuleReference> nameToModule = new HashMap<>(); Map<String, LoadedModule> localPackageToModule = new HashMap<>(); for (ResolvedModule resolvedModule : modules) { ModuleReference mref = resolvedModule.reference(); ModuleDescriptor descriptor = mref.descriptor(); nameToModule.put(descriptor.name(), mref); descriptor.packages().forEach(pn -> { LoadedModule lm = new LoadedModule(mref); if (localPackageToModule.put(pn, lm) != null) throw new IllegalArgumentException("Package " + pn + " in more than one module"); }); } this.nameToModule = nameToModule; this.localPackageToModule = localPackageToModule; } /** * Completes initialization of this Loader. This method populates * remotePackageToLoader with the packages of the remote modules, where * "remote modules" are the modules read by modules defined to this loader. * * @param cf the Configuration containing at least modules to be defined to * this class loader * * @param parentModuleLayers the parent ModuleLayers */ public Loader initRemotePackageMap(Configuration cf, List<ModuleLayer> parentModuleLayers) { for (String name : nameToModule.keySet()) { ResolvedModule resolvedModule = cf.findModule(name).get(); assert resolvedModule.configuration() == cf; for (ResolvedModule other : resolvedModule.reads()) { String mn = other.name(); ClassLoader loader; if (other.configuration() == cf) { // The module reads another module in the newly created // layer. If all modules are defined to the same class // loader then the packages are local. if (pool == null) { assert nameToModule.containsKey(mn); continue; } loader = pool.loaderFor(mn); assert loader != null; } else { // find the layer for the target module ModuleLayer layer = parentModuleLayers.stream() .map(parent -> findModuleLayer(parent, other.configuration())) .flatMap(Optional::stream) .findAny() .orElseThrow(() -> new InternalError("Unable to find parent layer")); // find the class loader for the module // For now we use the platform loader for modules defined to the // boot loader assert layer.findModule(mn).isPresent(); loader = layer.findLoader(mn); if (loader == null) loader = ClassLoaders.platformClassLoader(); } // find the packages that are exported to the target module ModuleDescriptor descriptor = other.reference().descriptor(); if (descriptor.isAutomatic()) { ClassLoader l = loader; descriptor.packages().forEach(pn -> remotePackage(pn, l)); } else { String target = resolvedModule.name(); for (ModuleDescriptor.Exports e : descriptor.exports()) { boolean delegate; if (e.isQualified()) { // qualified export in same configuration delegate = (other.configuration() == cf) && e.targets().contains(target); } else { // unqualified delegate = true; } if (delegate) { remotePackage(e.source(), loader); } } } } } return this; } /** * Adds to remotePackageToLoader so that an attempt to load a class in * the package delegates to the given class loader. * * @throws IllegalStateException * if the package is already mapped to a different class loader */ private void remotePackage(String pn, ClassLoader loader) { ClassLoader l = remotePackageToLoader.putIfAbsent(pn, loader); if (l != null && l != loader) { throw new IllegalStateException("Package " + pn + " cannot be imported from multiple loaders"); } } /** * Find the layer corresponding to the given configuration in the tree * of layers rooted at the given parent. */ private Optional<ModuleLayer> findModuleLayer(ModuleLayer parent, Configuration cf) { return SharedSecrets.getJavaLangAccess().layers(parent) .filter(l -> l.configuration() == cf) .findAny(); } /** * Returns the loader pool that this loader is in or {@code null} if this * loader is not in a loader pool. */ public LoaderPool pool() { return pool; } // -- resources -- /** * Returns a URL to a resource of the given name in a module defined to * this class loader. */ @Override protected URL findResource(String mn, String name) throws IOException { ModuleReference mref = (mn != null) ? nameToModule.get(mn) : null; if (mref == null) return null; // not defined to this class loader // locate resource URL url = null; Optional<URI> ouri = moduleReaderFor(mref).find(name); if (ouri.isPresent()) { try { url = ouri.get().toURL(); } catch (MalformedURLException | IllegalArgumentException e) { } } return url; } @Override public URL findResource(String name) { String pn = Resources.toPackageName(name); LoadedModule module = localPackageToModule.get(pn); if (module != null) { try { URL url = findResource(module.name(), name); if (url != null && (name.endsWith(".class") || url.toString().endsWith("/") || isOpen(module.mref(), pn))) { return url; } } catch (IOException ioe) { // ignore } } else { for (ModuleReference mref : nameToModule.values()) { try { URL url = findResource(mref.descriptor().name(), name); if (url != null) return url; } catch (IOException ioe) { // ignore } } } return null; } @Override public Enumeration<URL> findResources(String name) throws IOException { return Collections.enumeration(findResourcesAsList(name)); } @Override public URL getResource(String name) { Objects.requireNonNull(name); // this loader URL url = findResource(name); if (url == null) { // parent loader if (parent != null) { url = parent.getResource(name); } else { url = BootLoader.findResource(name); } } return url; } @Override public Enumeration<URL> getResources(String name) throws IOException { Objects.requireNonNull(name); // this loader List<URL> urls = findResourcesAsList(name); // parent loader Enumeration<URL> e; if (parent != null) { e = parent.getResources(name); } else { e = BootLoader.findResources(name); } // concat the URLs with the URLs returned by the parent return new Enumeration<>() { final Iterator<URL> iterator = urls.iterator(); @Override public boolean hasMoreElements() { return (iterator.hasNext() || e.hasMoreElements()); } @Override public URL nextElement() { if (iterator.hasNext()) { return iterator.next(); } else { return e.nextElement(); } } }; } /** * Finds the resources with the given name in this class loader. */ private List<URL> findResourcesAsList(String name) throws IOException { String pn = Resources.toPackageName(name); LoadedModule module = localPackageToModule.get(pn); if (module != null) { URL url = findResource(module.name(), name); if (url != null && (name.endsWith(".class") || url.toString().endsWith("/") || isOpen(module.mref(), pn))) { return List.of(url); } else { return Collections.emptyList(); } } else { List<URL> urls = new ArrayList<>(); for (ModuleReference mref : nameToModule.values()) { URL url = findResource(mref.descriptor().name(), name); if (url != null) { urls.add(url); } } return urls; } } // -- finding/loading classes /** * Finds the class with the specified binary name. */ @Override protected Class<?> findClass(String cn) throws ClassNotFoundException { Class<?> c = null; LoadedModule loadedModule = findLoadedModule(cn); if (loadedModule != null) c = findClassInModuleOrNull(loadedModule, cn); if (c == null) throw new ClassNotFoundException(cn); return c; } /** * Finds the class with the specified binary name in the given module. * This method returns {@code null} if the class cannot be found. */ @Override protected Class<?> findClass(String mn, String cn) { Class<?> c = null; LoadedModule loadedModule = findLoadedModule(cn); if (loadedModule != null && loadedModule.name().equals(mn)) c = findClassInModuleOrNull(loadedModule, cn); return c; } /** * Loads the class with the specified binary name. */ @Override protected Class<?> loadClass(String cn, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(cn)) { // check if already loaded Class<?> c = findLoadedClass(cn); if (c == null) { LoadedModule loadedModule = findLoadedModule(cn); if (loadedModule != null) { // class is in module defined to this class loader c = findClassInModuleOrNull(loadedModule, cn); } else { // type in another module or visible via the parent loader String pn = packageName(cn); ClassLoader loader = remotePackageToLoader.get(pn); if (loader == null) { // type not in a module read by any of the modules // defined to this loader, so delegate to parent // class loader loader = parent; } if (loader == null) { c = BootLoader.loadClassOrNull(cn); } else { c = loader.loadClass(cn); } } } if (c == null) throw new ClassNotFoundException(cn); if (resolve) resolveClass(c); return c; } } /** * Finds the class with the specified binary name if in a module * defined to this ClassLoader. * * @return the resulting Class or {@code null} if not found */ private Class<?> findClassInModuleOrNull(LoadedModule loadedModule, String cn) { ModuleReader reader = moduleReaderFor(loadedModule.mref()); try { // read class file String rn = cn.replace('.', '/').concat(".class"); ByteBuffer bb = reader.read(rn).orElse(null); if (bb == null) { // class not found return null; } try { return defineClass(cn, bb, loadedModule.codeSource()); } finally { reader.release(bb); } } catch (IOException ioe) { // TBD on how I/O errors should be propagated return null; } } // -- miscellaneous supporting methods /** * Find the candidate module for the given class name. * Returns {@code null} if none of the modules defined to this * class loader contain the API package for the class. */ private LoadedModule findLoadedModule(String cn) { String pn = packageName(cn); return pn.isEmpty() ? null : localPackageToModule.get(pn); } /** * Returns the package name for the given class name */ private String packageName(String cn) { int pos = cn.lastIndexOf('.'); return (pos < 0) ? "" : cn.substring(0, pos); } /** * Returns the ModuleReader for the given module. */ private ModuleReader moduleReaderFor(ModuleReference mref) { return moduleToReader.computeIfAbsent(mref, m -> createModuleReader(mref)); } /** * Creates a ModuleReader for the given module. */ private ModuleReader createModuleReader(ModuleReference mref) { try { return mref.open(); } catch (IOException e) { // Return a null module reader to avoid a future class load // attempting to open the module again. return new NullModuleReader(); } } /** * A ModuleReader that doesn't read any resources. */ private static class NullModuleReader implements ModuleReader { @Override public Optional<URI> find(String name) { return Optional.empty(); } @Override public Stream<String> list() { return Stream.empty(); } @Override public void close() { throw new InternalError("Should not get here"); } } /** * Returns true if the given module opens the given package * unconditionally. * * @implNote This method currently iterates over each of the open * packages. This will be replaced once the ModuleDescriptor.Opens * API is updated. */ private boolean isOpen(ModuleReference mref, String pn) { ModuleDescriptor descriptor = mref.descriptor(); if (descriptor.isOpen() || descriptor.isAutomatic()) return true; for (ModuleDescriptor.Opens opens : descriptor.opens()) { String source = opens.source(); if (!opens.isQualified() && source.equals(pn)) { return true; } } return false; } }
412
0.951487
1
0.951487
game-dev
MEDIA
0.456764
game-dev
0.911895
1
0.911895
scemino/engge2
5,912
src/scenegraph/saveloaddlg.nim
import std/strformat import std/os import std/times import std/json import glm import node import uinode import textnode import spritenode import nimyggpack import ../gfx/color import ../gfx/graphics import ../gfx/text import ../gfx/image import ../gfx/recti import ../gfx/texture import ../gfx/spritesheet import ../game/resmanager import ../game/screen import ../game/gameloader import ../game/states/state import ../io/textdb import ../util/strutils import ../util/time const LoadGame = 99910 SaveGame = 99911 Back = 99904 type ClickCallback* = proc(node: Node, id: int) SaveLoadDialogMode* = enum smLoad smSave SaveLoadDialog* = ref object of UINode mode: SaveLoadDialogMode savegames: array[9, Savegame] clickCbk: ClickCallback proc newHeader(id: int): TextNode = let titleTxt = newText(gResMgr.font("HeadingFont"), getText(id), thCenter) result = newTextNode(titleTxt) result.pos = vec2(ScreenWidth/2f - titleTxt.bounds.x/2f, 690f) proc onButton(src: Node, event: EventKind, pos: Vec2f, tag: pointer) = case event: of Enter: src.color = Yellow of Leave: src.color = White of Down: let dlg = cast[SaveLoadDialog](src.getParent()) src.color = White dlg.clickCbk(dlg, Back) else: discard proc newButton(id: int, y: float, font = "UIFontLarge"): TextNode = let titleTxt = newText(gResMgr.font(font), getText(id), thCenter) result = newTextNode(titleTxt) result.pos = vec2(ScreenWidth/2f - titleTxt.bounds.x/2f, y) result.addButton(onButton, cast[pointer](result)) proc newBackground(): SpriteNode = let sheet = gResMgr.spritesheet("SaveLoadSheet") result = newSpriteNode(gResMgr.texture(sheet.meta.image), sheet.frame("saveload")) result.scale = vec2(4f, 4f) result.pos = vec2(ScreenWidth/2f, ScreenHeight/2f) proc loadTexture(file: string): Texture = let f = open(file, fmRead) let size = f.getFileSize var buff = newSeq[byte](size) discard f.readBytes(buff, 0, size) f.close newTexture(newImage(buff)) proc fmtTime(time: Time): string = # time format: "%b %d at %H:%M" fmtTimeLikeC(time, getText(99944)) proc fmtGameTime(timeInSec: float): string = var buffer: array[120, char] var buf = cast[cstring](buffer[0].addr) var min = timeInSec.int div 60 if min < 2: # "%d minute" discard snprintf(buf, 120, getText(99945).cstring, min) elif min < 60: # "%d minutes" discard snprintf(buf, 120, getText(99946).cstring, min) else: var format: int var hour = min div 60 min = min mod 60 if hour < 2 and min < 2: # "%d hour %d minute" format = 99947 elif hour < 2 and min >= 2: # "%d hour %d minutes" format = 99948; elif hour >= 2 and min < 2: # "%d hours %d minute" format = 99949; else: # "%d hours %d minutes"; format = 99950 discard snprintf(buf, 120, getText(format).cstring, hour, min) $buf proc onGameButton(src: Node, event: EventKind, pos: Vec2f, tag: pointer) = case event: of Down: let dlg = cast[SaveLoadDialog](src.getParent()) popState(stateCount() - 1) if dlg.mode == smLoad: let data = cast[JsonNode](tag) loadGame(data) else: let i = cast[int](tag) saveGame(i) else: discard proc newSaveLoadDialog*(mode: SaveLoadDialogMode, clickCbk: ClickCallback): SaveLoadDialog = result = SaveLoadDialog(mode: mode, clickCbk: clickCbk) result.addChild newBackground() result.addChild newHeader(if mode == smLoad: LoadGame else: SaveGame) let sheet = gResMgr.spritesheet("SaveLoadSheet") let slotFrame = sheet.frame("saveload_slot_frame") let scale = vec2(4f*slotFrame.frame.w.float32/320f, 4f*slotFrame.frame.h.float32/180f) let fontSmallBold = gResMgr.font("UIFontSmall") for i in 0..<9: let path = fmt"Savegame{i+1}.png" let savePath = changeFileExt(path, "save") if fileExists(path) and fileExists(savePath): # load savegame data let savegame = loadSaveGame(savePath) result.savegames[i] = savegame let easyMode = savegame.data["easy_mode"].getInt() != 0 let gameTime = savegame.data["gameTime"].getFloat() var saveTimeText = if i==0: getText(99901) else: fmtTime(savegame.time) if easyMode: saveTimeText &= ' ' & getText(99955) # thumbnail let sn = newSpriteNode(loadTexture(path)) sn.scale = scale sn.setAnchorNorm(vec2(0.5f, 0.5f)) sn.pos = vec2f(scale.x * (1f + (i mod 3).float32) * (sn.size.x + 4f), (scale.y * ((8-i) div 3).float32 * (sn.size.y + 4f))) result.addChild sn # game time text let gtt = newTextNode(newText(fontSmallBold, fmtGameTime(gameTime), thCenter)) gtt.setAnchorNorm(vec2(0.5f, 0.5f)) gtt.pos = vec2(310f + 320f*(i mod 3).float32, 240f + 180*((8-i) div 3).float32) result.addChild gtt # save time text let stt = newTextNode(newText(fontSmallBold, saveTimeText, thCenter)) stt.setAnchorNorm(vec2(0.5f, 0.5f)) stt.pos = vec2(310f + 320f*(i mod 3).float32, 110f + 180*((8-i) div 3).float32) result.addChild stt # frame let sn = newSpriteNode(gResMgr.texture(sheet.meta.image), slotFrame) sn.scale = vec2(4f, 4f) sn.setAnchorNorm(vec2(0.5f, 0.5f)) sn.pos = vec2f((1f + (i mod 3).float32) * 4f * (sn.size.x + 1f), 4f * ((8-i) div 3).float32 * (sn.size.y + 1f)) # don't allow to save on slot 0 if (mode == smLoad and fileExists(savePath)) or (mode == smSave and i != 0): echo fmt"file '{savePath}' exists #{i}" let tag = if mode == smLoad: cast[pointer](result.savegames[i].data) else: cast[pointer](i) sn.addButton(onGameButton, tag) result.addChild sn result.addChild newButton(Back, 80f, "UIFontMedium") result.init() method drawCore(self: SaveLoadDialog, transf: Mat4f) = gfxDrawQuad(vec2(0f, 0f), vec2f(ScreenWidth, ScreenHeight), rgbaf(Black, 0.5f), transf)
412
0.738819
1
0.738819
game-dev
MEDIA
0.749648
game-dev
0.944093
1
0.944093
ProjectIgnis/CardScripts
3,303
unofficial/c511005091.lua
--Sacrifice's Blast --original script by Shad3 local s,id=GetID() function s.initial_effect(c) --Globals aux.GlobalCheck(s,function() local ge1=Effect.CreateEffect(c) ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge1:SetCode(EVENT_SSET) ge1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) ge1:SetCondition(s.gtg_cd) ge1:SetOperation(s.gtg_op) Duel.RegisterEffect(ge1,0) local ge2=Effect.CreateEffect(c) ge2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge2:SetCode(EVENT_SUMMON_SUCCESS) ge2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) ge2:SetOperation(s.sum_op) Duel.RegisterEffect(ge2,0) local ge3=Effect.CreateEffect(c) ge3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge3:SetCode(EVENT_LEAVE_FIELD_P) ge3:SetOperation(s.reflag_op) Duel.RegisterEffect(ge3,0) end) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetTarget(s.tg) e1:SetOperation(s.op) c:RegisterEffect(e1) end function s.gtg_cd(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(Card.IsOriginalCode,1,nil,id) end function s.gtg_op(e,tp,eg,ep,ev,re,r,rp) local g=eg:Filter(Card.IsOriginalCode,nil,id) local c=g:GetFirst() while c do local p=c:GetControler() if Duel.GetFieldGroupCount(p,LOCATION_MZONE,LOCATION_MZONE)>0 then Duel.Hint(HINT_SELECTMSG,p,HINTMSG_TARGET) local tc=Duel.GetFieldGroup(p,LOCATION_MZONE,LOCATION_MZONE):Select(p,1,1,nil):GetFirst() local fid=c:GetFieldID() tc:RegisterFlagEffect(id,RESET_EVENT+0x1000000,0,0,fid) end c=g:GetNext() end end function s.fid_chk(c,id) return c:GetFieldID()==id end function s.sum_op(e,tp,eg,ep,ev,re,r,rp) local tc=eg:GetFirst() if (tc:GetSummonType()&SUMMON_TYPE_TRIBUTE)==SUMMON_TYPE_TRIBUTE then local g=tc:GetMaterial() local sactg={} g:ForEach(function(c) if c:GetFlagEffect(id)~=0 then sactg[c:GetFlagEffectLabel(id)]=true c:ResetFlagEffect(id) end end) local sg=Duel.GetMatchingGroup(Card.IsOriginalCode,0,LOCATION_SZONE,LOCATION_SZONE,nil,id) sg:ForEach(function(c) local fid=c:GetFieldID() if sactg[fid] then c:GetActivateEffect():SetLabel(tc:GetFieldID()) local e1=Effect.CreateEffect(tc) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e1:SetCode(id) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_MZONE) e1:SetOperation(s.des_op) e1:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e1,true) end end) end end function s.des_op(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if Duel.Destroy(c,REASON_EFFECT)~=0 then Duel.Damage(c:GetPreviousControler(),c:GetPreviousAttackOnField(),REASON_EFFECT) end end function s.reflag_op(e,tp,eg,ep,ev,re,r,rp) local c=eg:GetFirst() while c do if c:GetFlagEffect(id)~=0 then if (c:GetReason()&REASON_RELEASE)==0 then c:ResetFlagEffect(id) end end c=eg:GetNext() end end function s.tg(e,tp,eg,ep,ev,re,r,rp,chk) local ac=Duel.GetAttacker() if chk==0 then return ac:GetControler()~=tp and e:GetLabel()==ac:GetFieldID() end e:GetHandler():SetCardTarget(ac) end function s.op(e,tp,eg,ep,ev,re,r,rp) local ac=e:GetHandler():GetFirstCardTarget() if ac then Duel.RaiseSingleEvent(ac,id,e,REASON_EFFECT,tp,tp,e:GetHandler():GetFieldID()) end end
412
0.798529
1
0.798529
game-dev
MEDIA
0.984297
game-dev
0.942837
1
0.942837
EvenMoreFish/EvenMoreFish
16,240
even-more-fish-plugin/src/main/resources/locales/messages_en.yml
# If a message contains EvenMoreFish placeholders, e.g. {player} or {rarity} it also supports placeholderapi placeholders. # Important: Read the following if you are on a Paper server. # These messages are able to support the MiniMessage format (in strict mode) if you are on a Paper server. # You are able to mix both formats on the same line, however this is not recommended. # Here are the MiniMessage Docs for help with using MiniMessage: https://docs.advntr.dev/minimessage/format.html # Sent to players when they fish an EvenMoreFish fish fish-caught: <b>{player}</b> has fished a {length}cm <b>{rarity}</b> {fish}! # By setting a fish's minimum-length to less than 0, you can create a lengthless fish. This is used when a player fishes a lengthless fish. lengthless-fish-caught: <b>{player}</b> has fished a <b>{rarity}</b> {fish}! # Sent to players when they hunt an EvenMoreFish fish fish-hunted: <b>{player}</b> has hunted a {length}cm <b>{rarity}</b> {fish}! # This is used when a player hunts a lengthless fish. lengthless-fish-hunted: <b>{player}</b> has hunted a <b>{rarity}</b> {fish}! # Sent to a player when they don't have permission to execute a command. no-permission: <red>You don't have permission to run that command. # The message to be sent when a competition starts and ends contest-start: <white>A fishing contest for {type} has started. contest-end: <white>The fishing contest has ended. # The message to be sent when a player joins whilst a competition is going on contest-join: <white>A fishing contest for {type} is occurring. # Shown to players when a new player takes #1 spot, remove this value or set it to "" to disable this message new-first: '<white>{player} is now #1' # Should this message appear in chat (false) or above the exp bar (true) action-bar-message: true # What competition types should the action bar be used for? (recommended: MOST_FISH) action-bar-types: - MOST_FISH # What should replace the {type} variable for each competition type? competition-types: # MOST_FISH most: the most fish # LARGEST_FISH largest: the largest fish # LARGEST_TOTAL_FISH largest-total: the largest total fish length # SHORTEST_FISH shortest: the shortest fish # SHORTEST_TOTAL_FISH shortest-total: the shortest total fish length # SPECIFIC_FISH specific: '{amount} <b>{rarity}</b> {fish}' # SPECIFIC_RARITY specific-rarity: '{amount} <b>{rarity}</b> fish' # Segments shown in the bossbar when competitions run bossbar: layout: '{prefix}{time-formatted} {remaining}' # The abbreviations used for different units of time in the {time-formatted} variable. hour: <white>{hour}h minute: <white>{minute}m second: <white>{second}s # For translating the "left" at the end e.g. "5s left" -> "5s kvar" # This is the {remaining} variable. remaining: left # The prefix shown in commands. Keeping the space in is recommended. prefix-regular: '<green>[EvenMoreFish] ' # The prefix shown in admin commands. prefix-admin: '<red>[EvenMoreFish] ' # The prefix shown when errors occur e.g. no permission to run a command. prefix-error: '<red>[EvenMoreFish] ' # This is the format of the lore given to fish when they're caught. # {custom-lore} is specified in the fish configs under the lore: section, if the fish has a lore, the lore's lines will # replace the {fish_lore}, however if it's empty the line will be removed. DO NOT ADD ANYTHING OTHER THAN THIS VARIABLE # TO THAT LINE. fish-lore: - '{fisherman_lore}' - '{length_lore}' - '' - '{fish_lore}' - '<b>{rarity}' # Sets what to replace with the {fisherman_lore} or {length_lore} with above ^ fisherman-lore: - <white>Caught by {player} length-lore: - <white>Measures {length}cm. # The format of the leaderboard after a competition is over (this message doesn't support papi placeholders) leaderboard-largest-fish: <white>#{position} | {player} (<b>{rarity}</b> {fish}, {length}cm) leaderboard-largest-total: <white>#{position} | {player} <white>({amount}cm<white>) leaderboard-most-fish: <white>#{position} | {player} <white>({amount} <white>fish) leaderboard-shortest-fish: <white>#{position} | {player} <white>(<b>{rarity}</b> {fish}<white>, {length}cm<white>) leaderboard-shortest-total: <white>#{position} | {player} <white>({amount}cm<white>) # If you're running a competition where there's no leaderboard, this message is sent when there's a winner single-winner: <white>{player} has won the competition for {type}. Congratulations! # This shows the number of players currently in the competition, set to "" to disable. total-players: <white>There are a total of {amount} player(s) in the leaderboard. # The number of positions shown in the leaderboard - can't be less than 1. leaderboard-count: 5 # If the player doesn't appear on /emf top, should their position be displayed at the bottom? always-show-pos: true # Sent to players when nobody got a record during a competition no-winners: <white>There were no fishing records. # When an individual player didn't get a record no-record: <white>You didn't catch any fish. # Sent when an admin tries to start a competition where the type doesn't exist e.g. /emf admin competition start 600 ABCDEFGH invalid-type: '<white>That isn''t a type of competition type, available types: https://evenmorefish.github.io/EvenMoreFish/docs/features/competitions/types' # Sent to all online players when not enough players are on to start a competition not-enough-players: <white>There's not enough players online to start the scheduled fishing competition. # Sent to all players at specific times to show the remaining time left # {time_formatted} shows the time (e.g. 5m left, 10m 30s left) # {time_raw} is what you input in competitions.yml time-alert: <white>There is {time_formatted} left on the competition for {type} # The sell price: # 0 – prints a digit if provided, 0 otherwise # # – prints a digit if provided, nothing otherwise # . – indicate where to put the decimal separator # , – indicate where to put the grouping separator sell-price-format: $#,##0.0 # The message sent to players when they've sold their fish in the /emf shop fish-sale: <white>You've sold <green>{amount} <white>fish for <green>{sell-price}<white>. # The message sent to players when they attempt to sell and there are no sellable fish no-sellable-fish: <white>You have nothing to sell! # Help messages # General help (/emf help) - permission node dependant commands will only show if they are formatted with the forward-slash. help-format: '[noPrefix]<aqua>{command} <yellow>- {description}' help-general: title: '[noPrefix]<gradient:#f1ffed:#f1ffed><st> </st><b><green> EvenMoreFish </green></b><st><gradient:#73ff6b:#f1ffed> ' top: '[noPrefix]Shows an ongoing competition''s leaderboard.' help: '[noPrefix]Shows you this page.' shop: '[noPrefix]Opens a shop to sell your fish.' toggle: '[noPrefix]Toggles whether or not you receive custom fish.' gui: '[noPrefix]Opens the Main Menu GUI.' admin: '[noPrefix]Admin command help page.' sellall: '[noPrefix]Sell all the fish in your inventory.' next: '[noPrefix]Show how much time is until the next competition.' applybaits: '[noPrefix]Apply baits to your fishing rod.' journal: "[noPrefix]View a journal of caught fish and their stats." help-list: fish: '[noPrefix]Display all fish in a specific rarity.' rarities: '[noPrefix]Display all rarities.' # Competition help (/emf admin competition help) help-competition: start: '[noPrefix]Starts a competition of a specified duration' end: '[noPrefix]Ends the current competition (if there is one)' # Admin help (/emf admin help) help-admin: bait: '[noPrefix]Gives baits to a player.' competition: '[noPrefix]Starts or stops a competition' clearbaits: '[noPrefix]Removes all applied baits from a fishing rod.' fish: '[noPrefix]Gives a fish to a player.' nbt-rod: '[noPrefix]Gives a custom NBT rod to a player required for catching EMF fish.' custom-rod: '[noPrefix]Gives a custom fishing rod to a player.' reload: '[noPrefix]Reloads the plugin''s config files.' migrate: '[noPrefix]Migrate the database from Legacy (V2) to V3' addons: '[noPrefix]Display all addons.' rewardtypes: '[noPrefix]Display all reward types.' version: '[noPrefix]Displays plugin information.' rawitem: '[noPrefix]Displays the item in your main hand as raw NBT.' # Shown when the emf %emf_competition_place_player_*% placeholder requests a position in the leaderboard that doesn't exist no-player-in-place: Start fishing to take this place # Shown when the emf %emf_competition_place_fish_*% placeholder requests a position in the leaderboard that doesn't exist no-fish-in-place: Start fishing to take this place # Shown when the emf %emf_competition_place_size_*% placeholder requests a position in the leaderboard that doesn't exist no-size-in-place: Start fishing to take this place # Shown when the emf %emf_competition_place_player_*% placeholder is used when there's no competition running no-competition-running: No competition running right now. # Shown when the emf %emf_competition_place_fish_*% placeholder is used when there's no competition running no-competition-running-fish: No competition running right now. # Shown when the emf %emf_competition_place_size_*% placeholder is used when there's no competition running no-competition-running-size: No competition running right now. # HOw should %emf_custom_fishing_status% be formatted? custom-fishing-enabled: <green>Enabled custom-fishing-disabled: <red>Disabled # How should the %emf_competition_place_fish_*% be formatted? emf-competition-fish-format: '{length}cm <b>{rarity}</b> {fish}' # How should the %emf_competition_place_fish_*% be formatted when there's no length on the fish? emf-lengthless-fish-format: '<b>{rarity}</b> {fish}' # How should %emf_competition_place_fish_*% be formatted during MOST/SPECIFIC_FISH competitions? emf-most-fish-format: '{amount} fish' # What should be displayed for %emf_competition_place_size_*% during the MOST_FISH competition? emf-size-during-most-fish: N/A # How the %emf_competition_time_left% variable should be formatted. emf-time-remaining: 'Time left until next competition: {days}d, {hours}h, {minutes}m.' # Replaces the %emf_competition_time_left% variable when there's a competition already running. emf-time-remaining-during-comp: There is a competition running right now. # Sent when a player tries to apply too many types of baits to a fishing rod, set in the general section of baits.yml max-baits-reached: <white>You have reached the maximum number of types of baits for this fishing rod. # Not to be confused with the above, this is sent when the maximum of a specific bait is reached. Define this in baits.yml using "max-baits". max-bait-reached: <white>You have reached the maximum number of {bait} <white>bait that can be applied to one rod. # Sent when a player catches a bait from fishing (this can be disabled by setting catch-percentage to 0 in baits.yml bait-catch: <white><b>{player}</b> has caught a <b>{bait}</b> bait! # Sent when a bait is applied and a fish is caught. bait-use: <white>You have used one of your rod's <b>{bait}</b> bait. # Sent when someone tries to use a bait in creative bait-survival-limited: <white>You must be in <u>survival or adventure mode</u> to apply baits to fishing rods. # Sent when someone tries to merge a baited rod into an unbaited rod bait-rod-protection: <white>Protected your baited fishing rod. If you are trying to repair it, please put it in the first slot instead. # Sent when someone tries to apply a bait to a fishing rod they cannot use to fish bait-invalid-rod: <white>You cannot apply bait to this fishing rod! # Shown when /emf toggle is run, to turn off and on respectively. toggle-off: <white>You will no longer catch custom fish. toggle-on: <white>You will now catch custom fish. admin: # Opens an /emf shop for another player open-fish-shop: <white>Opened a shop inventory for {player}. # When a fish is given to a player given-player-fish: <white>You have given {player} a {fish}. # When a bait is given to a player given-player-bait: <white>You have given {player} a {bait}. # When an admin runs /emf admin bait without a bait name. no-bait-specified: <white>You must specify a bait name. # When the admin tries the command /emf admin clearbaits whe not holding a fishing rod. must-be-holding-rod: <white>You need to be holding a fishing rod to run that command. # When /emf admin clearbaits command is run. all-baits-cleared: <white>You have removed all {amount} baits from your fishing rod. # /emf admin clearbaits is run, but there are no baits on the rod. no-baits-on-rod: <white>The fishing rod does not have any baits applied. # When economy is disabled for the plugin economy-disabled: <white>EvenMoreFish's economy features are disabled. # When the specified player can't be found when using -p: parameter. player-not-found: <white>{player} could not be found. # When the specified number in -q: is not a number. number-format-error: <white>{amount} is not a valid number. # When the specified number in -q: is not within the minecraft stack range (1-64) number-range-error: <white>{amount} is not a number between 1-64. # When a command cannot be run from the console cannot-run-on-console: <white>Command cannot be run from console. # Sent when a competition is already running when using /emf admin competition start competition-already-running: <white>There's already a competition running. # When an invalid competition type is provided competition-type-invalid: '<white>That isn''t a competition type. Available Types: https://evenmorefish.github.io/EvenMoreFish/docs/features/competitions/types' # When an invalid competition id is provided competition-id-invalid: <white>That isn't a valid competition id. # When the command /emf admin custom-rod is run. custom-rod-given: <white>You have given {player} a custom fishing rod. # When there's a modrinth update available, don't translate the URL otherwise it won't direct to the correct page. update-available: '<white>There is an update available: https://modrinth.com/plugin/evenmorefish/versions?l=paper' # When the plugin is reloaded reload: <white>Successfully reloaded the plugin. # When checking a list of registered addons. The actual list is added to the end of this message. list-addons: '<white>Registered {addon-type}s: ' # When an invalid rarity is provided for a command. rarity-invalid: <white>That is not a valid rarity! # When the player can't access the Fishing Journal journal-disabled: <white>The Fishing Journal is not accessible. Please enable the plugin's database. # Bait messages bait: # How the lore should look ({baits} takes up multiple lines) rod-lore: - <white> - '<gray>Bait Slots: <yellow>({current_baits}/{max_baits})' - <white> - '{baits}' - <white> # The default lore of the bait, changing this will not modify existing baits, but with an /emf admin reload, new baits # given out will have this lore. Bait themes can be set as a colour or prefix and be used in this lore. bait-lore: - <white> - 'Increases the catch rates for:' - '{boosts}' - '{lore}' - <white> - <#dadada>Drop onto a fishing rod to apply, - <#dadada>or hold <u>SHIFT</u> to apply all. - <white> # How the baits should look in each line of the {baits} variable above ^. {baits} respects the display name setting, # the <gold> is there for baits without a display name set. baits: <gold>► {amount} {bait} # These are listed in the {boosts} variable above in bait-lore # boost-rarity/rarities: shown when the bait only impacts 1 rarity or when it impacts multiple rarities. # boost-fish: shown when the bait impacts some fish individually. boosts-rarity: '► <white>1 Rarity' boosts-rarities: '► <white>{amount} Rarities' boosts-fish: '► <white>{amount} Fish' # This is added to the lore in place of a bait if show-unused-slots is enabled in the general section. unused-slot: <gray>► ? <i>Available Slot # ATTENTION ATTENTION ATTENTION # DO NOT EDIT THIS VALUE OR THINGS WILL BREAK!!! version: 5
412
0.910831
1
0.910831
game-dev
MEDIA
0.425369
game-dev
0.770034
1
0.770034
emileb/OpenGames
175,653
opengames/src/main/jni/OpenJK/code/game/g_active.cpp
/* This file is part of Jedi Academy. Jedi Academy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Jedi Academy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Jedi Academy. If not, see <http://www.gnu.org/licenses/>. */ // Copyright 2001-2013 Raven Software #include "g_local.h" #include "g_functions.h" #include "../cgame/cg_local.h" #include "Q3_Interface.h" #include "wp_saber.h" #include "g_vehicles.h" #include "b_local.h" #include "g_navigator.h" #ifdef _DEBUG #include <float.h> #endif //_DEBUG #define SLOWDOWN_DIST 128.0f #define MIN_NPC_SPEED 16.0f extern void VehicleExplosionDelay( gentity_t *self ); extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); extern void G_MaintainFormations(gentity_t *self); extern void BG_CalculateOffsetAngles( gentity_t *ent, usercmd_t *ucmd );//in bg_pangles.cpp extern void TryUse( gentity_t *ent ); extern void ChangeWeapon( gentity_t *ent, int newWeapon ); extern void ScoreBoardReset(void); extern void WP_SaberReflectCheck( gentity_t *self, usercmd_t *ucmd ); extern void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ); extern void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ); extern void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ); extern gentity_t *SeekerAcquiresTarget ( gentity_t *ent, vec3_t pos ); extern void FireSeeker( gentity_t *owner, gentity_t *target, vec3_t origin, vec3_t dir ); extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); extern qboolean PM_LockAngles( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesToGripper( gentity_t *gent, usercmd_t *cmd ); extern qboolean PM_AdjustAnglesToPuller( gentity_t *ent, gentity_t *puller, usercmd_t *ucmd, qboolean faceAway ); extern qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); extern qboolean PM_AdjustAngleForWallRunUp( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); extern qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ); extern qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ); extern qboolean PM_AdjustAnglesForDualJumpAttack( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForLongJump( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForGrapple( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAngleForWallJump( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); extern qboolean PM_AdjustAnglesForBFKick( gentity_t *ent, usercmd_t *ucmd, vec3_t fwdAngs, qboolean aimFront ); extern qboolean PM_AdjustAnglesForStabDown( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForSpinProtect( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForWallRunUpFlipAlt( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_AdjustAnglesForHeldByMonster( gentity_t *ent, gentity_t *monster, usercmd_t *ucmd ); extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); extern qboolean PM_LeapingSaberAnim( int anim ); extern qboolean PM_SpinningSaberAnim( int anim ); extern qboolean PM_SaberInAttack( int move ); extern qboolean PM_KickingAnim( int anim ); extern int PM_AnimLength( int index, animNumber_t anim ); extern qboolean PM_InKnockDown( playerState_t *ps ); extern qboolean PM_InGetUp( playerState_t *ps ); extern qboolean PM_InRoll( playerState_t *ps ); extern void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ); extern qboolean PM_InAttackRoll( int anim ); extern qboolean PM_CrouchAnim( int anim ); extern qboolean PM_FlippingAnim( int anim ); extern qboolean PM_InCartwheel( int anim ); extern qboolean PM_StandingAnim( int anim ); extern qboolean PM_InForceGetUp( playerState_t *ps ); extern qboolean PM_GetupAnimNoMove( int legsAnim ); extern qboolean PM_SuperBreakLoseAnim( int anim ); extern qboolean PM_SuperBreakWinAnim( int anim ); extern qboolean PM_CanRollFromSoulCal( playerState_t *ps ); extern qboolean BG_FullBodyTauntAnim( int anim ); extern qboolean FlyingCreature( gentity_t *ent ); extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); extern void G_AttachToVehicle( gentity_t *ent, usercmd_t **ucmd ); extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ); extern void G_UpdateEmplacedWeaponData( gentity_t *ent ); extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); extern void NPC_SetPainEvent( gentity_t *self ); extern qboolean G_HasKnockdownAnims( gentity_t *ent ); extern int G_GetEntsNearBolt( gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); extern qboolean PM_LockedAnim( int anim ); extern qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ); extern qboolean G_JediInNormalAI( gentity_t *ent ); extern bool in_camera; extern qboolean player_locked; extern qboolean stop_icarus; extern qboolean MatrixMode; extern cvar_t *g_spskill; extern cvar_t *g_timescale; extern cvar_t *g_saberMoveSpeed; extern cvar_t *g_saberAutoBlocking; extern cvar_t *g_speederControlScheme; extern cvar_t *d_slowmodeath; extern cvar_t *g_debugMelee; extern vmCvar_t cg_thirdPersonAlpha; extern vmCvar_t cg_thirdPersonAutoAlpha; void ClientEndPowerUps( gentity_t *ent ); int G_FindLookItem( gentity_t *self ) { //FIXME: should be a more intelligent way of doing this, like auto aim? //closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? gentity_t *ent; int bestEntNum = ENTITYNUM_NONE; gentity_t *entityList[MAX_GENTITIES]; int numListedEntities; vec3_t center, mins, maxs, fwdangles, forward, dir; int i, e; float radius = 256; float rating, bestRating = 0.0f; //FIXME: no need to do this in 1st person? fwdangles[1] = self->client->ps.viewangles[1]; AngleVectors( fwdangles, forward, NULL, NULL ); VectorCopy( self->currentOrigin, center ); for ( i = 0 ; i < 3 ; i++ ) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); if ( !numListedEntities ) { return ENTITYNUM_NONE; } for ( e = 0 ; e < numListedEntities ; e++ ) { ent = entityList[ e ]; if ( !ent->item ) { continue; } if ( ent->s.eFlags&EF_NODRAW ) { continue; } if ( (ent->spawnflags&4/*ITMSF_MONSTER*/) ) {//NPCs only continue; } if ( !BG_CanItemBeGrabbed( &ent->s, &self->client->ps ) ) {//don't need it continue; } if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) {//not even potentially visible continue; } if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) {//can't see him continue; } if ( ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER ) {//a weapon_saber pickup if ( self->client->ps.dualSabers//using 2 sabers already || (self->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) )//using a 2-handed saber {//hands are full already, don't look at saber pickups continue; } } //rate him based on how close & how in front he is VectorSubtract( ent->currentOrigin, center, dir ); rating = (1.0f-(VectorNormalize( dir )/radius)); rating *= DotProduct( forward, dir ); if ( ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY ) {//security keys are of the highest importance rating *= 2.0f; } if ( rating > bestRating ) { bestEntNum = ent->s.number; bestRating = rating; } } return bestEntNum; } extern void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ); qboolean G_ClearViewEntity( gentity_t *ent ) { if ( !ent->client->ps.viewEntity ) return qfalse; if ( ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_NONE ) { if ( &g_entities[ent->client->ps.viewEntity] ) { g_entities[ent->client->ps.viewEntity].svFlags &= ~SVF_BROADCAST; if ( g_entities[ent->client->ps.viewEntity].NPC ) { g_entities[ent->client->ps.viewEntity].NPC->controlledTime = 0; SetClientViewAngle( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); G_SetAngles( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); VectorCopy( g_entities[ent->client->ps.viewEntity].currentAngles, g_entities[ent->client->ps.viewEntity].NPC->lastPathAngles ); g_entities[ent->client->ps.viewEntity].NPC->desiredYaw = g_entities[ent->client->ps.viewEntity].currentAngles[YAW]; } } CG_SetClientViewAngles( ent->pos4, qtrue ); SetClientViewAngle( ent, ent->pos4 ); } ent->client->ps.viewEntity = 0; return qtrue; } void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ) { if ( !self || !self->client || !viewEntity ) { return; } if ( self->s.number == 0 && cg.zoomMode ) { // yeah, it should really toggle them so it plays the end sound.... cg.zoomMode = 0; } if ( viewEntity->s.number == self->client->ps.viewEntity ) { return; } //clear old one first G_ClearViewEntity( self ); //set new one self->client->ps.viewEntity = viewEntity->s.number; viewEntity->svFlags |= SVF_BROADCAST; //remember current angles VectorCopy( self->client->ps.viewangles, self->pos4 ); if ( viewEntity->client ) { //vec3_t clear = {0,0,0}; CG_SetClientViewAngles( viewEntity->client->ps.viewangles, qtrue ); //SetClientViewAngle( self, viewEntity->client->ps.viewangles ); //SetClientViewAngle( viewEntity, clear ); /* VectorCopy( viewEntity->client->ps.viewangles, self->client->ps.viewangles ); for ( int i = 0; i < 3; i++ ) { self->client->ps.delta_angles[i] = viewEntity->client->ps.delta_angles[i]; } */ } if ( !self->s.number ) { CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); } } qboolean G_ControlledByPlayer( gentity_t *self ) { if ( self && self->NPC && self->NPC->controlledTime > level.time ) {//being controlled gentity_t *controller = &g_entities[0]; if ( controller->client && controller->client->ps.viewEntity == self->s.number ) {//we're the player's viewEntity return qtrue; } } return qfalse; } qboolean G_ValidateLookEnemy( gentity_t *self, gentity_t *enemy ) { if ( !enemy ) { return qfalse; } if ( enemy->flags&FL_NOTARGET ) { return qfalse; } if ( (enemy->s.eFlags&EF_NODRAW) ) { return qfalse; } if ( !enemy || enemy == self || !enemy->inuse ) { return qfalse; } if ( !enemy->client || !enemy->NPC ) {//not valid if ( (enemy->svFlags&SVF_NONNPC_ENEMY) && enemy->s.weapon == WP_TURRET && enemy->noDamageTeam != self->client->playerTeam && enemy->health > 0 ) {//a turret //return qtrue; } else { return qfalse; } } else { if ( self->client->playerTeam != TEAM_FREE//evil player hates everybody && enemy->client->playerTeam == self->client->playerTeam ) {//on same team return qfalse; } Vehicle_t *pVeh = G_IsRidingVehicle( self ); if ( pVeh && pVeh == enemy->m_pVehicle ) { return qfalse; } if ( enemy->health <= 0 && ((level.time-enemy->s.time) > 3000||!InFront(enemy->currentOrigin,self->currentOrigin,self->client->ps.viewangles,0.2f)||DistanceHorizontal(enemy->currentOrigin,self->currentOrigin)>16384))//>128 {//corpse, been dead too long or too out of sight to be interesting if ( !enemy->message ) { return qfalse; } } } if ( (!InFront( enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || !G_ClearLOS( self, self->client->renderInfo.eyePoint, enemy ) ) && ( DistanceHorizontalSquared( enemy->currentOrigin, self->currentOrigin ) > 65536 || fabs(enemy->currentOrigin[2]-self->currentOrigin[2]) > 384 ) ) {//(not in front or not clear LOS) & greater than 256 away return qfalse; } //LOS? return qtrue; } void G_ChooseLookEnemy( gentity_t *self, usercmd_t *ucmd ) { //FIXME: should be a more intelligent way of doing this, like auto aim? //closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? gentity_t *ent, *bestEnt = NULL; gentity_t *entityList[MAX_GENTITIES]; int numListedEntities; vec3_t center, mins, maxs, fwdangles, forward, dir; int i, e; float radius = 256; float rating, bestRating = 0.0f; //FIXME: no need to do this in 1st person? fwdangles[0] = 0; //Must initialize data! fwdangles[1] = self->client->ps.viewangles[1]; fwdangles[2] = 0; AngleVectors( fwdangles, forward, NULL, NULL ); VectorCopy( self->currentOrigin, center ); for ( i = 0 ; i < 3 ; i++ ) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); if ( !numListedEntities ) {//should we clear the enemy? return; } for ( e = 0 ; e < numListedEntities ; e++ ) { ent = entityList[ e ]; if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) {//not even potentially visible continue; } if ( !G_ValidateLookEnemy( self, ent ) ) {//doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call continue; } if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) {//can't see him continue; } //rate him based on how close & how in front he is VectorSubtract( ent->currentOrigin, center, dir ); rating = (1.0f-(VectorNormalize( dir )/radius)); rating *= DotProduct( forward, dir )+1.0f; if ( ent->health <= 0 ) { if ( (ucmd->buttons&BUTTON_ATTACK) || (ucmd->buttons&BUTTON_ALT_ATTACK) || (ucmd->buttons&BUTTON_FORCE_FOCUS) ) {//if attacking, don't consider dead enemies continue; } if ( ent->message ) {//keyholder rating *= 0.5f; } else { rating *= 0.1f; } } if ( ent->s.weapon == WP_SABER ) { rating *= 2.0f; } if ( ent->enemy == self ) {//he's mad at me, he's more important rating *= 2.0f; } else if ( ent->NPC && ent->NPC->blockedSpeechDebounceTime > level.time - 6000 ) {//he's detected me, he's more important if ( ent->NPC->blockedSpeechDebounceTime > level.time + 4000 ) { rating *= 1.5f; } else {//from 1.0f to 1.5f rating += rating * ((float)(ent->NPC->blockedSpeechDebounceTime-level.time) + 6000.0f)/20000.0f; } } /* if ( g_crosshairEntNum == ent && !self->enemy ) {//we don't have an enemy and we are aiming at this guy rading *= 2.0f; } */ if ( rating > bestRating ) { bestEnt = ent; bestRating = rating; } } if ( bestEnt ) { self->enemy = bestEnt; } } /* =============== G_DamageFeedback Called just before a snapshot is sent to the given player. Totals up all damage and generates both the player_state_t damage values to that client for pain blends and kicks, and global pain sound events for all clients. =============== */ void P_DamageFeedback( gentity_t *player ) { gclient_t *client; float count; vec3_t angles; client = player->client; if ( client->ps.pm_type == PM_DEAD ) { return; } // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor; if ( count == 0 ) { return; // didn't take any damage } if ( count > 255 ) { count = 255; } // send the information to the client // world damage (falling, slime, etc) uses a special code // to make the blend blob centered instead of positional if ( client->damage_fromWorld ) { client->ps.damagePitch = 255; client->ps.damageYaw = 255; client->damage_fromWorld = false; } else { vectoangles( client->damage_from, angles ); client->ps.damagePitch = angles[PITCH]/360.0 * 256; client->ps.damageYaw = angles[YAW]/360.0 * 256; } client->ps.damageCount = count; // // clear totals // client->damage_blood = 0; client->damage_armor = 0; } /* ============= P_WorldEffects Check for lava / slime contents and drowning ============= */ extern void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); void P_WorldEffects( gentity_t *ent ) { int mouthContents = 0; if ( ent->client->noclip ) { ent->client->airOutTime = level.time + 12000; // don't need air return; } if ( !in_camera ) { if (gi.totalMapContents() & (CONTENTS_WATER|CONTENTS_SLIME)) { mouthContents = gi.pointcontents( ent->client->renderInfo.eyePoint, ent->s.number ); } } // // check for drowning // if ( (mouthContents&(CONTENTS_WATER|CONTENTS_SLIME)) ) { if ( ent->client->NPC_class == CLASS_SWAMPTROOPER ) {//they have air tanks ent->client->airOutTime = level.time + 12000; // don't need air ent->damage = 2; } else if ( ent->client->airOutTime < level.time) {// if out of air, start drowning // drown! ent->client->airOutTime += 1000; if ( ent->health > 0 ) { // take more damage the longer underwater ent->damage += 2; if (ent->damage > 15) ent->damage = 15; // play a gurp sound instead of a normal pain sound if (ent->health <= ent->damage) { G_AddEvent( ent, EV_WATER_DROWN, 0 ); } else { G_AddEvent( ent, Q_irand(EV_WATER_GURP1, EV_WATER_GURP2), 0 ); } // don't play a normal pain sound ent->painDebounceTime = level.time + 200; G_Damage (ent, NULL, NULL, NULL, NULL, ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); } } } else { ent->client->airOutTime = level.time + 12000; ent->damage = 2; } // // check for sizzle damage (move to pmove?) // if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) { if (ent->health > 0 && ent->painDebounceTime < level.time ) { if (ent->watertype & CONTENTS_LAVA) { G_Damage (ent, NULL, NULL, NULL, NULL, 15*ent->waterlevel, 0, MOD_LAVA); } if (ent->watertype & CONTENTS_SLIME) { G_Damage (ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); } } } if ((ent->health > 0) && (ent->painDebounceTime < level.time) && gi.WE_IsOutsideCausingPain(ent->currentOrigin) && TIMER_Done(ent, "AcidPainDebounce")) { if (ent->NPC && ent->client && (ent->client->ps.forcePowersKnown&(1<< FP_PROTECT))) { if (!(ent->client->ps.forcePowersActive & (1<<FP_PROTECT))) { WP_ForcePowerStart( ent, FP_PROTECT, 0 ); } } else { G_Damage (ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); } } // Poisoned? if ((ent->client->poisonDamage) && (ent->client->poisonTime < level.time)) { ent->client->poisonDamage -= 2; ent->client->poisonTime = level.time + 1000; G_Damage( ent, NULL, NULL, 0, 0, 2, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR, MOD_UNKNOWN );//FIXME: MOD_POISON? if (ent->client->poisonDamage<0) { ent->client->poisonDamage = 0; } } //in space? if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) { //we're in space, check for suffocating and for exiting gentity_t *spacetrigger = &g_entities[ent->client->inSpaceIndex]; if (!spacetrigger->inuse || !G_PointInBounds(ent->client->ps.origin, spacetrigger->absmin, spacetrigger->absmax)) { //no longer in space then I suppose ent->client->inSpaceIndex = 0; } else { //check for suffocation if (ent->client->inSpaceSuffocation < level.time) { //suffocate! if (ent->health > 0) { //if they're still alive.. G_Damage(ent, spacetrigger, spacetrigger, NULL, ent->client->ps.origin, Q_irand(20, 40), DAMAGE_NO_ARMOR, MOD_SUICIDE); if (ent->health > 0) { //did that last one kill them? //play the choking sound G_SoundOnEnt( ent, CHAN_VOICE, va( "*choke%d.wav", Q_irand( 1, 3 ) ) ); //make them grasp their throat NPC_SetAnim( ent, SETANIM_BOTH, BOTH_CHOKE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } ent->client->inSpaceSuffocation = level.time + Q_irand(1000, 2000); } } } } /* =============== G_SetClientSound =============== */ void G_SetClientSound( gentity_t *ent ) { // if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) // ent->s.loopSound = G_SoundIndex("sound/weapons/stasis/electricloop.wav"); // else // ent->s.loopSound = 0; } //============================================================== extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); void G_GetMassAndVelocityForEnt( gentity_t *ent, float *mass, vec3_t velocity ) { if( ent->client ) { VectorCopy( ent->client->ps.velocity, velocity ); *mass = ent->mass; } else { VectorCopy( ent->s.pos.trDelta, velocity ); if ( ent->s.pos.trType == TR_GRAVITY ) { velocity[2] -= 0.25f * g_gravity->value; } if( !ent->mass ) { *mass = 1; } else if ( ent->mass <= 10 ) { *mass = 10; } else { *mass = ent->mass;///10; } } } void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace ) { float magnitude, my_mass; bool thrown = false; vec3_t velocity; Vehicle_t *pSelfVeh = NULL; Vehicle_t *pOtherVeh = NULL; // See if either of these guys are vehicles, if so, keep a pointer to the vehicle npc. if ( self->client && self->client->NPC_class == CLASS_VEHICLE ) { pSelfVeh = self->m_pVehicle; } if ( other->client && other->client->NPC_class == CLASS_VEHICLE ) { pOtherVeh = other->m_pVehicle; } G_GetMassAndVelocityForEnt( self, &my_mass, velocity ); if ( pSelfVeh ) { magnitude = VectorLength( velocity ) * pSelfVeh->m_pVehicleInfo->mass / 50.0f; } else { magnitude = VectorLength( velocity ) * my_mass / 50; } //if vehicle hit another vehicle, factor in their data, too // TODO: Bring this back in later on, it's not critical right now... /* if ( self->client && self->client->NPC_class == CLASS_VEHICLE ) {//we're in a vehicle if ( other->client && other->client->ps.vehicleIndex != VEHICLE_NONE ) {//they're in a vehicle float o_mass; vec3_t o_velocity; G_GetMassAndVelocityForEnt( other, &o_mass, o_velocity ); //now combine if ( DotProduct( o_velocity, velocity ) < 0 ) {//were heading towards each other, this is going to be a STRONG impact... vec3_t velocityMod; //incorportate mass into each velocity to get directional force VectorScale( velocity, my_mass/50, velocityMod ); VectorScale( o_velocity, o_mass/50, o_velocity ); //figure out the overall magnitude of those 2 directed forces impacting magnitude = (DotProduct( o_velocity, velocityMod ) * -1.0f)/500.0f; } } }*/ // Check For Vehicle On Vehicle Impact (Ramming) //----------------------------------------------- if ( pSelfVeh && pSelfVeh->m_pVehicleInfo->type!=VH_ANIMAL && pOtherVeh && pSelfVeh->m_pVehicleInfo==pOtherVeh->m_pVehicleInfo ) { gentity_t* attacker = self; Vehicle_t* attackerVeh = pSelfVeh; gentity_t* victim = other; Vehicle_t* victimVeh = pOtherVeh; // Is The Attacker Actually Not Attacking? //----------------------------------------- if (!(attackerVeh->m_ulFlags&VEH_STRAFERAM)) { // Ok, So Is The Victim Actually Attacking? //------------------------------------------ if (victimVeh->m_ulFlags&VEH_STRAFERAM) { // Ah, Ok. Swap Who Is The Attacker Then //---------------------------------------- attacker = other; attackerVeh = pOtherVeh; victim = self; victimVeh = pSelfVeh; } else { // No Attackers, So Stop //----------------------- attacker = victim = 0; } } if (attacker && victim) { // float maxMoveSpeed = pSelfVeh->m_pVehicleInfo->speedMax; // float minLockingSpeed = maxMoveSpeed * 0.75; vec3_t attackerMoveDir; vec3_t victimMoveDir; vec3_t victimTowardAttacker; vec3_t victimRight; float victimRightAccuracy; VectorCopy(attacker->client->ps.velocity, attackerMoveDir); VectorCopy(victim->client->ps.velocity, victimMoveDir); AngleVectors(victim->currentAngles, 0, victimRight, 0); VectorSubtract(victim->currentOrigin, attacker->currentOrigin, victimTowardAttacker); /*victimTowardAttackerDistance = */VectorNormalize(victimTowardAttacker); victimRightAccuracy = DotProduct(victimTowardAttacker, victimRight); if ( fabsf(victimRightAccuracy)>0.25 // Must Be Exactly Right Or Left // && victimTowardAttackerDistance<100.0f // Must Be Close Enough // && attackerMoveSpeed>minLockingSpeed // Must be moving fast enough // && fabsf(attackerMoveSpeed - victimMoveSpeed)<100 // Both must be going about the same speed ) { thrown = true; vec3_t victimRight; vec3_t victimAngles; VectorCopy(victim->currentAngles, victimAngles); victimAngles[2] = 0; AngleVectors(victimAngles, 0, victimRight, 0); if (attackerVeh->m_fStrafeTime<0) { VectorScale(victimRight, -1.0f, victimRight); } if ( !(victim->flags&FL_NO_KNOCKBACK) ) { G_Throw(victim, victimRight, 250); } // if (false) // { // VectorMA(victim->currentOrigin, 250.0f, victimRight, victimRight); // CG_DrawEdge(victim->currentOrigin, victimRight, EDGE_IMPACT_POSSIBLE); // } if (victimVeh->m_pVehicleInfo->iImpactFX) { G_PlayEffect(victimVeh->m_pVehicleInfo->iImpactFX, victim->currentOrigin, trace->plane.normal ); } } } } if ( !self->client || self->client->ps.lastOnGround+300<level.time || ( self->client->ps.lastOnGround+100 < level.time ) ) { vec3_t dir1, dir2; float force = 0, dot; qboolean vehicleHitOwner = qfalse; if ( other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || ((other->svFlags&SVF_BBRUSH)&&(other->spawnflags&8/*THIN*/)) )//(other->absmax[0]-other->absmin[0]<=32||other->absmax[1]-other->absmin[1]<=32||other->absmax[2]-other->absmin[2]<=32)) ) {//glass and thin breakable brushes (axially aligned only, unfortunately) take more impact damage magnitude *= 2; } // See if the vehicle has crashed into the ground. if ( pSelfVeh && pSelfVeh->m_pVehicleInfo->type!=VH_ANIMAL) { if ((magnitude >= 80) && (self->painDebounceTime < level.time)) { // Setup Some Variables //---------------------- vec3_t vehFwd; VectorCopy(velocity, vehFwd); float vehSpeed = VectorNormalize(vehFwd); float vehToughnessAgainstOther = pSelfVeh->m_pVehicleInfo->toughness; float vehHitPercent = fabsf(DotProduct(vehFwd, trace->plane.normal)); int vehDFlags = DAMAGE_NO_ARMOR; bool vehPilotedByPlayer = (pSelfVeh->m_pPilot && pSelfVeh->m_pPilot->s.number<MAX_CLIENTS); bool vehInTurbo = (pSelfVeh->m_iTurboTime>level.time); self->painDebounceTime = level.time + 200; // Modify Magnitude By Hit Percent And Toughness Against Other //------------------------------------------------------------- if (pSelfVeh->m_ulFlags & VEH_OUTOFCONTROL) { vehToughnessAgainstOther *= 0.01f; // If Out Of Control, No Damage Resistance } else { if (vehPilotedByPlayer) { vehToughnessAgainstOther *= 1.5f; } if (other && other->client) { vehToughnessAgainstOther *= 15.0f; // Very Tough against other clients (NPCS, Player, etc) } } if (vehToughnessAgainstOther>0.0f) { magnitude *= (vehHitPercent / vehToughnessAgainstOther); } else { magnitude *= vehHitPercent; } // If We Hit Architecture //------------------------ if (!other || !other->client) { // Turbo Hurts //------------- if (vehInTurbo) { magnitude *= 5.0f; } else if (trace->plane.normal[2]>0.75f && vehHitPercent<0.2f) { magnitude /= 10.0f; } // If No Pilot, Blow This Thing Now //---------------------------------- if (vehHitPercent>0.9f && !pSelfVeh->m_pPilot && vehSpeed>1000.0f) { vehDFlags |= DAMAGE_IMPACT_DIE; } // If Out Of Control, And We Hit A Wall Or Landed Or Head On //------------------------------------------------------------ if ((pSelfVeh->m_ulFlags&VEH_OUTOFCONTROL) && (vehHitPercent>0.5f || trace->plane.normal[2]<0.5f || velocity[2]<-50.0f)) { vehDFlags |= DAMAGE_IMPACT_DIE; } // If This Is A Direct Impact (Debounced By 4 Seconds) //----------------------------------------------------- if (vehHitPercent>0.9f && (level.time - self->lastImpact)>2000 && vehSpeed>300.0f) { self->lastImpact = level.time; // The Player Has Harder Requirements to Explode //----------------------------------------------- if (vehPilotedByPlayer) { if ((vehHitPercent>0.99f && vehSpeed>1000.0f && !Q_irand(0,30)) || (vehHitPercent>0.999f && vehInTurbo)) { vehDFlags |= DAMAGE_IMPACT_DIE; } } else if (player && G_IsRidingVehicle(player) && (Distance(self->currentOrigin, player->currentOrigin)<800.0f) && (vehInTurbo || !Q_irand(0,1) || vehHitPercent>0.999f)) { vehDFlags |= DAMAGE_IMPACT_DIE; } } // Make Sure He Dies This Time. I will accept no excuses. //--------------------------------------------------------- if (vehDFlags&DAMAGE_IMPACT_DIE) { // If close enough To The PLayer if (player && G_IsRidingVehicle(player) && self->owner && Distance(self->currentOrigin, player->currentOrigin)<500.0f) { player->lastEnemy = self->owner; G_StartMatrixEffect(player, MEF_LOOK_AT_ENEMY|MEF_NO_RANGEVAR|MEF_NO_VERTBOB|MEF_NO_SPIN, 1000); } magnitude = 100000.0f; } } if (magnitude>10.0f) { // Play The Impact Effect //------------------------ if (pSelfVeh->m_pVehicleInfo->iImpactFX && vehSpeed>100.0f) { G_PlayEffect( pSelfVeh->m_pVehicleInfo->iImpactFX, self->currentOrigin, trace->plane.normal ); } // Set The Crashing Flag And Pain Debounce Time //---------------------------------------------- pSelfVeh->m_ulFlags |= VEH_CRASHING; } G_Damage( self, player, player, NULL, self->currentOrigin, magnitude, vehDFlags, MOD_FALLING );//FIXME: MOD_IMPACT } if ( self->owner == other || self->activator == other ) {//hit owner/activator if ( self->m_pVehicle && !self->m_pVehicle->m_pVehicleInfo->Inhabited( self->m_pVehicle ) ) {//empty swoop if ( self->client->respawnTime - level.time < 1000 ) {//just spawned in a second ago //don't actually damage or throw him... vehicleHitOwner = qtrue; } } } //if 2 vehicles on same side hit each other, tone it down //NOTE: we do this here because we still want the impact effect if ( pOtherVeh ) { if ( self->client->playerTeam == other->client->playerTeam ) { magnitude /= 25; } } } else if ( self->client && (PM_InKnockDown( &self->client->ps )||(self->client->ps.eFlags&EF_FORCE_GRIPPED)) && magnitude >= 120 ) {//FORCE-SMACKED into something if ( TIMER_Done( self, "impactEffect" ) ) { G_PlayEffect( G_EffectIndex( "env/impact_dustonly" ), trace->endpos, trace->plane.normal ); G_Sound( self, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); TIMER_Set( self, "impactEffect", 1000 ); } } //damage them if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD ) { VectorCopy( velocity, dir1 ); VectorNormalize( dir1 ); if( VectorCompare( other->currentOrigin, vec3_origin ) ) {//a brush with no origin VectorCopy ( dir1, dir2 ); } else { VectorSubtract( other->currentOrigin, self->currentOrigin, dir2 ); VectorNormalize( dir2 ); } dot = DotProduct( dir1, dir2 ); if ( dot >= 0.2 ) { force = dot; } else { force = 0; } force *= (magnitude/50); int cont = gi.pointcontents( other->absmax, other->s.number ); if( (cont&CONTENTS_WATER) ) {//water absorbs 2/3 velocity force *= 0.33333f; } if ( self->NPC && other->s.number == ENTITYNUM_WORLD ) {//NPCs take less damage force *= 0.5f; } if ( self->s.number >= MAX_CLIENTS && self->client && (PM_InKnockDown( &self->client->ps )||self->client->ps.eFlags&EF_FORCE_GRIPPED) ) {//NPC: I was knocked down or being gripped, impact should be harder //FIXME: what if I was just thrown - force pushed/pulled or thrown from a grip? force *= 10; } //FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. if ( pOtherVeh ) {//if hit another vehicle, take their toughness into account, too force /= pOtherVeh->m_pVehicleInfo->toughness; } if( ( (force >= 1 || pSelfVeh) && other->s.number>=MAX_CLIENTS ) || force >= 10) { /* dprint("Damage other ("); dprint(loser.classname); dprint("): "); dprint(ftos(force)); dprint("\n"); */ if ( other->svFlags & SVF_GLASS_BRUSH ) { other->splashRadius = (float)(self->maxs[0] - self->mins[0])/4.0f; } if ( pSelfVeh ) {//if in a vehicle when land on someone, always knockdown, throw, damage if ( !vehicleHitOwner ) {//didn't hit owner // If the player was hit don't make the damage so bad... if ( other && other->s.number<MAX_CLIENTS ) { force *= 0.5f; } //Hmm, maybe knockdown? if ( !(other->flags&FL_NO_KNOCKBACK) ) { G_Throw( other, dir2, force ); } G_Knockdown( other, self, dir2, force, qtrue ); G_Damage( other, self, self, velocity, self->currentOrigin, force, DAMAGE_NO_ARMOR|DAMAGE_EXTRA_KNOCKBACK, MOD_IMPACT ); } } else if ( self->forcePushTime > level.time - 1000//was force pushed/pulled in the last 1600 milliseconds && self->forcePuller == other->s.number )//hit the person who pushed/pulled me {//ignore the impact } else if ( other->takedamage ) { if ( !self->client || other->s.number<MAX_CLIENTS || !other->client ) {//aw, fuck it, clients no longer take impact damage from other clients, unless you're the player if ( other->client //he's a client && self->client //I'm a client && other->client->ps.forceGripEntityNum == self->s.number )//he's force-gripping me {//don't damage the other guy if he's gripping me } else { G_Damage( other, self, self, velocity, self->currentOrigin, floor(force), DAMAGE_NO_ARMOR, MOD_IMPACT ); } } else { GEntity_PainFunc( other, self, self, self->currentOrigin, force, MOD_IMPACT ); //Hmm, maybe knockdown? if (!thrown) { if ( !(other->flags&FL_NO_KNOCKBACK) ) { G_Throw( other, dir2, force ); } } } if ( other->health > 0 ) {//still alive? //TODO: if someone was thrown through the air (in a knockdown or being gripped) // and they hit me hard enough, knock me down if ( other->client ) { if ( self->client ) { if ( PM_InKnockDown( &self->client->ps ) || (self->client->ps.eFlags&EF_FORCE_GRIPPED) ) { G_Knockdown( other, self, dir2, Q_irand( 200, 400 ), qtrue ); } } else if ( self->forcePuller != ENTITYNUM_NONE && g_entities[self->forcePuller].client && self->mass > Q_irand( 50, 100 ) ) { G_Knockdown( other, &g_entities[self->forcePuller], dir2, Q_irand( 200, 400 ), qtrue ); } } } } else { //Hmm, maybe knockdown? if (!thrown) { if ( !(other->flags&FL_NO_KNOCKBACK) ) { G_Throw( other, dir2, force ); } } } } } if ( damageSelf && self->takedamage && !(self->flags&FL_NO_IMPACT_DMG)) { //Now damage me //FIXME: more lenient falling damage, especially for when driving a vehicle if ( pSelfVeh && self->client->ps.forceJumpZStart ) {//we were force-jumping if ( self->currentOrigin[2] >= self->client->ps.forceJumpZStart ) {//we landed at same height or higher than we landed magnitude = 0; } else {//FIXME: take off some of it, at least? magnitude = (self->client->ps.forceJumpZStart-self->currentOrigin[2])/3; } } if( ( magnitude >= 100 + self->health && self->s.number >= MAX_CLIENTS && self->s.weapon != WP_SABER ) || self->client->NPC_class == CLASS_VEHICLE || ( magnitude >= 700 ) )//health here is used to simulate structural integrity { if ( (self->s.weapon == WP_SABER || self->s.number<MAX_CLIENTS || (self->client&&(self->client->NPC_class==CLASS_BOBAFETT||self->client->NPC_class==CLASS_ROCKETTROOPER))) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 ) {//players and jedi take less impact damage //allow for some lenience on high falls magnitude /= 2; } //drop it some (magic number... sigh) magnitude /= 40; //If damage other, subtract half of that damage off of own injury if ( other->bmodel && other->material != MAT_GLASS ) {//take off only a little because we broke architecture (not including glass), that should hurt magnitude = magnitude - force/8; } else {//take off half damage we did to it magnitude = magnitude - force/2; } if ( pSelfVeh ) { //FIXME: if hit another vehicle, take their toughness into // account, too? Or should their toughness only matter // when they hit me? magnitude /= pSelfVeh->m_pVehicleInfo->toughness * 1000.0f; if ( other->bmodel && other->material != MAT_GLASS ) {//broke through some architecture, take a good amount of damage } else if ( pOtherVeh ) {//they're tougher //magnitude /= 4.0f;//FIXME: get the toughness of other from vehicles.cfg } else {//take some off because of give //NOTE: this covers all other entities and impact with world... //FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. magnitude /= 10.0f; } if ( magnitude < 1.0f ) { magnitude = 0; } } if ( magnitude >= 1 ) { //FIXME: Put in a thingtype impact sound function /* dprint("Damage self ("); dprint(self.classname); dprint("): "); dprint(ftos(magnitude)); dprint("\n"); */ if ( self->NPC && self->s.weapon == WP_SABER ) {//FIXME: for now Jedi take no falling damage, but really they should if pushed off? magnitude = 0; } G_Damage( self, NULL, NULL, NULL, self->currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT } } } //FIXME: slow my velocity some? /* if(self.flags&FL_ONGROUND) self.last_onground=time; */ } } /* ============== ClientImpacts ============== */ void ClientImpacts( gentity_t *ent, pmove_t *pm ) { int i, j; trace_t trace; gentity_t *other; memset( &trace, 0, sizeof( trace ) ); for (i=0 ; i<pm->numtouch ; i++) { for (j=0 ; j<i ; j++) { if (pm->touchents[j] == pm->touchents[i] ) { break; } } if (j != i) { continue; // duplicated } other = &g_entities[ pm->touchents[i] ]; if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { // last check unneccessary GEntity_TouchFunc( ent, other, &trace ); } if ( other->e_TouchFunc == touchF_NULL ) { // not needed, but I'll leave it I guess (cache-hit issues) continue; } GEntity_TouchFunc( other, ent, &trace ); } } /* ============ G_TouchTriggersLerped Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. This version checks at 6 unit steps between last and current origins ============ */ void G_TouchTriggersLerped( gentity_t *ent ) { int i, num; float dist, curDist = 0; gentity_t *touch[MAX_GENTITIES], *hit; trace_t trace; vec3_t end, mins, maxs, diff; const vec3_t range = { 40, 40, 52 }; qboolean touched[MAX_GENTITIES]; qboolean done = qfalse; if ( !ent->client ) { return; } // dead NPCs don't activate triggers! if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { if ( ent->s.number>=MAX_CLIENTS ) { return; } } #ifdef _DEBUG for ( int j = 0; j < 3; j++ ) { assert( !Q_isnan(ent->currentOrigin[j])); assert( !Q_isnan(ent->lastOrigin[j])); } #endif// _DEBUG VectorSubtract( ent->currentOrigin, ent->lastOrigin, diff ); dist = VectorNormalize( diff ); #ifdef _DEBUG assert( (dist<1024) && "insane distance in G_TouchTriggersLerped!" ); #endif// _DEBUG if ( dist > 1024 ) { return; } memset (touched, qfalse, sizeof(touched) ); for ( curDist = 0; !done && ent->maxs[1]>0; curDist += (float)ent->maxs[1]/2.0f ) { if ( curDist >= dist ) { VectorCopy( ent->currentOrigin, end ); done = qtrue; } else { VectorMA( ent->lastOrigin, curDist, diff, end ); } VectorSubtract( end, range, mins ); VectorAdd( end, range, maxs ); num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); // can't use ent->absmin, because that has a one unit pad VectorAdd( end, ent->mins, mins ); VectorAdd( end, ent->maxs, maxs ); for ( i=0 ; i<num ; i++ ) { hit = touch[i]; if ( (hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { continue; } if ( !( hit->contents & CONTENTS_TRIGGER ) ) { continue; } if ( touched[i] == qtrue ) { continue;//already touched this move } if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { if ( Q_stricmp( "trigger_teleport", hit->classname ) || !(hit->spawnflags&16/*TTSF_DEAD_OK*/) ) {//dead clients can only touch tiogger_teleports that are marked as touchable continue; } } // use seperate code for determining if an item is picked up // so you don't have to actually contact its bounding box /* if ( hit->s.eType == ET_ITEM ) { if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) { continue; } } else */ { if ( !gi.EntityContact( mins, maxs, hit ) ) { continue; } } touched[i] = qtrue; memset( &trace, 0, sizeof(trace) ); if ( hit->e_TouchFunc != touchF_NULL ) { GEntity_TouchFunc(hit, ent, &trace); } //WTF? Why would a trigger ever fire off the NPC's touch func??!!! /* if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { GEntity_TouchFunc( ent, hit, &trace ); } */ } } } /* ============ G_TouchTriggers Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ void G_TouchTriggers( gentity_t *ent ) { int i, num; gentity_t *touch[MAX_GENTITIES], *hit; trace_t trace; vec3_t mins, maxs; const vec3_t range = { 40, 40, 52 }; if ( !ent->client ) { return; } // dead clients don't activate triggers! if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { return; } VectorSubtract( ent->client->ps.origin, range, mins ); VectorAdd( ent->client->ps.origin, range, maxs ); num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); // can't use ent->absmin, because that has a one unit pad VectorAdd( ent->client->ps.origin, ent->mins, mins ); VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); for ( i=0 ; i<num ; i++ ) { hit = touch[i]; if ( (hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { continue; } if ( !( hit->contents & CONTENTS_TRIGGER ) ) { continue; } // use seperate code for determining if an item is picked up // so you don't have to actually contact its bounding box /* if ( hit->s.eType == ET_ITEM ) { if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) { continue; } } else */ { if ( !gi.EntityContact( mins, maxs, hit ) ) { continue; } } memset( &trace, 0, sizeof(trace) ); if ( hit->e_TouchFunc != touchF_NULL ) { GEntity_TouchFunc(hit, ent, &trace); } if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { GEntity_TouchFunc( ent, hit, &trace ); } } } /* ============ G_MoverTouchTriggers Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ) { int i, num; float step, stepSize, dist; gentity_t *touch[MAX_GENTITIES], *hit; trace_t trace; vec3_t mins, maxs, dir, size, checkSpot; const vec3_t range = { 40, 40, 52 }; // non-moving movers don't hit triggers! if ( !VectorLengthSquared( ent->s.pos.trDelta ) ) { return; } VectorSubtract( ent->mins, ent->maxs, size ); stepSize = VectorLength( size ); if ( stepSize < 1 ) { stepSize = 1; } VectorSubtract( ent->currentOrigin, oldOrg, dir ); dist = VectorNormalize( dir ); for ( step = 0; step <= dist; step += stepSize ) { VectorMA( ent->currentOrigin, step, dir, checkSpot ); VectorSubtract( checkSpot, range, mins ); VectorAdd( checkSpot, range, maxs ); num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); // can't use ent->absmin, because that has a one unit pad VectorAdd( checkSpot, ent->mins, mins ); VectorAdd( checkSpot, ent->maxs, maxs ); for ( i=0 ; i<num ; i++ ) { hit = touch[i]; if ( hit->s.eType != ET_PUSH_TRIGGER ) { continue; } if ( hit->e_TouchFunc == touchF_NULL ) { continue; } if ( !( hit->contents & CONTENTS_TRIGGER ) ) { continue; } if ( !gi.EntityContact( mins, maxs, hit ) ) { continue; } memset( &trace, 0, sizeof(trace) ); if ( hit->e_TouchFunc != touchF_NULL ) { GEntity_TouchFunc(hit, ent, &trace); } } } } void G_MatchPlayerWeapon( gentity_t *ent ) { if ( g_entities[0].inuse && g_entities[0].client ) {//player is around int newWeap; if ( g_entities[0].client->ps.weapon > WP_CONCUSSION ) { newWeap = WP_BLASTER_PISTOL; } else { newWeap = g_entities[0].client->ps.weapon; } if ( newWeap != WP_NONE && ent->client->ps.weapon != newWeap ) { G_RemoveWeaponModels( ent ); ent->client->ps.stats[STAT_WEAPONS] = ( 1 << newWeap ); ent->client->ps.ammo[weaponData[newWeap].ammoIndex] = 999; ChangeWeapon( ent, newWeap ); ent->client->ps.weapon = newWeap; ent->client->ps.weaponstate = WEAPON_READY; if ( newWeap == WP_SABER ) { //FIXME: AddSound/Sight Event int numSabers = WP_SaberInitBladeData( ent ); WP_SaberAddG2SaberModels( ent ); for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) { //G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[saberNum].model, ent->handRBolt, 0 ); ent->client->ps.saber[saberNum].type = g_entities[0].client->ps.saber[saberNum].type; for ( int bladeNum = 0; bladeNum < ent->client->ps.saber[saberNum].numBlades; bladeNum++ ) { ent->client->ps.saber[saberNum].blade[0].active = g_entities[0].client->ps.saber[saberNum].blade[bladeNum].active; ent->client->ps.saber[saberNum].blade[0].length = g_entities[0].client->ps.saber[saberNum].blade[bladeNum].length; } } ent->client->ps.saberAnimLevel = g_entities[0].client->ps.saberAnimLevel; ent->client->ps.saberStylesKnown = g_entities[0].client->ps.saberStylesKnown; } else { G_CreateG2AttachedWeaponModel( ent, weaponData[newWeap].weaponMdl, ent->handRBolt, 0 ); } } } } void G_NPCMunroMatchPlayerWeapon( gentity_t *ent ) { //special uber hack for cinematic players to match player's weapon if ( !in_camera ) { if ( ent && ent->client && ent->NPC && (ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON) ) {//we're a Player NPC G_MatchPlayerWeapon( ent ); } } } /* ================== ClientTimerActions Actions that happen once a second ================== */ void ClientTimerActions( gentity_t *ent, int msec ) { gclient_t *client; client = ent->client; client->timeResidual += msec; while ( client->timeResidual >= 1000 ) { client->timeResidual -= 1000; if ( ent->s.weapon != WP_NONE ) { ent->client->sess.missionStats.weaponUsed[ent->s.weapon]++; } // if we've got the seeker powerup, see if we can shoot it at someone /* if ( ent->client->ps.powerups[PW_SEEKER] > level.time ) { vec3_t seekerPos, dir; gentity_t *enemy = SeekerAcquiresTarget( ent, seekerPos ); if ( enemy != NULL ) // set the client's enemy to a valid target { FireSeeker( ent, enemy, seekerPos, dir ); gentity_t *tent; tent = G_TempEntity( seekerPos, EV_POWERUP_SEEKER_FIRE ); VectorCopy( dir, tent->pos1 ); tent->s.eventParm = ent->s.number; } }*/ if ( (ent->flags&FL_OVERCHARGED_HEALTH) ) {//need to gradually reduce health back to max if ( ent->health > ent->client->ps.stats[STAT_MAX_HEALTH] ) {//decrement it ent->health--; ent->client->ps.stats[STAT_HEALTH] = ent->health; } else {//done ent->flags &= ~FL_OVERCHARGED_HEALTH; } } } } /* ==================== ClientIntermissionThink ==================== */ static qboolean ClientCinematicThink( gclient_t *client ) { client->ps.eFlags &= ~EF_FIRING; // swap button actions client->oldbuttons = client->buttons; client->buttons = client->usercmd.buttons; if ( client->buttons & ( BUTTON_USE ) & ( client->oldbuttons ^ client->buttons ) ) { return( qtrue ); } return( qfalse ); } /* ================ ClientEvents Events will be passed on to the clients for presentation, but any server game effects are handled here ================ */ extern void WP_SabersDamageTrace( gentity_t *ent, qboolean noEffects = qfalse ); extern void WP_SaberUpdateOldBladeData( gentity_t *ent ); void ClientEvents( gentity_t *ent, int oldEventSequence ) { int i; int event; gclient_t *client; //int damage; #ifndef FINAL_BUILD qboolean fired = qfalse; #endif client = ent->client; for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) { event = client->ps.events[ i & (MAX_PS_EVENTS-1) ]; switch ( event ) { case EV_FALL_MEDIUM: case EV_FALL_FAR://these come from bg_pmove, PM_CrashLand if ( ent->s.eType != ET_PLAYER ) { break; // not in the player model } /* //FIXME: isn't there a more accurate way to calculate damage from falls? if ( event == EV_FALL_FAR ) { damage = 50; } else { damage = 25; } ent->painDebounceTime = level.time + 200; // no normal pain sound G_Damage (ent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING); */ break; case EV_FIRE_WEAPON: #ifndef FINAL_BUILD if ( fired ) { gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); } fired = qtrue; #endif FireWeapon( ent, qfalse ); break; case EV_ALT_FIRE: #ifndef FINAL_BUILD if ( fired ) { gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); } fired = qtrue; #endif FireWeapon( ent, qtrue ); break; default: break; } } //by the way, if you have your saber in hand and it's on, do the damage trace if ( client->ps.weapon == WP_SABER ) { if ( g_timescale->value >= 1.0f || !(client->ps.forcePowersActive&(1<<FP_SPEED)) ) { int wait = FRAMETIME/2; //sanity check if ( client->ps.saberDamageDebounceTime - level.time > wait ) {//when you unpause the game with force speed on, the time gets *really* wiggy... client->ps.saberDamageDebounceTime = level.time + wait; } if ( client->ps.saberDamageDebounceTime <= level.time ) { WP_SabersDamageTrace( ent ); WP_SaberUpdateOldBladeData( ent ); /* if ( g_timescale->value&&client->ps.clientNum==0&&!player_locked&&!MatrixMode&&client->ps.forcePowersActive&(1<<FP_SPEED) ) { wait = floor( (float)wait*g_timescale->value ); } */ client->ps.saberDamageDebounceTime = level.time + wait; } } } } void G_ThrownDeathAnimForDeathAnim( gentity_t *hitEnt, vec3_t impactPoint ) { int anim = -1; if ( !hitEnt || !hitEnt->client ) { return; } switch ( hitEnt->client->ps.legsAnim ) { case BOTH_DEATH9://fall to knees, fall over case BOTH_DEATH10://fall to knees, fall over case BOTH_DEATH11://fall to knees, fall over case BOTH_DEATH13://stumble back, fall over case BOTH_DEATH17://jerky fall to knees, fall over case BOTH_DEATH18://grab gut, fall to knees, fall over case BOTH_DEATH19://grab gut, fall to knees, fall over case BOTH_DEATH20://grab shoulder, fall forward case BOTH_DEATH21://grab shoulder, fall forward case BOTH_DEATH3://knee collapse, twist & fall forward case BOTH_DEATH7://knee collapse, twist & fall forward { vec3_t dir2Impact, fwdAngles, facing; VectorSubtract( impactPoint, hitEnt->currentOrigin, dir2Impact ); dir2Impact[2] = 0; VectorNormalize( dir2Impact ); VectorSet( fwdAngles, 0, hitEnt->client->ps.viewangles[YAW], 0 ); AngleVectors( fwdAngles, facing, NULL, NULL ); float dot = DotProduct( facing, dir2Impact );//-1 = hit in front, 0 = hit on side, 1 = hit in back if ( dot > 0.5f ) {//kicked in chest, fly backward switch ( Q_irand( 0, 4 ) ) {//FIXME: don't start at beginning of anim? case 0: anim = BOTH_DEATH1;//thrown backwards break; case 1: anim = BOTH_DEATH2;//fall backwards break; case 2: anim = BOTH_DEATH15;//roll over backwards break; case 3: anim = BOTH_DEATH22;//fast fall back break; case 4: anim = BOTH_DEATH23;//fast fall back break; } } else if ( dot < -0.5f ) {//kicked in back, fly forward switch ( Q_irand( 0, 5 ) ) {//FIXME: don't start at beginning of anim? case 0: anim = BOTH_DEATH14; break; case 1: anim = BOTH_DEATH24; break; case 2: anim = BOTH_DEATH25; break; case 3: anim = BOTH_DEATH4;//thrown forwards break; case 4: anim = BOTH_DEATH5;//thrown forwards break; case 5: anim = BOTH_DEATH16;//thrown forwards break; } } else {//hit on side, spin switch ( Q_irand( 0, 2 ) ) {//FIXME: don't start at beginning of anim? case 0: anim = BOTH_DEATH12; break; case 1: anim = BOTH_DEATH14; break; case 2: anim = BOTH_DEATH15; break; case 3: anim = BOTH_DEATH6; break; case 4: anim = BOTH_DEATH8; break; } } } break; } if ( anim != -1 ) { NPC_SetAnim( hitEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t kickEnd, int kickDamage, float kickPush, qboolean doSoundOnWalls ) { vec3_t traceOrg, traceEnd, kickMins={-2,-2,-2}, kickMaxs={2,2,2}; trace_t trace; gentity_t *hitEnt = NULL; //FIXME: variable kick height? if ( kickEnd && !VectorCompare( kickEnd, vec3_origin ) ) {//they passed us the end point of the trace, just use that //this makes the trace flat VectorSet( traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], kickEnd[2] ); VectorCopy( kickEnd, traceEnd ); } else {//extrude VectorSet( traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2]+ent->maxs[2]*0.5f ); VectorMA( traceOrg, kickDist, kickDir, traceEnd ); } gi.trace( &trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 );//clipmask ok? if ( trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid && trace.entityNum < ENTITYNUM_NONE ) { hitEnt = &g_entities[trace.entityNum]; if ( ent->client->ps.lastKickedEntNum != trace.entityNum ) { TIMER_Remove( ent, "kickSoundDebounce" ); ent->client->ps.lastKickedEntNum = trace.entityNum; } if ( hitEnt ) {//we hit an entity if ( hitEnt->client ) { if ( !(hitEnt->client->ps.pm_flags&PMF_TIME_KNOCKBACK) && TIMER_Done( hitEnt, "kickedDebounce" ) )//not already flying through air? Intended to stop multiple hits, but... {//FIXME: this should not always work if ( PM_InKnockDown( &hitEnt->client->ps ) && !PM_InGetUp( &hitEnt->client->ps ) ) {//don't hit people who are knocked down or being knocked down (okay to hit people getting up, though) return NULL; } if ( PM_InRoll( &hitEnt->client->ps ) ) {//can't hit people who are rolling return NULL; } //don't hit same ent more than once per kick if ( hitEnt->takedamage ) {//hurt it G_Damage( hitEnt, ent, ent, kickDir, trace.endpos, kickDamage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_KILL, MOD_MELEE ); } //do kick hit sound and impact effect if ( TIMER_Done( ent, "kickSoundDebounce" ) ) { if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) { G_Sound( ent, G_SoundIndex( "sound/movers/objects/saber_slam" ) ); } else { vec3_t fxOrg, fxDir; VectorCopy( kickDir, fxDir ); VectorMA( trace.endpos, Q_flrand( 5.0f, 10.0f ), fxDir, fxOrg ); VectorScale( fxDir, -1, fxDir ); G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), fxOrg, fxDir ); //G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); } TIMER_Set( ent, "kickSoundDebounce", 2000 ); } TIMER_Set( hitEnt, "kickedDebounce", 1000 ); if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) {//hit in head if ( hitEnt->health > 0 ) {//knock down if ( kickPush >= 150.0f/*75.0f*/ && !Q_irand( 0, 1 ) ) {//knock them down if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush/3.0f ); } G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); } else {//force them to play a pain anim if ( hitEnt->s.number < MAX_CLIENTS ) { NPC_SetPainEvent( hitEnt ); } else { GEntity_PainFunc( hitEnt, ent, ent, hitEnt->currentOrigin, 0, MOD_MELEE ); } } //just so we don't hit him again... hitEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; hitEnt->client->ps.pm_time = 100; } else { if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush ); } //see if we should play a better looking death on them G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); } } else if ( ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_BROLL_F || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_F ) { if ( hitEnt->health > 0 ) {//knock down if ( hitEnt->client->ps.groundEntityNum == ENTITYNUM_NONE ) {//he's in the air? Send him flying back if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush ); } } else { //just so we don't hit him again... hitEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; hitEnt->client->ps.pm_time = 100; } //knock them down G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); } else { if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush ); } //see if we should play a better looking death on them G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); } } else if ( hitEnt->health <= 0 ) {//we kicked a dead guy //throw harder - FIXME: no matter how hard I push them, they don't go anywhere... corpses use less physics??? if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush*4 ); } //see if we should play a better looking death on them G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); } else { if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) { G_Throw( hitEnt, kickDir, kickPush ); } if ( kickPush >= 150.0f/*75.0f*/ && !Q_irand( 0, 2 ) ) { G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); } else { G_Knockdown( hitEnt, ent, kickDir, kickPush, qtrue ); } } } } else {//FIXME: don't do this in repeated frames... only allow 1 frame in kick to hit wall? The most extended one? Pass in a bool on that frame. if ( doSoundOnWalls ) {//do kick hit sound and impact effect if ( TIMER_Done( ent, "kickSoundDebounce" ) ) { if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) { G_Sound( ent, G_SoundIndex( "sound/movers/objects/saber_slam" ) ); } else { G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), trace.endpos, trace.plane.normal ); //G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); } TIMER_Set( ent, "kickSoundDebounce", 2000 ); } } } } } return (hitEnt); } qboolean G_CheckRollSafety( gentity_t *self, int anim, float testDist ) { vec3_t forward, right, testPos, angles; trace_t trace; int contents = (CONTENTS_SOLID|CONTENTS_BOTCLIP); if ( !self || !self->client ) { return qfalse; } if ( self->s.number < MAX_CLIENTS ) {//player contents |= CONTENTS_PLAYERCLIP; } else {//NPC contents |= CONTENTS_MONSTERCLIP; } if ( PM_InAttackRoll( self->client->ps.legsAnim ) ) {//we don't care if people are in the way, we'll knock them down! contents &= ~CONTENTS_BODY; } angles[PITCH] = angles[ROLL] = 0; angles[YAW] = self->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? AngleVectors( angles, forward, right, NULL ); switch ( anim ) { case BOTH_GETUP_BROLL_R: case BOTH_GETUP_FROLL_R: VectorMA( self->currentOrigin, testDist, right, testPos ); break; case BOTH_GETUP_BROLL_L: case BOTH_GETUP_FROLL_L: VectorMA( self->currentOrigin, -testDist, right, testPos ); break; case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_F: VectorMA( self->currentOrigin, testDist, forward, testPos ); break; case BOTH_GETUP_BROLL_B: case BOTH_GETUP_FROLL_B: VectorMA( self->currentOrigin, -testDist, forward, testPos ); break; default://FIXME: add normal rolls? Make generic for any forced-movement anim? return qtrue; break; } gi.trace( &trace, self->currentOrigin, self->mins, self->maxs, testPos, self->s.number, contents, (EG2_Collision)0, 0 ); if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) {//inside something or will hit something return qfalse; } return qtrue; } void G_CamPullBackForLegsAnim( gentity_t *ent, qboolean useTorso = qfalse ) { if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) ) { float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (useTorso?(animNumber_t)ent->client->ps.torsoAnim:(animNumber_t)ent->client->ps.legsAnim) ); float elapsedTime = (float)(animLength-(useTorso?ent->client->ps.torsoAnimTimer:ent->client->ps.legsAnimTimer)); float backDist = 0; if ( elapsedTime < animLength/2.0f ) {//starting anim backDist = (elapsedTime/animLength)*120.0f; } else {//ending anim backDist = ((animLength-elapsedTime)/animLength)*120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; } } void G_CamCircleForLegsAnim( gentity_t *ent ) { if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) ) { float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ); float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); float angle = 0; angle = (elapsedTime/animLength)*360.0f; cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; } } qboolean G_GrabClient( gentity_t *ent, usercmd_t *ucmd ) { gentity_t *bestEnt = NULL, *radiusEnts[ 128 ]; int numEnts; const float radius = 100.0f; const float radiusSquared = (radius*radius); float bestDistSq = (radiusSquared+1.0f), distSq; int i; vec3_t boltOrg; numEnts = G_GetEntsNearBolt( ent, radiusEnts, radius, ent->handRBolt, boltOrg ); for ( i = 0; i < numEnts; i++ ) { if ( !radiusEnts[i]->inuse ) { continue; } if ( radiusEnts[i] == ent ) {//Skip the rancor ent continue; } if ( !radiusEnts[i]->inuse || radiusEnts[i]->health <= 0 ) {//must be alive continue; } if ( radiusEnts[i]->client == NULL ) {//must be a client continue; } if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) ||(radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) ||(radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) ) {//can't be one being held continue; } if ( PM_LockedAnim( radiusEnts[i]->client->ps.torsoAnim ) || PM_LockedAnim( radiusEnts[i]->client->ps.legsAnim ) ) {//don't interrupt continue; } if ( radiusEnts[i]->client->ps.groundEntityNum == ENTITYNUM_NONE ) {//must be on ground continue; } if ( PM_InOnGroundAnim( &radiusEnts[i]->client->ps ) ) {//must be standing up continue; } if ( fabs(radiusEnts[i]->currentOrigin[2]-ent->currentOrigin[2])>8.0f ) {//have to be close in Z continue; } if ( !PM_HasAnimation( radiusEnts[i], BOTH_PLAYER_PA_1 ) ) {//doesn't have matching anims continue; } distSq = DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ); if ( distSq < bestDistSq ) { bestDistSq = distSq; bestEnt = radiusEnts[i]; } } if ( bestEnt != NULL ) { int lockType = LOCK_KYLE_GRAB1; if ( ucmd->forwardmove > 0 ) { lockType = LOCK_KYLE_GRAB3; } else if ( ucmd->forwardmove < 0 ) { lockType = LOCK_KYLE_GRAB2; } WP_SabersCheckLock2( ent, bestEnt, (sabersLockMode_t)lockType ); return qtrue; } return qfalse; } qboolean G_PullAttack( gentity_t *ent, usercmd_t *ucmd ) { qboolean overridAngles = qfalse; if ( ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB || ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING ) {//pulling if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } else if ( ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_B || ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_F ) {//being pulled gentity_t *puller = &g_entities[ent->client->ps.pullAttackEntNum]; if ( puller && puller->inuse && puller->client && ( puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB || puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING ) ) { vec3_t pullDir; vec3_t pullPos; //calc where to pull me to /* VectorCopy( puller->client->ps.saber[0].blade[0].muzzlePoint, pullPos ); VectorMA( pullPos, puller->client->ps.saber[0].blade[0].length*0.5f, puller->client->ps.saber[0].blade[0].muzzleDir, pullPos ); */ vec3_t pullerFwd; AngleVectors( puller->client->ps.viewangles, pullerFwd, NULL, NULL ); VectorMA( puller->currentOrigin, (puller->maxs[0]*1.5f)+16.0f, pullerFwd, pullPos ); //pull me towards that pos VectorSubtract( pullPos, ent->currentOrigin, pullDir ); float pullDist = VectorNormalize( pullDir ); int sweetSpotTime = (puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB)?1250:1350; float pullLength = PM_AnimLength( puller->client->clientInfo.animFileIndex, (animNumber_t)puller->client->ps.torsoAnim )-sweetSpotTime; if ( pullLength <= 0.25f ) { pullLength = 0.25f; } //float pullTimeRemaining = ent->client->ps.pullAttackTime - level.time; //float pullSpeed = pullDist * (pullTimeRemaining/pullLength); float pullSpeed = (pullDist*1000.0f)/pullLength; VectorScale( pullDir, pullSpeed, ent->client->ps.velocity ); //slide, if necessary ent->client->ps.pm_flags |= PMF_TIME_NOFRICTION; ent->client->ps.pm_time = 100; //make it so I don't actually hurt them when pulled at them... ent->forcePuller = puller->s.number; ent->forcePushTime = level.time + 100; // let the push effect last for 100 more ms //look at him PM_AdjustAnglesToPuller( ent, puller, ucmd, qboolean(ent->client->ps.legsAnim==BOTH_PULLED_INAIR_B) ); overridAngles = qtrue; //don't move if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } } return overridAngles; } void G_FixMins( gentity_t *ent ) { //do a trace to make sure it's okay float downdist = (DEFAULT_MINS_2-ent->mins[2]); vec3_t end={ent->currentOrigin[0],ent->currentOrigin[1],ent->currentOrigin[2]+downdist}; trace_t trace; gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); if ( !trace.allsolid && !trace.startsolid ) { if ( trace.fraction >= 1.0f ) {//all clear //drop the bottom of my bbox back down ent->mins[2] = DEFAULT_MINS_2; if ( ent->client ) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } } else {//move me up so the bottom of my bbox will be where the trace ended, at least //need to trace up, too float updist = ((1.0f-trace.fraction) * -downdist); end[2] = ent->currentOrigin[2]+updist; gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); if ( !trace.allsolid && !trace.startsolid ) { if ( trace.fraction >= 1.0f ) {//all clear //move me up ent->currentOrigin[2] += updist; //drop the bottom of my bbox back down ent->mins[2] = DEFAULT_MINS_2; G_SetOrigin( ent, ent->currentOrigin ); gi.linkentity( ent ); if ( ent->client ) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } } else {//crap, no room to expand! if ( ent->client->ps.legsAnimTimer <= 200 ) {//at the end of the anim, and we can't leave ourselves like this //so drop the maxs, put the mins back and move us up ent->maxs[2] += downdist; ent->currentOrigin[2] -= downdist; ent->mins[2] = DEFAULT_MINS_2; G_SetOrigin( ent, ent->currentOrigin ); gi.linkentity( ent ); //this way we'll be in a crouch when we're done ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; ent->client->ps.pm_flags |= PMF_DUCKED; //FIXME: do we need to set a crouch anim here? if ( ent->client ) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } } } }//crap, stuck } }//crap, stuck! } qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) { qboolean overridAngles = qfalse; if ( ent->client->NPC_class == CLASS_PROTOCOL || ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_GONK || ent->client->NPC_class == CLASS_MOUSE ) {//these droids *cannot* strafe (looks bad) if ( ucmd->rightmove ) { //clear the strafe ucmd->rightmove = 0; //movedir is invalid now, but PM_WalkMove will rebuild it from the ucmds, with the appropriate speed VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.pullAttackEntNum < ENTITYNUM_WORLD && ent->client->ps.pullAttackTime > level.time ) { return G_PullAttack( ent, ucmd ); } if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) && ent->s.weapon == WP_MELEE && ent->client->ps.torsoAnim == BOTH_KYLE_GRAB ) {//see if we grabbed enemy if ( ent->client->ps.torsoAnimTimer <= 200 ) {//close to end of anim if ( G_GrabClient( ent, ucmd ) ) {//grabbed someone! } else {//missed NPC_SetAnim( ent, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; } } ucmd->rightmove = ucmd->forwardmove = ucmd->upmove = 0; } if ( (!ent->s.number&&ent->aimDebounceTime>level.time) || (ent->client->ps.pm_time && (ent->client->ps.pm_flags&PMF_TIME_KNOCKBACK)) || ent->forcePushTime > level.time ) {//being knocked back, can't do anything! ucmd->buttons = 0; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } } overridAngles = (PM_AdjustAnglesForKnockdown( ent, ucmd, qfalse )?qtrue:overridAngles); if ( PM_GetupAnimNoMove( ent->client->ps.legsAnim ) ) { ucmd->forwardmove = ucmd->rightmove = 0;//ucmd->upmove = ? } //check saberlock if ( ent->client->ps.saberLockTime > level.time ) {//in saberlock ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->client->ps.saberLockTime - level.time > SABER_LOCK_DELAYED_TIME ) {//2 second delay before either can push //FIXME: base on difficulty ucmd->buttons = 0; } else { ucmd->buttons &= ~(ucmd->buttons&~BUTTON_ATTACK); } overridAngles = (PM_AdjustAnglesForSaberLock( ent, ucmd )?qtrue:overridAngles); if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } } //check force drain if ( (ent->client->ps.forcePowersActive&(1<<FP_DRAIN)) ) {//draining ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS); if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.saberMove == LS_A_LUNGE ) {//can't move during lunge ucmd->rightmove = ucmd->upmove = 0; if ( ent->client->ps.legsAnimTimer > 500 && (ent->s.number || !player_locked) ) { ucmd->forwardmove = 127; } else { ucmd->forwardmove = 0; } if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_ALT && ent->client->ps.legsAnimTimer ) { vec3_t vFwd, fwdAng = {0,ent->currentAngles[YAW],0}; AngleVectors( fwdAng, vFwd, NULL, NULL ); if ( ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) { float savZ = ent->client->ps.velocity[2]; VectorScale( vFwd, 100, ent->client->ps.velocity ); ent->client->ps.velocity[2] = savZ; } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; overridAngles = (PM_AdjustAnglesForWallRunUpFlipAlt( ent, ucmd )?qtrue:overridAngles); } if ( ent->client->ps.saberMove == LS_A_JUMP_T__B_ ) {//can't move during leap if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE || (!ent->s.number && player_locked) ) {//hit the ground ucmd->forwardmove = 0; } ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.saberMove == LS_A_BACKFLIP_ATK && ent->client->ps.legsAnim == BOTH_JUMPATTACK7 ) {//backflip attack if ( ent->client->ps.legsAnimTimer > 800 //not at end && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK7 ) - ent->client->ps.legsAnimTimer >= 400 )//not in beginning {//middle of anim if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//still on ground? vec3_t yawAngles, backDir; //push backwards some? VectorSet( yawAngles, 0, ent->client->ps.viewangles[YAW]+180, 0 ); AngleVectors( yawAngles, backDir, 0, 0 ); VectorScale( backDir, 100, ent->client->ps.velocity ); //jump! ent->client->ps.velocity[2] = 180; ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; //FIXME: NPCs yell? G_AddEvent( ent, EV_JUMP, 0 ); G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); ucmd->upmove = 0;//clear any actual jump command } } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.legsAnim == BOTH_JUMPATTACK6 && ent->client->ps.legsAnimTimer > 0 ) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; //FIXME: don't slide off people/obstacles? if ( ent->client->ps.legsAnimTimer >= 100 //not at end && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 250 )//not in beginning {//middle of anim //push forward ucmd->forwardmove = 127; } if ( (ent->client->ps.legsAnimTimer >= 900 //not at end && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 950 ) //not in beginning || ( ent->client->ps.legsAnimTimer >= 1600 && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 400 ) )//not in beginning {//one of the two jumps if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//still on ground? //jump! ent->client->ps.velocity[2] = 250; ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; //FIXME: NPCs yell? G_AddEvent( ent, EV_JUMP, 0 ); G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); } else {//FIXME: if this is the second jump, maybe we should just stop the anim? } } //else {//disallow turning unless in the middle frame when you're on the ground //overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); } //dynamically reduce bounding box to let character sail over heads of enemies if ( ( ent->client->ps.legsAnimTimer >= 1450 && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 400 ) ||(ent->client->ps.legsAnimTimer >= 400 && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 1100 ) ) {//in a part of the anim that we're pretty much sideways in, raise up the mins ent->mins[2] = 0; ent->client->ps.pm_flags |= PMF_FIX_MINS; } else if ( (ent->client->ps.pm_flags&PMF_FIX_MINS) ) {//drop the mins back down G_FixMins( ent ); } if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } else if ( (ent->client->ps.pm_flags&PMF_FIX_MINS) ) { G_FixMins( ent ); } if ( ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_LEFT ) || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_RIGHT ) || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT && ent->client->ps.saberMove == LS_BUTTERFLY_RIGHT ) || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT && ent->client->ps.saberMove == LS_BUTTERFLY_LEFT ) ) {//forward flip/spin attack ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; /*if ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || ent->client->ps.legsAnim == BOTH_BUTTERFLY RIGHT )*/ { //FIXME: don't slide off people/obstacles? if ( ent->client->ps.legsAnim != BOTH_BUTTERFLY_LEFT && ent->client->ps.legsAnim != BOTH_BUTTERFLY_RIGHT ) { if ( ent->client->ps.legsAnimTimer >= 100 //not at end && PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ) - ent->client->ps.legsAnimTimer >= 250 )//not in beginning {//middle of anim //push forward ucmd->forwardmove = 127; } } if ( ent->client->ps.legsAnimTimer >= 1700 && ent->client->ps.legsAnimTimer < 1800 ) {//one of the two jumps if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//still on ground? //jump! ent->client->ps.velocity[2] = 250; ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; //FIXME: NPCs yell? G_AddEvent( ent, EV_JUMP, 0 ); G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); } else {//FIXME: if this is the second jump, maybe we should just stop the anim? } } //disallow turning unless in the middle frame when you're on the ground //overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); } if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.legsAnim == BOTH_A7_SOULCAL && ent->client->ps.saberMove == LS_STAFF_SOULCAL ) {//forward spinning staff attack ucmd->upmove = 0; if ( PM_CanRollFromSoulCal( &ent->client->ps ) ) { ucmd->upmove = -127; } else { ucmd->rightmove = 0; //FIXME: don't slide off people/obstacles? if ( ent->client->ps.legsAnimTimer >= 2750 ) {//not at end //push forward ucmd->forwardmove = 64; } else { ucmd->forwardmove = 0; } } if ( ent->client->ps.legsAnimTimer >= 2650 && ent->client->ps.legsAnimTimer < 2850 ) {//the jump if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//still on ground? //jump! ent->client->ps.velocity[2] = 250; ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; //FIXME: NPCs yell? G_AddEvent( ent, EV_JUMP, 0 ); G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); } } if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } } if ( ent->client->ps.torsoAnim == BOTH_LK_DL_S_T_SB_1_W ) { G_CamPullBackForLegsAnim( ent, qtrue ); } if ( ent->client->ps.torsoAnim == BOTH_A6_FB || ent->client->ps.torsoAnim == BOTH_A6_LR ) {//can't turn or move during dual attack if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } else if ( ent->client->ps.legsAnim == BOTH_ROLL_STAB ) { if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->client->ps.legsAnimTimer ) { ucmd->upmove = -127; } if ( ent->client->ps.dualSabers && ent->client->ps.saber[1].Active() ) { G_CamPullBackForLegsAnim( ent ); } } else if ( PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) ) {//can't turn during Kyle's grappling if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->client->ps.legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) { PM_CmdForRoll( &ent->client->ps, ucmd ); if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } ent->client->ps.speed = 400; } } else if ( ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_START || ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_HOLD || ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_END || ent->client->ps.legsAnim==BOTH_FORCE_DRAIN_GRABBED ) {//can't turn or move if ( ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent) ) {//player float forceDrainAngle = 90.0f; if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START ) {//starting drain float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); float angle = (elapsedTime/animLength)*forceDrainAngle; cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; } else if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) {//draining cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+forceDrainAngle; } else if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END ) {//ending drain float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); float angle = forceDrainAngle-((elapsedTime/animLength)*forceDrainAngle); cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; } } if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; overridAngles = PM_LockAngles( ent, ucmd )?qtrue:overridAngles; } else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_1 || ent->client->ps.legsAnim==BOTH_PLAYER_PA_2 || ent->client->ps.legsAnim==BOTH_PLAYER_PA_3 || ent->client->ps.legsAnim==BOTH_PLAYER_PA_3_FLY || ent->client->ps.legsAnim==BOTH_KYLE_PA_1 || ent->client->ps.legsAnim==BOTH_KYLE_PA_2 || ent->client->ps.legsAnim==BOTH_KYLE_PA_3 ) {//can't turn during Kyle's grappling if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = PM_AdjustAnglesForGrapple( ent, ucmd )?qtrue:overridAngles; //if ( g_debugMelee->integer ) {//actually do some damage during sequence int damage = 0; int dflags = (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR|DAMAGE_NO_KILL); if ( TIMER_Done( ent, "grappleDamageDebounce" ) ) { switch ( ent->client->ps.legsAnim ) { case BOTH_PLAYER_PA_1: if ( ent->client->ps.legsAnimTimer <= 3150 && ent->client->ps.legsAnimTimer > 3050 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 1, 3 ); } else { damage = Q_irand( 3, 5 ); } } if ( ent->client->ps.legsAnimTimer <= 1150 && ent->client->ps.legsAnimTimer > 10500 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 3, 5 ); } else { damage = Q_irand( 5, 8 ); } } if ( ent->client->ps.legsAnimTimer <= 100 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 5, 8 ); } else { damage = Q_irand( 10, 20 ); } dflags &= ~DAMAGE_NO_KILL; } break; case BOTH_PLAYER_PA_2: if ( ent->client->ps.legsAnimTimer <= 5700 && ent->client->ps.legsAnimTimer > 5600 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 3, 6 ); } else { damage = Q_irand( 7, 10 ); } } if ( ent->client->ps.legsAnimTimer <= 5200 && ent->client->ps.legsAnimTimer > 5100 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 1, 3 ); } else { damage = Q_irand( 3, 5 ); } } if ( ent->client->ps.legsAnimTimer <= 4550 && ent->client->ps.legsAnimTimer > 4450 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 3, 6 ); } else { damage = Q_irand( 10, 15 ); } } if ( ent->client->ps.legsAnimTimer <= 3550 && ent->client->ps.legsAnimTimer > 3450 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 3, 6 ); } else { damage = Q_irand( 10, 20 ); } dflags &= ~DAMAGE_NO_KILL; } break; case BOTH_PLAYER_PA_3: if ( ent->client->ps.legsAnimTimer <= 3800 && ent->client->ps.legsAnimTimer > 3700 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 2, 5 ); } else { damage = Q_irand( 5, 8 ); } } if ( ent->client->ps.legsAnimTimer <= 3100 && ent->client->ps.legsAnimTimer > 3000 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 2, 5 ); } else { damage = Q_irand( 5, 8 ); } } if ( ent->client->ps.legsAnimTimer <= 1650 && ent->client->ps.legsAnimTimer > 1550 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); if ( ent->s.number < MAX_CLIENTS ) {//special case damage = Q_irand( 3, 6 ); } else { damage = Q_irand( 7, 12 ); } } break; case BOTH_PLAYER_PA_3_FLY: /* if ( ent->s.number < MAX_CLIENTS ) {//special case if ( ent->client->ps.legsAnimTimer > PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME && ent->client->ps.legsAnimTimer <= PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME + 100 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); damage = Q_irand( 4, 8 ); dflags &= ~DAMAGE_NO_KILL; } } else*/ if ( ent->client->ps.legsAnimTimer <= 100 ) { TIMER_Set( ent, "grappleDamageDebounce", 150 ); damage = Q_irand( 10, 20 ); dflags &= ~DAMAGE_NO_KILL; } break; } if ( damage ) { G_Damage( ent, ent->enemy, ent->enemy, NULL, ent->currentOrigin, damage, dflags, MOD_MELEE );//MOD_IMPACT? } } } qboolean clearMove = qtrue; int endOfAnimTime = 100; if ( ent->s.number < MAX_CLIENTS && ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY ) {//player holds extra long so you have more time to decide to do the quick getup //endOfAnimTime += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; if ( ent->client->ps.legsAnimTimer <= endOfAnimTime )//PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME ) { clearMove = qfalse; } } if ( clearMove ) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } if ( ent->client->ps.legsAnimTimer <= endOfAnimTime ) {//pretty much done with the anim, so get up now if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_3 ) { vec3_t ang = {10,ent->currentAngles[YAW],0}; vec3_t throwDir; AngleVectors( ang, throwDir, NULL, NULL ); if ( !(ent->flags&FL_NO_KNOCKBACK) ) { G_Throw( ent, throwDir, -100 ); } ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; NPC_SetAnim( ent, SETANIM_BOTH, BOTH_PLAYER_PA_3_FLY, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); ent->client->ps.weaponTime = ent->client->ps.legsAnimTimer; /* if ( ent->s.number < MAX_CLIENTS ) {//player holds extra long so you have more time to decide to do the quick getup ent->client->ps.legsAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; ent->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } */ //force-thrown - FIXME: start earlier? ent->forcePushTime = level.time + 500; } else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_1 ) { vec3_t ang = {10,ent->currentAngles[YAW],0}; vec3_t throwDir; AngleVectors( ang, throwDir, NULL, NULL ); if ( !(ent->flags&FL_NO_KNOCKBACK) ) { G_Throw( ent, throwDir, -100 ); } ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; NPC_SetAnim( ent, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); ent->client->ps.weaponTime = ent->client->ps.legsAnimTimer; if ( ent->s.number < MAX_CLIENTS ) {//player holds extra long so you have more time to decide to do the quick getup ent->client->ps.legsAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; ent->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } } //FIXME: should end so you can do a getup /* else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_2 ) { ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; NPC_SetAnim( ent, SETANIM_BOTH, BOTH_GETUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); ent->client->ps.weaponTime = ent->client->ps.legsAnimTimer; } */ } if ( d_slowmodeath->integer <= 3 && ent->s.number < MAX_CLIENTS ) {//no matrix effect, so slide the camera back and to the side G_CamPullBackForLegsAnim( ent ); G_CamCircleForLegsAnim( ent ); } } else if ( ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_START || ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_ATTACK || ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_LAND ) {//can't turn during force leap if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } overridAngles = PM_AdjustAnglesForLongJump( ent, ucmd )?qtrue:overridAngles; } else if ( PM_KickingAnim( ent->client->ps.legsAnim ) || ent->client->ps.legsAnim == BOTH_ARIAL_F1 || ent->client->ps.legsAnim == BOTH_ARIAL_LEFT || ent->client->ps.legsAnim == BOTH_ARIAL_RIGHT || ent->client->ps.legsAnim == BOTH_CARTWHEEL_LEFT || ent->client->ps.legsAnim == BOTH_CARTWHEEL_RIGHT || ent->client->ps.legsAnim == BOTH_JUMPATTACK7 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT || ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || ent->client->ps.legsAnim == BOTH_A7_SOULCAL ) {//can't move, check for damage frame if ( PM_KickingAnim( ent->client->ps.legsAnim ) ) { ucmd->forwardmove = ucmd->rightmove = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } } vec3_t kickDir={0,0,0}, kickDir2={0,0,0}, kickEnd={0,0,0}, kickEnd2={0,0,0}, fwdAngs = {0,ent->client->ps.viewangles[YAW],0}; float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ); float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); float remainingTime = (animLength-elapsedTime); float kickDist = (ent->maxs[0]*1.5f)+STAFF_KICK_RANGE+8.0f;//fudge factor of 8 float kickDist2 = kickDist; int kickDamage = Q_irand( 3, 8 ); int kickDamage2 = Q_irand( 3, 8 ); int kickPush = Q_flrand( 100.0f, 200.0f );//Q_flrand( 50.0f, 100.0f ); int kickPush2 = Q_flrand( 100.0f, 200.0f );//Q_flrand( 50.0f, 100.0f ); qboolean doKick = qfalse; qboolean doKick2 = qfalse; qboolean kickSoundOnWalls = qfalse; //HMM... or maybe trace from origin to footRBolt/footLBolt? Which one? G2 trace? Will do hitLoc, if so... if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) { if ( elapsedTime >= 250 && remainingTime >= 250 ) {//front doKick = qtrue; if ( ent->handRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->handRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } } else { switch ( ent->client->ps.legsAnim ) { case BOTH_A7_SOULCAL: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); if ( elapsedTime >= 1400 && elapsedTime <= 1500 ) {//right leg doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } break; case BOTH_ARIAL_F1: if ( elapsedTime >= 550 && elapsedTime <= 1000 ) {//right leg doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 800 && elapsedTime <= 1200 ) {//left leg doKick2 = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: if ( elapsedTime >= 200 && elapsedTime <= 600 ) {//lead leg int footBolt = (ent->client->ps.legsAnim==BOTH_ARIAL_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims doKick = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 400 && elapsedTime <= 850 ) {//trailing leg int footBolt = (ent->client->ps.legsAnim==BOTH_ARIAL_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims doKick2 = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_CARTWHEEL_LEFT: case BOTH_CARTWHEEL_RIGHT: if ( elapsedTime >= 200 && elapsedTime <= 600 ) {//lead leg int footBolt = (ent->client->ps.legsAnim==BOTH_CARTWHEEL_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims doKick = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 350 && elapsedTime <= 650 ) {//trailing leg int footBolt = (ent->client->ps.legsAnim==BOTH_CARTWHEEL_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims doKick2 = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_JUMPATTACK7: if ( elapsedTime >= 300 && elapsedTime <= 900 ) {//right knee doKick = qtrue; if ( ent->kneeRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->kneeRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 600 && elapsedTime <= 900 ) {//left leg doKick2 = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_BUTTERFLY_FL1: case BOTH_BUTTERFLY_FR1: if ( elapsedTime >= 950 && elapsedTime <= 1300 ) {//lead leg int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_FL1)?ent->footRBolt:ent->footLBolt;//mirrored anims doKick = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 1150 && elapsedTime <= 1600 ) {//trailing leg int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_FL1)?ent->footLBolt:ent->footRBolt;//mirrored anims doKick2 = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_BUTTERFLY_LEFT: case BOTH_BUTTERFLY_RIGHT: if ( (elapsedTime >= 100 && elapsedTime <= 450) || (elapsedTime >= 1100 && elapsedTime <= 1350) ) {//lead leg int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims doKick = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( elapsedTime >= 900 && elapsedTime <= 1600 ) {//trailing leg int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims doKick2 = qtrue; if ( footBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, footBolt, kickEnd2 ); VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); kickDir2[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir2 ); } else {//guess AngleVectors( fwdAngs, kickDir2, NULL, NULL ); } } break; case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: case BOTH_GETUP_FROLL_F: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); if ( elapsedTime >= 250 && remainingTime >= 250 ) {//front doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } if ( ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B ) {//rolling back, pull back the view G_CamPullBackForLegsAnim( ent ); } break; case BOTH_A7_KICK_F_AIR: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; if ( elapsedTime >= 100 && remainingTime >= 500 ) {//front doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } break; case BOTH_A7_KICK_F: kickSoundOnWalls = qtrue; //FIXME: push forward? if ( elapsedTime >= 250 && remainingTime >= 250 ) {//front doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); } } break; case BOTH_A7_KICK_B_AIR: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; if ( elapsedTime >= 100 && remainingTime >= 400 ) {//back doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_B: kickSoundOnWalls = qtrue; if ( elapsedTime >= 250 && remainingTime >= 250 ) {//back doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, kickDir, NULL, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_R_AIR: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; if ( elapsedTime >= 150 && remainingTime >= 300 ) {//left doKick = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_R: kickSoundOnWalls = qtrue; //FIXME: push right? if ( elapsedTime >= 250 && remainingTime >= 250 ) {//right doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); } } break; case BOTH_A7_KICK_L_AIR: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; if ( elapsedTime >= 150 && remainingTime >= 300 ) {//left doKick = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_L: kickSoundOnWalls = qtrue; //FIXME: push left? if ( elapsedTime >= 250 && remainingTime >= 250 ) {//left doKick = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_S: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); if ( ent->footRBolt != -1 ) {//actually trace to a bolt if ( elapsedTime >= 550 && elapsedTime <= 1050 ) { doKick = qtrue; G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is VectorMA( kickEnd, 8.0f, kickDir, kickEnd ); } } else {//guess if ( elapsedTime >= 400 && elapsedTime < 500 ) {//front doKick = qtrue; AngleVectors( fwdAngs, kickDir, NULL, NULL ); } else if ( elapsedTime >= 500 && elapsedTime < 600 ) {//front-right? doKick = qtrue; fwdAngs[YAW] += 45; AngleVectors( fwdAngs, kickDir, NULL, NULL ); } else if ( elapsedTime >= 600 && elapsedTime < 700 ) {//right doKick = qtrue; AngleVectors( fwdAngs, NULL, kickDir, NULL ); } else if ( elapsedTime >= 700 && elapsedTime < 800 ) {//back-right? doKick = qtrue; fwdAngs[YAW] += 45; AngleVectors( fwdAngs, NULL, kickDir, NULL ); } else if ( elapsedTime >= 800 && elapsedTime < 900 ) {//back doKick = qtrue; AngleVectors( fwdAngs, kickDir, NULL, NULL ); VectorScale( kickDir, -1, kickDir ); } else if ( elapsedTime >= 900 && elapsedTime < 1000 ) {//back-left? doKick = qtrue; fwdAngs[YAW] += 45; AngleVectors( fwdAngs, kickDir, NULL, NULL ); } else if ( elapsedTime >= 1000 && elapsedTime < 1100 ) {//left doKick = qtrue; AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } else if ( elapsedTime >= 1100 && elapsedTime < 1200 ) {//front-left? doKick = qtrue; fwdAngs[YAW] += 45; AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_BF: kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); if ( elapsedTime < 1500 ) {//auto-aim! overridAngles = PM_AdjustAnglesForBFKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; //FIXME: if we haven't done the back kick yet and there's no-one there to // kick anymore, go into some anim that returns us to our base stance } if ( ent->footRBolt != -1 ) {//actually trace to a bolt if ( ( elapsedTime >= 750 && elapsedTime < 850 ) || ( elapsedTime >= 1400 && elapsedTime < 1500 ) ) {//right, though either would do doKick = qtrue; G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is VectorMA( kickEnd, 8, kickDir, kickEnd ); } } else {//guess if ( elapsedTime >= 250 && elapsedTime < 350 ) {//front doKick = qtrue; AngleVectors( fwdAngs, kickDir, NULL, NULL ); } else if ( elapsedTime >= 350 && elapsedTime < 450 ) {//back doKick = qtrue; AngleVectors( fwdAngs, kickDir, NULL, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; case BOTH_A7_KICK_RL: kickSoundOnWalls = qtrue; kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); //FIXME: auto aim at enemies on the side of us? //overridAngles = PM_AdjustAnglesForRLKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; if ( elapsedTime >= 250 && elapsedTime < 350 ) {//right doKick = qtrue; if ( ent->footRBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is VectorMA( kickEnd, 8, kickDir, kickEnd ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); } } else if ( elapsedTime >= 350 && elapsedTime < 450 ) {//left doKick = qtrue; if ( ent->footLBolt != -1 ) {//actually trace to a bolt G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); kickDir[2] = 0;//ah, flatten it, I guess... VectorNormalize( kickDir ); //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is VectorMA( kickEnd, 8, kickDir, kickEnd ); } else {//guess AngleVectors( fwdAngs, NULL, kickDir, NULL ); VectorScale( kickDir, -1, kickDir ); } } break; } } if ( doKick ) { G_KickTrace( ent, kickDir, kickDist, kickEnd, kickDamage, kickPush, kickSoundOnWalls ); } if ( doKick2 ) { G_KickTrace( ent, kickDir2, kickDist2, kickEnd2, kickDamage2, kickPush2, kickSoundOnWalls ); } } else if ( ent->client->ps.saberMove == LS_DUAL_FB ) { //pull back the view G_CamPullBackForLegsAnim( ent ); } else if ( ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || ent->client->ps.saberMove == LS_A_BACKSTAB ) {//can't move or turn during back attacks ucmd->forwardmove = ucmd->rightmove = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); } if ( (overridAngles = (PM_AdjustAnglesForBackAttack( ent, ucmd )?qtrue:overridAngles)) == qtrue ) { //pull back the view G_CamPullBackForLegsAnim( ent ); } } else if ( ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK1 || ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK2 || ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_END || ent->client->ps.legsAnim == BOTH_FORCEWALLREBOUND_BACK ) { //pull back the view G_CamPullBackForLegsAnim( ent ); } else if ( ent->client->ps.torsoAnim == BOTH_A6_SABERPROTECT ) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); ent->client->ps.forceJumpCharge = 0; } if ( !ent->s.number ) { float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); float backDist = 0; if ( elapsedTime <= 300.0f ) {//starting anim backDist = (elapsedTime/300.0f)*90.0f; } else if ( ent->client->ps.torsoAnimTimer <= 300.0f ) {//ending anim backDist = (ent->client->ps.torsoAnimTimer/300.0f)*90.0f; } else {//in middle of anim backDist = 90.0f; } //back off and look down cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF); cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; cg.overrides.thirdPersonPitchOffset = cg_thirdPersonPitchOffset.value+(backDist/2.0f); } overridAngles = (PM_AdjustAnglesForSpinProtect( ent, ucmd )?qtrue:overridAngles); } else if ( ent->client->ps.legsAnim == BOTH_A3_SPECIAL ) {//push forward float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); ucmd->upmove = ucmd->rightmove = 0; ucmd->forwardmove = 0; if ( elapsedTime >= 350 && elapsedTime < 1500 ) {//push forward ucmd->forwardmove = 64; ent->client->ps.speed = 200.0f; } //FIXME: pull back camera? } else if ( ent->client->ps.legsAnim == BOTH_A2_SPECIAL ) {//push forward ucmd->upmove = ucmd->rightmove = 0; ucmd->forwardmove = 0; if ( ent->client->ps.legsAnimTimer > 200.0f ) { float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); if ( elapsedTime < 750 || (elapsedTime >= 1650 && elapsedTime < 2400) ) {//push forward ucmd->forwardmove = 64; ent->client->ps.speed = 200.0f; } } //FIXME: pull back camera? }//FIXME: fast special? else if ( ent->client->ps.legsAnim == BOTH_A1_SPECIAL && (ucmd->forwardmove || ucmd->rightmove || (VectorCompare( ent->client->ps.moveDir, vec3_origin )&&ent->client->ps.speed>0)) ) {//moving during full-body fast special ent->client->ps.legsAnimTimer = 0;//don't hold this legsAnim, allow them to run //FIXME: just add this to the list of overridable special moves in PM_Footsteps? } else if ( ent->client->ps.legsAnim == BOTH_FLIP_LAND ) {//moving during full-body fast special float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); ucmd->upmove = ucmd->rightmove = ucmd->forwardmove = 0; if ( elapsedTime > 600 && elapsedTime < 800 && ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//jump - FIXME: how do we stop double-jumps? ent->client->ps.pm_flags |= PMF_JUMP_HELD; ent->client->ps.groundEntityNum = ENTITYNUM_NONE; ent->client->ps.jumpZStart = ent->currentOrigin[2]; ent->client->ps.velocity[2] = JUMP_VELOCITY; G_AddEvent( ent, EV_JUMP, 0 ); } } else if ( ( PM_SuperBreakWinAnim( ent->client->ps.torsoAnim ) || PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) ) && ent->client->ps.torsoAnimTimer ) {//can't move or turn ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); ent->client->ps.forceJumpCharge = 0; } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); } else if ( BG_FullBodyTauntAnim( ent->client->ps.legsAnim ) && BG_FullBodyTauntAnim( ent->client->ps.torsoAnim ) ) { if ( (ucmd->buttons&BUTTON_ATTACK) || (ucmd->buttons&BUTTON_ALT_ATTACK) || (ucmd->buttons&BUTTON_USE_FORCE) || (ucmd->buttons&BUTTON_FORCEGRIP) || (ucmd->buttons&BUTTON_FORCE_LIGHTNING) || (ucmd->buttons&BUTTON_FORCE_DRAIN) || ucmd->upmove ) {//stop the anim if ( ent->client->ps.legsAnim == BOTH_MEDITATE && ent->client->ps.torsoAnim == BOTH_MEDITATE ) { NPC_SetAnim( ent, SETANIM_BOTH, BOTH_MEDITATE_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); } else { ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; } } else { if ( ent->client->ps.legsAnim == BOTH_MEDITATE ) { if ( ent->client->ps.legsAnimTimer < 100 ) { ent->client->ps.legsAnimTimer = 100; } } if ( ent->client->ps.torsoAnim == BOTH_MEDITATE ) { if ( ent->client->ps.torsoAnimTimer < 100 ) { ent->client->ps.legsAnimTimer = 100; } } if ( ent->client->ps.legsAnimTimer > 0 || ent->client->ps.torsoAnimTimer > 0 ) { ucmd->rightmove = 0; ucmd->upmove = 0; ucmd->forwardmove = 0; ucmd->buttons = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); ent->client->ps.forceJumpCharge = 0; } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); } } } else if ( ent->client->ps.legsAnim == BOTH_MEDITATE_END && ent->client->ps.legsAnimTimer > 0 ) { ucmd->rightmove = 0; ucmd->upmove = 0; ucmd->forwardmove = 0; ucmd->buttons = 0; if ( ent->NPC ) { VectorClear( ent->client->ps.moveDir ); ent->client->ps.forceJumpCharge = 0; } overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); } else if ( !ent->s.number ) { if ( ent->client->NPC_class != CLASS_ATST ) { // Not in a vehicle. if ( ent->s.m_iVehicleNum == 0 ) { if ( !MatrixMode ) { cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_ANG); cg.overrides.thirdPersonRange = 0; } } } } if ( PM_InRoll( &ent->client->ps ) ) { if ( ent->s.number >= MAX_CLIENTS || !player_locked ) { //FIXME: NPCs should try to face us during this roll, so they roll around us...? PM_CmdForRoll( &ent->client->ps, ucmd ); if ( ent->s.number >= MAX_CLIENTS ) {//make sure it doesn't roll me off a ledge if ( !G_CheckRollSafety( ent, ent->client->ps.legsAnim, 24 ) ) {//crap! I guess all we can do is stop... UGH ucmd->rightmove = ucmd->forwardmove = 0; } } } if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } ent->client->ps.speed = 400; } if ( PM_InCartwheel( ent->client->ps.legsAnim ) ) {//can't keep moving in cartwheel if ( ent->client->ps.legsAnimTimer > 100 ) {//still have time left in the anim ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } if ( ent->s.number || !player_locked ) { switch ( ent->client->ps.legsAnim ) { case BOTH_ARIAL_LEFT: case BOTH_CARTWHEEL_LEFT: ucmd->rightmove = -127; break; case BOTH_ARIAL_RIGHT: case BOTH_CARTWHEEL_RIGHT: ucmd->rightmove = 127; break; case BOTH_ARIAL_F1: ucmd->forwardmove = 127; break; default: break; } } } } if ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT ) { if ( ent->client->ps.legsAnimTimer > 100 ) {//still have time left in the anim ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; if ( ent->NPC ) {//invalid now VectorClear( ent->client->ps.moveDir ); } if ( ent->s.number || !player_locked ) { if ( ent->client->ps.legsAnimTimer > 450 ) { switch ( ent->client->ps.legsAnim ) { case BOTH_BUTTERFLY_LEFT: ucmd->rightmove = -127; break; case BOTH_BUTTERFLY_RIGHT: ucmd->rightmove = 127; break; default: break; } } } } } overridAngles = (PM_AdjustAnglesForStabDown( ent, ucmd )?qtrue:overridAngles); overridAngles = (PM_AdjustAngleForWallJump( ent, ucmd, qtrue )?qtrue:overridAngles); overridAngles = (PM_AdjustAngleForWallRunUp( ent, ucmd, qtrue )?qtrue:overridAngles); overridAngles = (PM_AdjustAngleForWallRun( ent, ucmd, qtrue )?qtrue:overridAngles); return overridAngles; } void BG_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd ) { vec3_t forward, right, moveDir; float pushSpeed, fMove, rMove; if ( !self->client ) { return; } pushSpeed = VectorLengthSquared(self->client->pushVec); if(!pushSpeed) {//not being pushed return; } AngleVectors(self->client->ps.viewangles, forward, right, NULL); VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir); VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir); //moveDir is now our intended move velocity VectorAdd(moveDir, self->client->pushVec, moveDir); self->client->ps.speed = VectorNormalize(moveDir); //moveDir is now our intended move velocity plus our push Vector fMove = 127.0 * DotProduct(forward, moveDir); rMove = 127.0 * DotProduct(right, moveDir); ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive ucmd->rightmove = floor(rMove);//If in the same dir , will be positive if ( self->client->pushVecTime < level.time ) { VectorClear( self->client->pushVec ); } } void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc ) { if ( !ent->client || !ent->NPC ) { return; } if ( !ent->NPC->stats.acceleration ) {//No acceleration means just start and stop ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } //FIXME: in cinematics always accel/decel? else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed ) {//Only accelerate if at walkSpeeds if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) { //ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) { //ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) {//decelerate even when walking ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) {//stop on a dime ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) {//Only decelerate if at runSpeeds if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) {//Accelerate to runspeed //ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) {//accelerate instantly //ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) { ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) { ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } } /* ------------------------- NPC_GetWalkSpeed ------------------------- */ static int NPC_GetWalkSpeed( gentity_t *ent ) { int walkSpeed = 0; if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) return 0; switch ( ent->client->playerTeam ) { case TEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code) default: walkSpeed = ent->NPC->stats.walkSpeed; break; } return walkSpeed; } /* ------------------------- NPC_GetRunSpeed ------------------------- */ #define BORG_RUN_INCR 25 #define SPECIES_RUN_INCR 25 #define STASIS_RUN_INCR 20 #define WARBOT_RUN_INCR 20 static int NPC_GetRunSpeed( gentity_t *ent ) { int runSpeed = 0; if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) return 0; /* switch ( ent->client->playerTeam ) { case TEAM_BORG: runSpeed = ent->NPC->stats.runSpeed; runSpeed += BORG_RUN_INCR * (g_spskill->integer%3); break; case TEAM_8472: runSpeed = ent->NPC->stats.runSpeed; runSpeed += SPECIES_RUN_INCR * (g_spskill->integer%3); break; case TEAM_STASIS: runSpeed = ent->NPC->stats.runSpeed; runSpeed += STASIS_RUN_INCR * (g_spskill->integer%3); break; case TEAM_BOTS: runSpeed = ent->NPC->stats.runSpeed; break; default: runSpeed = ent->NPC->stats.runSpeed; break; } */ // team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types switch( ent->client->NPC_class) { case CLASS_PROBE: // droid cases here to shut-up compiler case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: case CLASS_MARK1: case CLASS_MARK2: case CLASS_PROTOCOL: case CLASS_ATST: // hmm, not really your average droid case CLASS_MOUSE: case CLASS_SEEKER: case CLASS_REMOTE: runSpeed = ent->NPC->stats.runSpeed; break; default: runSpeed = ent->NPC->stats.runSpeed; break; } return runSpeed; } void G_HeldByMonster( gentity_t *ent, usercmd_t **ucmd ) { if ( ent && ent->activator && ent->activator->inuse && ent->activator->health > 0 ) { gentity_t *monster = ent->activator; //take the monster's waypoint as your own ent->waypoint = monster->waypoint; //update the actual origin of the victim mdxaBone_t boltMatrix; // Getting the bolt here int boltIndex = monster->gutBolt;//default to being held in his mouth if ( monster->count == 1 ) {//being held in hand rather than the mouth, so use *that* bolt boltIndex = monster->handRBolt; } vec3_t monAngles = {0}; monAngles[YAW] = monster->currentAngles[YAW];//only use YAW when passing angles to G2 gi.G2API_GetBoltMatrix( monster->ghoul2, monster->playerModel, boltIndex, &boltMatrix, monAngles, monster->currentOrigin, (cg.time?cg.time:level.time), NULL, monster->s.modelScale ); // Storing ent position, bolt position, and bolt axis gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->ps.origin ); gi.linkentity( ent ); //lock view angles PM_AdjustAnglesForHeldByMonster( ent, monster, *ucmd ); if ( monster->client && monster->client->NPC_class == CLASS_WAMPA ) {//can only hit attack button (*ucmd)->buttons &= ~((*ucmd)->buttons&~BUTTON_ATTACK); } } else if (ent) {//doh, my captor died! ent->activator = NULL; if (ent->client) { ent->client->ps.eFlags &= ~(EF_HELD_BY_WAMPA|EF_HELD_BY_RANCOR); } } // don't allow movement, weapon switching, and most kinds of button presses (*ucmd)->forwardmove = 0; (*ucmd)->rightmove = 0; (*ucmd)->upmove = 0; } // yes... so stop skipping... void G_StopCinematicSkip( void ) { gi.cvar_set("skippingCinematic", "0"); gi.cvar_set("timescale", "1"); } void G_StartCinematicSkip( void ) { if (cinematicSkipScript[0]) { Quake3Game()->RunScript( &g_entities[0], cinematicSkipScript ); cinematicSkipScript[0] = 0; gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); } else { // no... so start skipping... gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); } } void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) { if ( !ent || !ent->client || ent->health <= 0 ) { return; } if ( !ent->s.number && ( !cg.renderingThirdPerson || cg.zoomMode ) ) { if ( ent->client->idleTime < level.time ) { ent->client->idleTime = level.time; } return; } if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || !PM_StandingAnim( ent->client->ps.legsAnim ) || ent->enemy || ent->client->ps.legsAnimTimer || ent->client->ps.torsoAnimTimer ) {//FIXME: also check for turning? if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || ent->enemy ) { //if in an idle, break out switch ( ent->client->ps.legsAnim ) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: case BOTH_STAND3IDLE1: case BOTH_STAND5IDLE1: ent->client->ps.legsAnimTimer = 0; break; } switch ( ent->client->ps.torsoAnim ) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: case BOTH_STAND3IDLE1: case BOTH_STAND5IDLE1: ent->client->ps.torsoAnimTimer = 0; break; } } // if ( ent->client->idleTime < level.time ) { ent->client->idleTime = level.time; } } else if ( level.time - ent->client->idleTime > 5000 ) {//been idle for 5 seconds int idleAnim = -1; switch ( ent->client->ps.legsAnim ) { case BOTH_STAND1: idleAnim = BOTH_STAND1IDLE1; break; case BOTH_STAND2: idleAnim = Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); break; case BOTH_STAND3: idleAnim = BOTH_STAND3IDLE1; break; case BOTH_STAND5: idleAnim = BOTH_STAND5IDLE1; break; } if ( idleAnim != -1 && PM_HasAnimation( ent, idleAnim ) ) { NPC_SetAnim( ent, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); //don't idle again after this anim for a while ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); } } } void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd ) { if ( ent->client ) { if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir || ucmd->forwardmove || ucmd->rightmove//moving using ucmds || (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move || (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move { switch( ent->client->NPC_class ) { case CLASS_R2D2: ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); break; case CLASS_R5D2: ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); break; case CLASS_MARK2: ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); break; case CLASS_MOUSE: ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); break; case CLASS_PROBE: ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); break; default: break; } } else {//not moving under your own control, stop loopSound if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_PROBE ) { ent->s.loopSound = 0; } } } } /* ============== ClientAlterSpeed This function is called ONLY from ClientThinkReal, and is responsible for setting client ps.speed ============== */ void ClientAlterSpeed(gentity_t *ent, usercmd_t *ucmd, qboolean controlledByPlayer, float vehicleFrameTimeModifier) { gclient_t *client = ent->client; Vehicle_t *pVeh = NULL; if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) { pVeh = ent->m_pVehicle; } // set speed // This may be wrong: If we're an npc and we are in a vehicle??? if ( ent->NPC != NULL && ent->client && ( ent->s.m_iVehicleNum != 0 )/*&& ent->client->NPC_class == CLASS_VEHICLE*/ ) {//we don't actually scale the ucmd, we use actual speeds //FIXME: swoop should keep turning (and moving forward?) for a little bit? if ( ent->NPC->combatMove == qfalse ) { if ( !(ucmd->buttons & BUTTON_USE) ) {//Not leaning qboolean Flying = (ucmd->upmove && ent->client->moveType == MT_FLYSWIM); qboolean Climbing = (ucmd->upmove && ent->watertype&CONTENTS_LADDER ); client->ps.friction = 6; if ( ucmd->forwardmove || ucmd->rightmove || Flying ) { //if ( ent->NPC->behaviorState != BS_FORMATION ) {//In - Formation NPCs set thier desiredSpeed themselves if ( ucmd->buttons & BUTTON_WALKING ) { ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed; } else//running { ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed; } if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer ) {//At higher speeds, need to slow down close to stuff //Slow down as you approach your goal // if ( ent->NPC->distToGoal < SLOWDOWN_DIST && client->race != RACE_BORG && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 { if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED ) { float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST; ent->NPC->desiredSpeed = ceil(slowdownSpeed); if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED ) {//don't slow down too much ent->NPC->desiredSpeed = MIN_NPC_SPEED; } } } } } } else if ( Climbing ) { ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed; } else {//We want to stop ent->NPC->desiredSpeed = 0; } NPC_Accelerate( ent, qfalse, qfalse ); if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) {//No-one walks this slow client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop ucmd->forwardmove = 0; ucmd->rightmove = 0; } else { if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed ) {//Play the walkanim ucmd->buttons |= BUTTON_WALKING; } else { ucmd->buttons &= ~BUTTON_WALKING; } if ( ent->NPC->currentSpeed > 0 ) {//We should be moving if ( Climbing || Flying ) { if ( !ucmd->upmove ) {//We need to force them to take a couple more steps until stopped ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove; } } else if ( !ucmd->forwardmove && !ucmd->rightmove ) {//We need to force them to take a couple more steps until stopped ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove; ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove; } } client->ps.speed = ent->NPC->currentSpeed; if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) { } else { //Slow down on turns - don't orbit!!! float turndelta = 0; // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... { turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180; } else { turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->desiredYaw ) ))/180; } if ( turndelta < 0.75f ) { client->ps.speed = 0; } else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 ) {//Turn is greater than 45 degrees or closer than 100 to goal client->ps.speed = floor(((float)(client->ps.speed))*turndelta); } } } } } else { ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent ); client->ps.speed = ent->NPC->desiredSpeed; } } else {//Client sets ucmds and such for speed alterations { client->ps.speed = g_speed->value;//default is 320 /*if ( !ent->s.number && ent->painDebounceTime>level.time ) { client->ps.speed *= 0.25f; } else */if (ent->client->ps.heldClient < ENTITYNUM_WORLD) { client->ps.speed *= 0.3f; } else if ( PM_SaberInAttack( ent->client->ps.saberMove ) && ucmd->forwardmove < 0 ) {//if running backwards while attacking, don't run as fast. switch( client->ps.saberAnimLevel ) { case SS_FAST: client->ps.speed *= 0.75f; break; case SS_MEDIUM: case SS_DUAL: case SS_STAFF: client->ps.speed *= 0.60f; break; case SS_STRONG: client->ps.speed *= 0.45f; break; } if ( g_saberMoveSpeed->value != 1.0f ) { client->ps.speed *= g_saberMoveSpeed->value; } } else if ( PM_LeapingSaberAnim( client->ps.legsAnim ) ) {//no mod on speed when leaping //FIXME: maybe jump? } else if ( PM_SpinningSaberAnim( client->ps.legsAnim ) ) { client->ps.speed *= 0.5f; if ( g_saberMoveSpeed->value != 1.0f ) { client->ps.speed *= g_saberMoveSpeed->value; } } else if ( client->ps.weapon == WP_SABER && ( ucmd->buttons & BUTTON_ATTACK ) ) {//if attacking with saber while running, drop your speed //FIXME: should be weaponTime? Or in certain anims? switch( client->ps.saberAnimLevel ) { case SS_MEDIUM: case SS_DUAL: case SS_STAFF: client->ps.speed *= 0.85f; break; case SS_STRONG: client->ps.speed *= 0.70f; break; } if ( g_saberMoveSpeed->value != 1.0f ) { client->ps.speed *= g_saberMoveSpeed->value; } } } } if ( client->NPC_class == CLASS_ATST && client->ps.legsAnim == BOTH_RUN1START ) {//HACK: when starting to move as atst, ramp up speed //float animLength = PM_AnimLength( client->clientInfo.animFileIndex, (animNumber_t)client->ps.legsAnim); //client->ps.speed *= ( animLength - client->ps.legsAnimTimer)/animLength; if ( client->ps.legsAnimTimer > 100 ) { client->ps.speed = 0; } } //Apply forced movement if ( client->forced_forwardmove ) { ucmd->forwardmove = client->forced_forwardmove; if ( !client->ps.speed ) { if ( ent->NPC != NULL ) { client->ps.speed = ent->NPC->stats.runSpeed; } else { client->ps.speed = g_speed->value;//default is 320 } } } if ( client->forced_rightmove ) { ucmd->rightmove = client->forced_rightmove; if ( !client->ps.speed ) { if ( ent->NPC != NULL ) { client->ps.speed = ent->NPC->stats.runSpeed; } else { client->ps.speed = g_speed->value;//default is 320 } } } if ( !pVeh ) { if ( ucmd->forwardmove < 0 && !(ucmd->buttons&BUTTON_WALKING) && client->ps.groundEntityNum != ENTITYNUM_NONE ) {//running backwards is slower than running forwards client->ps.speed *= 0.75; } if (client->ps.forceRageRecoveryTime > level.time ) { client->ps.speed *= 0.75; } if ( client->ps.weapon == WP_SABER ) { if ( client->ps.saber[0].moveSpeedScale != 1.0f ) { client->ps.speed *= client->ps.saber[0].moveSpeedScale; } if ( client->ps.dualSabers && client->ps.saber[1].moveSpeedScale != 1.0f ) { client->ps.speed *= client->ps.saber[1].moveSpeedScale; } } } } extern qboolean ForceDrain2(gentity_t *ent); extern void ForceGrip(gentity_t *ent); extern void ForceLightning(gentity_t *ent); extern void ForceProtect(gentity_t *ent); extern void ForceRage(gentity_t *ent); extern void ForceSeeing(gentity_t *ent); extern void ForceTelepathy(gentity_t *ent); extern void ForceAbsorb(gentity_t *ent); extern void ForceHeal(gentity_t *ent); static void ProcessGenericCmd(gentity_t *ent, byte cmd) { switch(cmd) { case 0: break; case GENCMD_FORCE_DRAIN: ForceDrain2(ent); break; case GENCMD_FORCE_THROW: ForceThrow(ent, qfalse); break; case GENCMD_FORCE_SPEED: ForceSpeed(ent); break; case GENCMD_FORCE_PULL: ForceThrow(ent, qtrue); break; case GENCMD_FORCE_DISTRACT: ForceTelepathy(ent); break; case GENCMD_FORCE_GRIP: ForceGrip(ent); break; case GENCMD_FORCE_LIGHTNING: ForceLightning(ent); break; case GENCMD_FORCE_RAGE: ForceRage(ent); break; case GENCMD_FORCE_PROTECT: ForceProtect(ent); break; case GENCMD_FORCE_ABSORB: ForceAbsorb(ent); break; case GENCMD_FORCE_SEEING: ForceSeeing(ent); break; case GENCMD_FORCE_HEAL: ForceHeal(ent); break; } } /* ============== ClientThink This will be called once for each client frame, which will usually be a couple times for each server frame on fast clients. ============== */ extern int G_FindLocalInterestPoint( gentity_t *self ); extern float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUmcd ); void ClientThink_real( gentity_t *ent, usercmd_t *ucmd ) { gclient_t *client; pmove_t pm; vec3_t oldOrigin; int oldEventSequence; int msec; qboolean inSpinFlipAttack = PM_AdjustAnglesForSpinningFlip( ent, ucmd, qfalse ); qboolean controlledByPlayer = qfalse; Vehicle_t *pVeh = NULL; if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) { pVeh = ent->m_pVehicle; } //Don't let the player do anything if in a camera if ( (ent->s.eFlags&EF_HELD_BY_RANCOR) || (ent->s.eFlags&EF_HELD_BY_WAMPA) ) { G_HeldByMonster( ent, &ucmd ); } if ( ent->s.number == 0 ) { extern cvar_t *g_skippingcin; if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) { G_UpdateEmplacedWeaponData( ent ); RunEmplacedWeapon( ent, &ucmd ); } if ( ent->client->ps.saberLockTime > level.time && ent->client->ps.saberLockEnemy != ENTITYNUM_NONE ) { NPC_SetLookTarget( ent, ent->client->ps.saberLockEnemy, level.time+1000 ); } if ( ent->client->renderInfo.lookTargetClearTime < level.time //NOTE: here this is used as a debounce, not an actual timer && ent->health > 0 //must be alive && (!ent->enemy || ent->client->ps.saberMove != LS_A_BACKSTAB) )//don't update if in backstab unless don't currently have an enemy {//NOTE: doesn't keep updating to nearest enemy once you're dead int newLookTarget; if ( !G_ValidateLookEnemy( ent, ent->enemy ) ) { ent->enemy = NULL; } //FIXME: make this a little prescient? G_ChooseLookEnemy( ent, ucmd ); if ( ent->enemy ) {//target newLookTarget = ent->enemy->s.number; //so we don't change our minds in the next 1 second ent->client->renderInfo.lookTargetClearTime = level.time+1000; ent->client->renderInfo.lookMode = LM_ENT; } else {//no target //FIXME: what about sightalerts and missiles? newLookTarget = ENTITYNUM_NONE; newLookTarget = G_FindLocalInterestPoint( ent ); if ( newLookTarget != ENTITYNUM_NONE ) {//found something of interest ent->client->renderInfo.lookMode = LM_INTEREST; } else {//okay, no interesting things and no enemies, so look for items newLookTarget = G_FindLookItem( ent ); ent->client->renderInfo.lookMode = LM_ENT; } } if ( ent->client->renderInfo.lookTarget != newLookTarget ) {//transitioning NPC_SetLookTarget( ent, newLookTarget, level.time+1000 ); } } if ( in_camera ) { // watch the code here, you MUST "return" within this IF(), *unless* you're stopping the cinematic skip. // if ( ClientCinematicThink(ent->client) ) { if (g_skippingcin->integer) // already doing cinematic skip? {// yes... so stop skipping... G_StopCinematicSkip(); } else {// no... so start skipping... G_StartCinematicSkip(); return; } } else { return; } } // If he's riding the vehicle... else if ( ent->s.m_iVehicleNum != 0 && ent->health > 0 ) { } else { if ( g_skippingcin->integer ) {//We're skipping the cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } if ( ent->client->ps.pm_type == PM_DEAD && cg.missionStatusDeadTime < level.time ) {//mission status screen is up because player is dead, stop all scripts stop_icarus = qtrue; } } // // Don't allow the player to adjust the pitch when they are in third person overhead cam. //extern vmCvar_t cg_thirdPerson; // if ( cg_thirdPerson.integer == 2 ) // { // ucmd->angles[PITCH] = 0; // } if ( cg.zoomMode == 2 ) { // Any kind of movement when the player is NOT ducked when the disruptor gun is zoomed will cause us to auto-magically un-zoom if ( ( (ucmd->forwardmove||ucmd->rightmove) && ucmd->upmove >= 0 //crouching-moving is ok && !(ucmd->buttons&BUTTON_USE)/*leaning is ok*/ ) || ucmd->upmove > 0 //jumping not allowed ) { // already zooming, so must be wanting to turn it off G_Sound( ent, G_SoundIndex( "sound/weapons/disruptor/zoomend.wav" )); cg.zoomMode = 0; cg.zoomTime = cg.time; cg.zoomLocked = qfalse; } } if ( (player_locked || (ent->client->ps.eFlags&EF_FORCE_GRIPPED) || (ent->client->ps.eFlags&EF_FORCE_DRAINED) || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_1) || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_2) || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_3)) && ent->client->ps.pm_type < PM_DEAD ) // unless dead {//lock out player control if ( !player_locked ) { VectorClear( ucmd->angles ); } ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->buttons = 0; ucmd->upmove = 0; PM_AdjustAnglesToGripper( ent, ucmd ); } if ( ent->client->ps.leanofs ) {//no shooting while leaning ucmd->buttons &= ~BUTTON_ATTACK; if ( ent->client->ps.weapon != WP_DISRUPTOR ) {//can still zoom around corners ucmd->buttons &= ~BUTTON_ALT_ATTACK; } } } else { if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) { G_UpdateEmplacedWeaponData( ent ); } if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) { controlledByPlayer = qtrue; int sav_weapon = ucmd->weapon; memcpy( ucmd, &player->client->usercmd, sizeof( usercmd_t ) ); ucmd->weapon = sav_weapon; ent->client->usercmd = *ucmd; } // Transfer over our driver's commands to us (the vehicle). if ( ent->owner && ent->client && ent->client->NPC_class == CLASS_VEHICLE ) { memcpy( ucmd, &ent->owner->client->usercmd, sizeof( usercmd_t ) ); ucmd->buttons &= ~BUTTON_USE;//Vehicles NEVER try to use ANYTHING!!! //ucmd->weapon = ent->client->ps.weapon; // but keep our weapon. ent->client->usercmd = *ucmd; } G_NPCMunroMatchPlayerWeapon( ent ); } // If we are a vehicle, update ourself. if ( pVeh && (pVeh->m_pVehicleInfo->Inhabited(pVeh) || pVeh->m_iBoarding!=0 || pVeh->m_pVehicleInfo->type!=VH_ANIMAL) ) { pVeh->m_pVehicleInfo->Update( pVeh, ucmd ); } else if ( ent->client ) {//this is any client that is not a vehicle (OR: is a vehicle and it not being ridden, is not being boarded, or is a TaunTaun...! if ( ent->client->NPC_class == CLASS_GONK || ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 ) {//no jumping or strafing in these guys ucmd->upmove = ucmd->rightmove = 0; } else if ( ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_RANCOR ) {//no jumping in atst if (ent->client->ps.pm_type != PM_NOCLIP) { ucmd->upmove = 0; } if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//ATST crushes anything underneath it gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; if ( under && under->health && under->takedamage ) { vec3_t down = {0,0,-1}; //FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin G_Damage( under, ent, ent, down, under->currentOrigin, 100, 0, MOD_CRUSH ); } //so they know to run like hell when I get close //FIXME: project this in the direction I'm moving? if ( ent->client->NPC_class != CLASS_RANCOR && !Q_irand( 0, 10 ) ) {//not so often... AddSoundEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER, qfalse, qtrue ); AddSightEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER, 100 ); } } } else if ( ent->client->ps.groundEntityNum < ENTITYNUM_WORLD && !ent->client->ps.forceJumpCharge ) {//standing on an entity and not currently force jumping gentity_t *groundEnt = &g_entities[ent->client->ps.groundEntityNum]; if ( groundEnt && groundEnt->client ) { // If you landed on a speeder or animal vehicle... if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_VEHICLE ) { if ( ent->client->NPC_class != CLASS_VEHICLE ) {//um... vehicles shouldn't ride other vehicles, mmkay? if ( (groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL && PM_HasAnimation( ent, BOTH_VT_IDLE )) || (groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && PM_HasAnimation( ent, BOTH_VS_IDLE )) ) { //groundEnt->m_pVehicle->m_iBoarding = -3; // Land From Behind groundEnt->m_pVehicle->m_pVehicleInfo->Board( groundEnt->m_pVehicle, ent ); } } } else if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_SAND_CREATURE && G_HasKnockdownAnims( ent ) ) {//step on a sand creature = *you* fall down G_Knockdown( ent, groundEnt, vec3_origin, 300, qtrue ); } else if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_RANCOR ) {//step on a Rancor, it bucks & throws you off if ( groundEnt->client->ps.legsAnim != BOTH_ATTACK3 && groundEnt->client->ps.legsAnim != BOTH_ATTACK4 && groundEnt->client->ps.legsAnim != BOTH_BUCK_RIDER ) {//don't interrupt special anims vec3_t throwDir, right; AngleVectors( groundEnt->currentAngles, throwDir, right, NULL ); VectorScale(throwDir,-1,throwDir); VectorMA( throwDir, Q_flrand( -0.5f, 0.5f), right, throwDir ); throwDir[2] = 0.2f; VectorNormalize( throwDir ); if ( !(ent->flags&FL_NO_KNOCKBACK) ) { G_Throw( ent, throwDir, Q_flrand( 50, 200 ) ); } if ( G_HasKnockdownAnims( ent ) ) { G_Knockdown( ent, groundEnt, vec3_origin, 300, qtrue ); } NPC_SetAnim( groundEnt, SETANIM_BOTH, BOTH_BUCK_RIDER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); } } else if ( groundEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && groundEnt->health > 0 && !PM_InRoll( &groundEnt->client->ps ) && !(groundEnt->client->ps.eFlags&EF_LOCKED_TO_WEAPON) && !(groundEnt->client->ps.eFlags&EF_HELD_BY_RANCOR) && !(groundEnt->client->ps.eFlags&EF_HELD_BY_WAMPA) && !(groundEnt->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) && !inSpinFlipAttack ) {//landed on a live client who is on the ground, jump off them and knock them down qboolean forceKnockdown = qfalse; // If in a vehicle when land on someone, always knockdown. if ( pVeh ) { forceKnockdown = qtrue; } else if ( ent->s.number && ent->NPC && ent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 )//ent->s.weapon == WP_SABER ) {//force-jumper landed on someone //don't jump off, too many ledges, plus looks weird if ( groundEnt->client->playerTeam != ent->client->playerTeam ) {//don't knock down own guys forceKnockdown = (qboolean)(Q_irand( 0, RANK_CAPTAIN+4 )<ent->NPC->rank); } //now what... push the groundEnt out of the way? if ( !ent->client->ps.velocity[0] && !ent->client->ps.velocity[1] ) {//not moving, shove us a little vec3_t slideFwd; AngleVectors( ent->client->ps.viewangles, slideFwd, NULL, NULL ); slideFwd[2] = 0.0f; VectorNormalize( slideFwd ); ent->client->ps.velocity[0] = slideFwd[0]*10.0f; ent->client->ps.velocity[1] = slideFwd[1]*10.0f; } //slide for a little ent->client->ps.pm_flags |= PMF_TIME_NOFRICTION; ent->client->ps.pm_time = 100; } else if ( ent->health > 0 ) { if ( !PM_InRoll( &ent->client->ps ) && !PM_FlippingAnim( ent->client->ps.legsAnim ) ) { if ( ent->s.number && ent->s.weapon == WP_SABER ) { ent->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently? } else if ( !ucmd->upmove ) {//if not ducking (which should cause a roll), then jump ucmd->upmove = 127; } if ( !ucmd->forwardmove && !ucmd->rightmove ) {// If not moving, don't want to jump straight up //FIXME: trace for clear di? if ( !Q_irand( 0, 3 ) ) { ucmd->forwardmove = 127; } else if ( !Q_irand( 0, 3 ) ) { ucmd->forwardmove = -127; } else if ( !Q_irand( 0, 1 ) ) { ucmd->rightmove = 127; } else { ucmd->rightmove = -127; } } if ( !ent->s.number && ucmd->upmove < 0 ) {//player who should roll- force it int rollAnim = BOTH_ROLL_F; if ( ucmd->forwardmove >= 0 ) { rollAnim = BOTH_ROLL_F; } else if ( ucmd->forwardmove < 0 ) { rollAnim = BOTH_ROLL_B; } else if ( ucmd->rightmove > 0 ) { rollAnim = BOTH_ROLL_R; } else if ( ucmd->rightmove < 0 ) { rollAnim = BOTH_ROLL_L; } NPC_SetAnim(ent,SETANIM_BOTH,rollAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); G_AddEvent( ent, EV_ROLL, 0 ); ent->client->ps.saberMove = LS_NONE; } } } else {//a corpse? Shit //Hmm, corpses should probably *always* knockdown... forceKnockdown = qtrue; ent->clipmask &= ~CONTENTS_BODY; } //FIXME: need impact sound event GEntity_PainFunc( groundEnt, ent, ent, groundEnt->currentOrigin, 0, MOD_CRUSH ); if ( !forceKnockdown && groundEnt->client->NPC_class == CLASS_DESANN && ent->client->NPC_class != CLASS_LUKE ) {//can't knock down desann unless you're luke //FIXME: should he smack you away like Galak Mech? } else if ( forceKnockdown //forced || ent->client->NPC_class == CLASS_DESANN //desann always knocks people down || ( ( (groundEnt->s.number&&(groundEnt->s.weapon!=WP_SABER||!groundEnt->NPC||groundEnt->NPC->rank<Q_irand(RANK_CIVILIAN,RANK_CAPTAIN+1))) //an NPC who is either not a saber user or passed the rank-based probability test || ((!ent->s.number||G_ControlledByPlayer(groundEnt)) && !Q_irand( 0, 3 )&&cg.renderingThirdPerson&&!cg.zoomMode) )//or a player in third person, 25% of the time && groundEnt->client->playerTeam != ent->client->playerTeam//and not on the same team && ent->client->ps.legsAnim != BOTH_JUMPATTACK6 ) )//not in the sideways-spinning jump attack { int knockAnim = BOTH_KNOCKDOWN1; if ( PM_CrouchAnim( groundEnt->client->ps.legsAnim ) ) {//knockdown from crouch knockAnim = BOTH_KNOCKDOWN4; } else { vec3_t gEFwd, gEAngles = {0,groundEnt->client->ps.viewangles[YAW],0}; AngleVectors( gEAngles, gEFwd, NULL, NULL ); if ( DotProduct( ent->client->ps.velocity, gEFwd ) > 50 ) {//pushing him forward knockAnim = BOTH_KNOCKDOWN3; } } NPC_SetAnim( groundEnt, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } } } } client = ent->client; // mark the time, so the connection sprite can be removed client->lastCmdTime = level.time; client->pers.lastCommand = *ucmd; // sanity check the command time to prevent speedup cheating if ( ucmd->serverTime > level.time + 200 ) { ucmd->serverTime = level.time + 200; } if ( ucmd->serverTime < level.time - 1000 ) { ucmd->serverTime = level.time - 1000; } msec = ucmd->serverTime - client->ps.commandTime; if ( msec < 1 ) { msec = 1; } if ( msec > 200 ) { msec = 200; } if ( client->noclip ) { client->ps.pm_type = PM_NOCLIP; } else if ( client->ps.stats[STAT_HEALTH] <= 0 ) { client->ps.pm_type = PM_DEAD; } else { client->ps.pm_type = PM_NORMAL; } //FIXME: if global gravity changes this should update everyone's personal gravity... if ( !(ent->svFlags & SVF_CUSTOM_GRAVITY) ) { if (ent->client->inSpaceIndex) { //in space, so no gravity... client->ps.gravity = 0.0f; } else { client->ps.gravity = g_gravity->value; } } if (!USENEWNAVSYSTEM || ent->s.number==0) { ClientAlterSpeed(ent, ucmd, controlledByPlayer, 0); } //FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) BG_AddPushVecToUcmd( ent, ucmd ); G_CheckClampUcmd( ent, ucmd ); WP_ForcePowersUpdate( ent, ucmd ); //if we have the saber in hand, check for starting a block to reflect shots if ( ent->s.number < MAX_CLIENTS//player || ( ent->NPC && G_JediInNormalAI( ent ) ) )//NPC jedi not in a special AI mode { WP_SaberStartMissileBlockCheck( ent, ucmd ); } // Update the position of the saber, and check to see if we're throwing it if ( client->ps.saberEntityNum != ENTITYNUM_NONE ) { int updates = 1; if ( ent->NPC ) { updates = 3;//simulate player update rate? } for ( int update = 0; update < updates; update++ ) { WP_SaberUpdate( ent, ucmd ); } } //NEED to do this every frame, since these overrides do not go into the save/load data if ( ent->client && ent->s.m_iVehicleNum != 0 && !ent->s.number && !MatrixMode) {//FIXME: extern and read from g_vehicleInfo? Vehicle_t *pPlayerVeh = ent->owner->m_pVehicle; if ( pPlayerVeh && pPlayerVeh->m_pVehicleInfo->cameraOverride ) { // Vehicle Camera Overrides //-------------------------- cg.overrides.active |= ( CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_FOV | CG_OVERRIDE_3RD_PERSON_VOF | CG_OVERRIDE_3RD_PERSON_POF ); cg.overrides.thirdPersonRange = pPlayerVeh->m_pVehicleInfo->cameraRange; cg.overrides.fov = pPlayerVeh->m_pVehicleInfo->cameraFOV; cg.overrides.thirdPersonVertOffset = pPlayerVeh->m_pVehicleInfo->cameraVertOffset; cg.overrides.thirdPersonPitchOffset = pPlayerVeh->m_pVehicleInfo->cameraPitchOffset; if ( pPlayerVeh->m_pVehicleInfo->cameraAlpha ) { cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; } // If In A Speeder (NOT DURING TURBO) //------------------------------------ if ((level.time>pPlayerVeh->m_iTurboTime) && pPlayerVeh->m_pVehicleInfo->type==VH_SPEEDER) { // If Using Strafe And Use Keys //------------------------------ if ((pPlayerVeh->m_ucmd.rightmove!=0) && // (pPlayerVeh->m_pParentEntity->client->ps.speed>=0) && (pPlayerVeh->m_ucmd.buttons&BUTTON_USE) ) { cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; // Turn On Angle Offset cg.overrides.thirdPersonRange *= -2; // Camera In Front Of Player cg.overrides.thirdPersonAngle = (pPlayerVeh->m_ucmd.rightmove>0)?(20):(-20); } // Auto Pullback Of Camera To Show Enemy //--------------------------------------- else { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_ANG; // Turn Off Angle Offset if (ent->enemy) { vec3_t actorDirection; vec3_t enemyDirection; AngleVectors(ent->currentAngles, actorDirection, 0, 0); VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, enemyDirection); float enemyDistance = VectorNormalize(enemyDirection); if (enemyDistance>cg.overrides.thirdPersonRange && enemyDistance<400 && DotProduct(actorDirection, enemyDirection)<-0.5f) { cg.overrides.thirdPersonRange = enemyDistance; } } } } } } else if ( client->ps.eFlags&EF_IN_ATST ) { cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_VOF); cg.overrides.thirdPersonRange = 240; if ( cg_thirdPersonAutoAlpha.integer ) { if ( ent->health > 0 && ent->client->ps.viewangles[PITCH] < 15 && ent->client->ps.viewangles[PITCH] > 0 ) { cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; if ( cg.overrides.thirdPersonAlpha > 0.525f ) { cg.overrides.thirdPersonAlpha -= 0.025f; } else if ( cg.overrides.thirdPersonAlpha > 0.5f ) { cg.overrides.thirdPersonAlpha = 0.5f; } } else if ( cg.overrides.active&CG_OVERRIDE_3RD_PERSON_APH ) { if ( cg.overrides.thirdPersonAlpha > cg_thirdPersonAlpha.value ) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; } else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value-0.1f ) { cg.overrides.thirdPersonAlpha += 0.1f; } else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value ) { cg.overrides.thirdPersonAlpha = cg_thirdPersonAlpha.value; cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; } } } if ( ent->client->ps.viewangles[PITCH] > 0 ) { cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-10; if ( cg.overrides.thirdPersonVertOffset < 0 ) { cg.overrides.thirdPersonVertOffset = 0; } } else if ( ent->client->ps.viewangles[PITCH] < 0 ) { cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-5; if ( cg.overrides.thirdPersonVertOffset > 300 ) { cg.overrides.thirdPersonVertOffset = 300; } } else { cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonVertOffset = 200; } } //play/stop any looping sounds tied to controlled movement G_CheckMovingLoopingSounds( ent, ucmd ); //remember your last angles VectorCopy ( ent->client->ps.viewangles, ent->lastAngles ); // set up for pmove oldEventSequence = client->ps.eventSequence; memset( &pm, 0, sizeof(pm) ); pm.gent = ent; pm.ps = &client->ps; pm.cmd = *ucmd; // pm.tracemask = MASK_PLAYERSOLID; // used differently for navgen pm.tracemask = ent->clipmask; pm.trace = gi.trace; pm.pointcontents = gi.pointcontents; pm.debugLevel = g_debugMove->integer; pm.noFootsteps = 0;//( g_dmflags->integer & DF_NO_FOOTSTEPS ) > 0; if ( ent->client && ent->NPC ) { pm.cmd.weapon = ent->client->ps.weapon; } VectorCopy( client->ps.origin, oldOrigin ); // perform a pmove Pmove( &pm ); pm.gent = 0; ProcessGenericCmd(ent, pm.cmd.generic_cmd); // save results of pmove if ( ent->client->ps.eventSequence != oldEventSequence ) { ent->eventTime = level.time; { int seq; seq = (ent->client->ps.eventSequence-1) & (MAX_PS_EVENTS-1); ent->s.event = ent->client->ps.events[ seq ] | ( ( ent->client->ps.eventSequence & 3 ) << 8 ); ent->s.eventParm = ent->client->ps.eventParms[ seq ]; } } PlayerStateToEntityState( &ent->client->ps, &ent->s ); VectorCopy ( ent->currentOrigin, ent->lastOrigin ); #if 1 // use the precise origin for linking VectorCopy( ent->client->ps.origin, ent->currentOrigin ); #else //We don't use prediction anymore, so screw this // use the snapped origin for linking so it matches client predicted versions VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); #endif //Had to leave this in, some legacy code must still be using s.angles //Shouldn't interfere with interpolation of angles, should it? VectorCopy(ent->client->ps.viewangles , ent->currentAngles ); // if (pVeh) // { // gi.Printf("%d\n", ucmd->angles[2]); // } VectorCopy( pm.mins, ent->mins ); VectorCopy( pm.maxs, ent->maxs ); ent->waterlevel = pm.waterlevel; ent->watertype = pm.watertype; _VectorCopy( ucmd->angles, client->pers.cmd_angles ); // execute client events ClientEvents( ent, oldEventSequence ); if ( pm.useEvent ) { //TODO: Use TryUse( ent ); } // link entity now, after any personal teleporters have been used gi.linkentity( ent ); ent->client->hiddenDist = 0; if ( !ent->client->noclip ) { G_TouchTriggersLerped( ent ); } // touch other objects ClientImpacts( ent, &pm ); // swap and latch button actions client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; client->latched_buttons |= client->buttons & ~client->oldbuttons; // check for respawning if ( client->ps.stats[STAT_HEALTH] <= 0 ) { // wait for the attack button to be pressed if ( ent->NPC == NULL && level.time > client->respawnTime ) { // don't allow respawn if they are still flying through the // air, unless 10 extra seconds have passed, meaning something // strange is going on, like the corpse is caught in a wind tunnel /* if ( level.time < client->respawnTime + 10000 ) { if ( client->ps.groundEntityNum == ENTITYNUM_NONE ) { return; } } */ // pressing attack or use is the normal respawn method if ( ucmd->buttons & ( BUTTON_ATTACK ) ) { respawn( ent ); } } if ( ent && !ent->s.number && ent->enemy && ent->enemy != ent && ent->enemy->s.number < ENTITYNUM_WORLD && ent->enemy->inuse && !(cg.overrides.active&CG_OVERRIDE_3RD_PERSON_ANG) ) {//keep facing enemy vec3_t deadDir; float deadYaw; VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, deadDir ); deadYaw = AngleNormalize180( vectoyaw ( deadDir ) ); if ( deadYaw > ent->client->ps.stats[STAT_DEAD_YAW] + 1 ) { ent->client->ps.stats[STAT_DEAD_YAW]++; } else if ( deadYaw < ent->client->ps.stats[STAT_DEAD_YAW] - 1 ) { ent->client->ps.stats[STAT_DEAD_YAW]--; } else { ent->client->ps.stats[STAT_DEAD_YAW] = deadYaw; } } return; } // perform once-a-second actions ClientTimerActions( ent, msec ); ClientEndPowerUps( ent ); //try some idle anims on ent if getting no input and not moving for some time G_CheckClientIdle( ent, ucmd ); } /* ================== ClientThink A new command has arrived from the client ================== */ extern void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ); extern qboolean PM_GentCantJump( gentity_t *gent ); extern qboolean PM_WeaponOkOnVehicle( int weapon ); void ClientThink( int clientNum, usercmd_t *ucmd ) { gentity_t *ent; qboolean restore_ucmd = qfalse; usercmd_t sav_ucmd = {0}; ent = g_entities + clientNum; if ( ent->s.number<MAX_CLIENTS ) { if ( ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_WORLD ) {//you're controlling another NPC gentity_t *controlled = &g_entities[ent->client->ps.viewEntity]; qboolean freed = qfalse; if ( controlled->NPC && controlled->NPC->controlledTime && ent->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) {//An NPC I'm controlling with mind trick if ( controlled->NPC->controlledTime < level.time ) {//time's up! G_ClearViewEntity( ent ); freed = qtrue; } else if ( ucmd->upmove > 0 ) {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? G_ClearViewEntity( ent ); ucmd->upmove = 0;//ucmd->buttons = 0; //stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } } else if ( controlled->client //an NPC && PM_GentCantJump( controlled ) //that cannot jump && controlled->client->moveType != MT_FLYSWIM ) //and does not use upmove to fly {//these types use jump to get out if ( ucmd->upmove > 0 ) {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? G_ClearViewEntity( ent ); ucmd->upmove = 0;//ucmd->buttons = 0; //stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } } if ( !freed ) {//still controlling, save off my ucmd and clear it for my actual run through pmove restore_ucmd = qtrue; memcpy( &sav_ucmd, ucmd, sizeof( usercmd_t ) ); memset( ucmd, 0, sizeof( usercmd_t ) ); //to keep pointing in same dir, need to set ucmd->angles ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; if ( controlled->NPC ) { VectorClear( controlled->client->ps.moveDir ); controlled->client->ps.speed = (sav_ucmd.buttons&BUTTON_WALKING)?controlled->NPC->stats.walkSpeed:controlled->NPC->stats.runSpeed; } } else { ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; } } else if ( ent->client->NPC_class == CLASS_ATST ) { if ( ucmd->upmove > 0 ) {//get out of ATST GEntity_UseFunc( ent->activator, ent, ent ); ucmd->upmove = 0;//ucmd->buttons = 0; } } PM_CheckForceUseButton( ent, ucmd ); } Vehicle_t *pVeh = NULL; // Rider logic. // NOTE: Maybe this should be extracted into a RiderUpdate() within the vehicle. if ( ( pVeh = G_IsRidingVehicle( ent ) ) != 0 ) { // If we're still in the vehicle... if ( pVeh->m_pVehicleInfo->UpdateRider( pVeh, ent, ucmd ) ) { restore_ucmd = qtrue; memcpy( &sav_ucmd, ucmd, sizeof( usercmd_t ) ); memset( ucmd, 0, sizeof( usercmd_t ) ); //to keep pointing in same dir, need to set ucmd->angles //ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; //ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; //ucmd->angles[ROLL] = 0; ucmd->angles[PITCH] = sav_ucmd.angles[PITCH]; ucmd->angles[YAW] = sav_ucmd.angles[YAW]; ucmd->angles[ROLL] = sav_ucmd.angles[ROLL]; //if ( sav_ucmd.weapon != ent->client->ps.weapon && PM_WeaponOkOnVehicle( sav_ucmd.weapon ) ) {//trying to change weapons to a valid weapon for this vehicle, to preserve this weapon change command ucmd->weapon = sav_ucmd.weapon; } //else {//keep our current weapon // ucmd->weapon = ent->client->ps.weapon; // if ( ent->client->ps.weapon != WP_NONE ) {//not changing weapons and we are using one of our weapons, not using vehicle weapon //so we actually want to do our fire weapon on us, not the vehicle ucmd->buttons = (sav_ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)); // sav_ucmd.buttons &= ~ucmd->buttons; } } } } ent->client->usercmd = *ucmd; // if ( !g_syncronousClients->integer ) { ClientThink_real( ent, ucmd ); } // If a vehicle, make sure to attach our driver and passengers here (after we pmove, which is done in Think_Real)) if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) { pVeh = ent->m_pVehicle; pVeh->m_pVehicleInfo->AttachRiders( pVeh ); } // ClientThink_real can end up freeing this ent, need to check if ( restore_ucmd && ent->client ) {//restore ucmd for later so NPC you're controlling can refer to them memcpy( &ent->client->usercmd, &sav_ucmd, sizeof( usercmd_t ) ); } if ( ent->s.number ) {//NPCs drown, burn from lava, etc, also P_WorldEffects( ent ); } } void ClientEndPowerUps( gentity_t *ent ) { int i; if ( ent == NULL || ent->client == NULL ) { return; } // turn off any expired powerups for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { if ( ent->client->ps.powerups[ i ] < level.time ) { ent->client->ps.powerups[ i ] = 0; } } } /* ============== ClientEndFrame Called at the end of each server frame for each connected client A fast client will have multiple ClientThink for each ClientEdFrame, while a slow client may have multiple ClientEndFrame between ClientThink. ============== */ void ClientEndFrame( gentity_t *ent ) { // // If the end of unit layout is displayed, don't give // the player any normal movement attributes // // burn from lava, etc P_WorldEffects (ent); // apply all the damage taken this frame P_DamageFeedback (ent); // add the EF_CONNECTION flag if we haven't gotten commands recently /* if ( level.time - ent->client->lastCmdTime > 1000 ) { ent->s.eFlags |= EF_CONNECTION; } else { ent->s.eFlags &= ~EF_CONNECTION; } */ ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... // G_SetClientSound (ent); }
412
0.991168
1
0.991168
game-dev
MEDIA
0.633705
game-dev
0.689442
1
0.689442
Kaedrin/nwn2cc
2,002
NWN2 WIP/Source/ScriptMaster_146/cmi_s0_linkprcpt.NSS
//:://///////////////////////////////////////////// //:: Blessed Aim //:: cmi_s0_blessedaim //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: June 28, 2007 //::////////////////////////////////////////////// #include "cmi_ginc_spells" #include "x2_inc_spellhook" #include "x0_i0_spells" void main() { if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } int nBonus; object oTarget = GetFirstObjectInShape(SHAPE_SPHERE, RADIUS_SIZE_HUGE, GetLocation(OBJECT_SELF)); while(GetIsObjectValid(oTarget)) { if (spellsIsTarget(oTarget, SPELL_TARGET_ALLALLIES, OBJECT_SELF)) { nBonus++; } oTarget = GetNextObjectInShape(SHAPE_SPHERE, RADIUS_SIZE_HUGE, GetLocation(OBJECT_SELF)); } nBonus = nBonus * 2; if (nBonus > 20) //Sanity check nBonus = 20; effect eSkill1 = EffectSkillIncrease(SKILL_SPOT, nBonus); effect eSkill2 = EffectSkillIncrease(SKILL_LISTEN, nBonus); effect eVis = EffectVisualEffect(VFX_DUR_SPELL_HEROISM); effect eLink = EffectLinkEffects(eSkill1, eSkill2); eLink = EffectLinkEffects(eLink, eVis); int nSpellId = GetSpellId(); int nCasterLvl = GetPalRngCasterLevel(); float fDuration = TurnsToSeconds( nCasterLvl ); fDuration = ApplyMetamagicDurationMods(fDuration); float fDelay; oTarget = GetFirstObjectInShape(SHAPE_SPHERE, RADIUS_SIZE_HUGE, GetLocation(OBJECT_SELF)); while(GetIsObjectValid(oTarget)) { if (spellsIsTarget(oTarget, SPELL_TARGET_ALLALLIES, OBJECT_SELF)) { fDelay = GetRandomDelay(0.4, 1.1); RemoveEffectsFromSpell(oTarget, nSpellId); SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF,nSpellId, FALSE)); DelayCommand(fDelay, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oTarget, fDuration)); } oTarget = GetNextObjectInShape(SHAPE_SPHERE, RADIUS_SIZE_HUGE, GetLocation(OBJECT_SELF)); } }
412
0.742454
1
0.742454
game-dev
MEDIA
0.965959
game-dev
0.966775
1
0.966775
OvercastNetwork/SportBukkit
4,290
snapshot/Bukkit/src/main/java/org/bukkit/command/FormattedCommandAlias.java
package org.bukkit.command; import java.util.ArrayList; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.RemoteServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent; public class FormattedCommandAlias extends Command { private final String[] formatStrings; public FormattedCommandAlias(String alias, String[] formatStrings) { super(alias); this.formatStrings = formatStrings; } @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { boolean result = false; ArrayList<String> commands = new ArrayList<String>(); for (String formatString : formatStrings) { try { commands.add(buildCommand(formatString, args)); } catch (Throwable throwable) { if (throwable instanceof IllegalArgumentException) { sender.sendMessage(throwable.getMessage()); } else { sender.sendMessage(org.bukkit.ChatColor.RED + "An internal error occurred while attempting to perform this command"); } return false; } } for (String command : commands) { result |= Bukkit.dispatchCommand(sender, command); } return result; } private String buildCommand(String formatString, String[] args) { int index = formatString.indexOf("$"); while (index != -1) { int start = index; if (index > 0 && formatString.charAt(start - 1) == '\\') { formatString = formatString.substring(0, start - 1) + formatString.substring(start); index = formatString.indexOf("$", index); continue; } boolean required = false; if (formatString.charAt(index + 1) == '$') { required = true; // Move index past the second $ index++; } // Move index past the $ index++; int argStart = index; while (index < formatString.length() && inRange(((int) formatString.charAt(index)) - 48, 0, 9)) { // Move index past current digit index++; } // No numbers found if (argStart == index) { throw new IllegalArgumentException("Invalid replacement token"); } int position = Integer.valueOf(formatString.substring(argStart, index)); // Arguments are not 0 indexed if (position == 0) { throw new IllegalArgumentException("Invalid replacement token"); } // Convert position to 0 index position--; boolean rest = false; if (index < formatString.length() && formatString.charAt(index) == '-') { rest = true; // Move index past the - index++; } int end = index; if (required && position >= args.length) { throw new IllegalArgumentException("Missing required argument " + (position + 1)); } StringBuilder replacement = new StringBuilder(); if (rest && position < args.length) { for (int i = position; i < args.length; i++) { if (i != position) { replacement.append(' '); } replacement.append(args[i]); } } else if (position < args.length) { replacement.append(args[position]); } formatString = formatString.substring(0, start) + replacement.toString() + formatString.substring(end); // Move index past the replaced data so we don't process it again index = start + replacement.length(); // Move to the next replacement token index = formatString.indexOf("$", index); } return formatString; } private static boolean inRange(int i, int j, int k) { return i >= j && i <= k; } }
412
0.937501
1
0.937501
game-dev
MEDIA
0.625019
game-dev
0.875123
1
0.875123
0ceal0t/Dalamud-VFXEditor
1,318
VFXEditor/Formats/SklbFormat/Bones/SklbBoneListView.cs
using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using Dalamud.Bindings.ImGui; using System.Collections.Generic; using VfxEditor.SklbFormat.Bones; using VfxEditor.Utils; namespace VfxEditor.Formats.SklbFormat.Bones { public class SklbBoneListView { private readonly List<SklbBone> Bones; private SklbBone DraggingItem; public SklbBoneListView( List<SklbBone> bones ) { Bones = bones; } public void Draw() { using var child = ImRaii.Child( "Child" ); using( var disabled = ImRaii.Disabled() ) { using( var font = ImRaii.PushFont( UiBuilder.IconFont ) ) { ImGui.Text( FontAwesomeIcon.InfoCircle.ToIconString() ); } ImGui.SameLine(); ImGui.Text( "Bones can be re-ordered by dragging them" ); } foreach( var (bone, idx) in Bones.WithIndex() ) { var text = $"[{idx:D3}] {bone.Name.Value}"; ImGui.TreeNodeEx( text, ImGuiTreeNodeFlags.Framed | ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.FramePadding | ImGuiTreeNodeFlags.NoTreePushOnOpen ); if( UiUtils.DrawDragDrop( Bones, bone, text, ref DraggingItem, "BONE-LIST", true ) ) break; } } } }
412
0.729832
1
0.729832
game-dev
MEDIA
0.727057
game-dev
0.702817
1
0.702817
kripken/intensityengine
1,720
src/thirdparty/bullet/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_COLLISION_CONFIGURATION #define BT_COLLISION_CONFIGURATION struct btCollisionAlgorithmCreateFunc; class btStackAlloc; class btPoolAllocator; ///btCollisionConfiguration allows to configure Bullet collision detection ///stack allocator size, default collision algorithms and persistent manifold pool size ///@todo: describe the meaning class btCollisionConfiguration { public: virtual ~btCollisionConfiguration() { } ///memory pools virtual btPoolAllocator* getPersistentManifoldPool() = 0; virtual btPoolAllocator* getCollisionAlgorithmPool() = 0; virtual btStackAlloc* getStackAllocator() = 0; virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) =0; }; #endif //BT_COLLISION_CONFIGURATION
412
0.796861
1
0.796861
game-dev
MEDIA
0.997262
game-dev
0.618357
1
0.618357
PentestSS13/Pentest
5,711
code/modules/modular_computers/file_system/programs/arcade.dm
/datum/computer_file/program/arcade filename = "dsarcade" filedesc = "Donksoft Micro Arcade" program_icon_state = "arcade" extended_desc = "This port of the classic game 'Outbomb Cuban Pete', redesigned to run on tablets, with thrilling graphics and chilling storytelling." requires_ntnet = FALSE size = 6 tgui_id = "NtosArcade" program_icon = "gamepad" ///Returns TRUE if the game is being played. var/game_active = TRUE ///This disables buttom actions from having any impact if TRUE. Resets to FALSE when the player is allowed to make an action again. var/pause_state = FALSE var/boss_hp = 45 var/boss_mp = 15 var/player_hp = 30 var/player_mp = 10 var/ticket_count = 0 ///Shows what text is shown on the app, usually showing the log of combat actions taken by the player. var/heads_up = "Nanotrasen says, winners make us money." var/boss_name = "Cuban Pete's Minion" ///Determines which boss image to use on the UI. var/boss_id = 1 /datum/computer_file/program/arcade/proc/game_check(mob/user) sleep(5) usr?.mind?.adjust_experience(/datum/skill/gaming, 1) if(boss_hp <= 0) heads_up = "You have crushed [boss_name]! Rejoice!" playsound(computer.loc, 'sound/arcade/win.ogg', 25) game_active = FALSE program_icon_state = "arcade_off" if(istype(computer)) computer.update_appearance() ticket_count += 1 usr?.mind?.adjust_experience(/datum/skill/gaming, 50) sleep(10) else if(player_hp <= 0 || player_mp <= 0) heads_up = "You have been defeated... how will the station survive?" playsound(computer.loc, 'sound/arcade/lose.ogg', 25) game_active = FALSE program_icon_state = "arcade_off" if(istype(computer)) computer.update_appearance() usr?.mind?.adjust_experience(/datum/skill/gaming, 10) sleep(10) /datum/computer_file/program/arcade/proc/enemy_check(mob/user) var/boss_attackamt = 0 //Spam protection from boss attacks as well. var/boss_mpamt = 0 var/bossheal = 0 if(pause_state == TRUE) boss_attackamt = rand(3,6) boss_mpamt = rand (2,4) bossheal = rand (4,6) if(game_active == FALSE) return if (boss_mp <= 5) heads_up = "[boss_mpamt] magic power has been stolen from you!" playsound(computer.loc, 'sound/arcade/steal.ogg', 25, TRUE) player_mp -= boss_mpamt boss_mp += boss_mpamt else if(boss_mp > 5 && boss_hp <12) heads_up = "[boss_name] heals for [bossheal] health!" playsound(computer.loc, 'sound/arcade/heal.ogg', 25, TRUE) boss_hp += bossheal boss_mp -= boss_mpamt else heads_up = "[boss_name] attacks you for [boss_attackamt] damage!" playsound(computer.loc, 'sound/arcade/hit.ogg', 25, TRUE) player_hp -= boss_attackamt pause_state = FALSE game_check() /datum/computer_file/program/arcade/ui_assets(mob/user) return list( get_asset_datum(/datum/asset/simple/arcade), ) /datum/computer_file/program/arcade/ui_data(mob/user) var/list/data = get_header_data() data["Hitpoints"] = boss_hp data["PlayerHitpoints"] = player_hp data["PlayerMP"] = player_mp data["TicketCount"] = ticket_count data["GameActive"] = game_active data["PauseState"] = pause_state data["Status"] = heads_up data["BossID"] = "boss[boss_id].gif" return data /datum/computer_file/program/arcade/ui_act(action, list/params) . = ..() if(.) return var/obj/item/computer_hardware/printer/printer if(computer) printer = computer.all_components[MC_PRINT] var/gamerSkillLevel = usr.mind?.get_skill_level(/datum/skill/gaming) var/gamerSkill = usr.mind?.get_skill_modifier(/datum/skill/gaming, SKILL_RANDS_MODIFIER) switch(action) if("Attack") var/attackamt = 0 //Spam prevention. if(pause_state == FALSE) attackamt = rand(2,6) + rand(0, gamerSkill) pause_state = TRUE heads_up = "You attack for [attackamt] damage." playsound(computer.loc, 'sound/arcade/hit.ogg', 25, TRUE) boss_hp -= attackamt sleep(10) game_check() enemy_check() return TRUE if("Heal") var/healamt = 0 //More Spam Prevention. var/healcost = 0 if(pause_state == FALSE) healamt = rand(6,8) + rand(0, gamerSkill) var/maxPointCost = 3 if(gamerSkillLevel >= SKILL_LEVEL_JOURNEYMAN) maxPointCost = 2 healcost = rand(1, maxPointCost) pause_state = TRUE heads_up = "You heal for [healamt] damage." playsound(computer.loc, 'sound/arcade/heal.ogg', 25, TRUE) player_hp += healamt player_mp -= healcost sleep(10) game_check() enemy_check() return TRUE if("Recharge_Power") var/rechargeamt = 0 //As above. if(pause_state == FALSE) rechargeamt = rand(4,7) + rand(0, gamerSkill) pause_state = TRUE heads_up = "You regain [rechargeamt] magic power." playsound(computer.loc, 'sound/arcade/mana.ogg', 25, TRUE) player_mp += rechargeamt sleep(10) game_check() enemy_check() return TRUE if("Dispense_Tickets") if(!printer) to_chat(usr, span_notice("Hardware error: A printer is required to redeem tickets.")) return if(printer.stored_paper <= 0) to_chat(usr, span_notice("Hardware error: Printer is out of paper.")) return else computer.visible_message(span_notice("\The [computer] prints out paper.")) if(ticket_count >= 1) new /obj/item/stack/arcadeticket((get_turf(computer)), 1) to_chat(usr, span_notice("[src] dispenses a ticket!")) ticket_count -= 1 printer.stored_paper -= 1 else to_chat(usr, span_notice("You don't have any stored tickets!")) return TRUE if("Start_Game") game_active = TRUE boss_hp = 45 player_hp = 30 player_mp = 10 heads_up = "You stand before [boss_name]! Prepare for battle!" program_icon_state = "arcade" boss_id = rand(1,6) pause_state = FALSE if(istype(computer)) computer.update_appearance()
412
0.860186
1
0.860186
game-dev
MEDIA
0.97112
game-dev
0.970078
1
0.970078
cadaver/turso3d
5,358
Turso3D/Object/Serializable.h
// For conditions of distribution and use, see copyright notice in License.txt #pragma once #include "Attribute.h" #include "Object.h" class ObjectResolver; /// Base class for objects with automatic serialization using attributes. class Serializable : public Object { public: /// Load from binary stream. Store object ref attributes to be resolved later. virtual void Load(Stream& source, ObjectResolver& resolver); /// Save to binary stream. virtual void Save(Stream& dest); /// Load from JSON data. Optionally store object ref attributes to be resolved later. virtual void LoadJSON(const JSONValue& source, ObjectResolver& resolver); /// Save as JSON data. virtual void SaveJSON(JSONValue& dest); /// Return id for referring to the object in serialization. virtual unsigned Id() const { return 0; } /// Set attribute value from memory. void SetAttributeValue(Attribute* attr, const void* source); /// Copy attribute value to memory. void AttributeValue(Attribute* attr, void* dest); /// Set attribute value, template version. Return true if value was right type. template <class T> bool SetAttributeValue(Attribute* attr, const T& source) { AttributeImpl<T>* typedAttr = dynamic_cast<AttributeImpl<T>*>(attr); if (typedAttr) { typedAttr->SetValue(this, source); return true; } else return false; } /// Copy attribute value, template version. Return true if value was right type. template <class T> bool AttributeValue(Attribute* attr, T& dest) { AttributeImpl<T>* typedAttr = dynamic_cast<AttributeImpl<T>*>(attr); if (typedAttr) { typedAttr->Value(this, dest); return true; } else return false; } /// Return attribute value, template version. template <class T> T AttributeValue(Attribute* attr) { AttributeImpl<T>* typedAttr = dynamic_cast<AttributeImpl<T>*>(attr); return typedAttr ? typedAttr->Value(this) : T(); } /// Return the attribute descriptions. Default implementation uses per-class registration. virtual const std::vector<SharedPtr<Attribute> >* Attributes() const; /// Return an attribute description by name, or null if does not exist. Attribute* FindAttribute(const std::string& name) const; /// Return an attribute description by name, or null if does not exist. Attribute* FindAttribute(const char* name) const; /// Register a per-class attribute. If an attribute with the same name already exists, it will be replaced. static void RegisterAttribute(StringHash type, Attribute* attr); /// Copy all base class attributes. static void CopyBaseAttributes(StringHash type, StringHash baseType); /// Copy one base class attribute. static void CopyBaseAttribute(StringHash type, StringHash baseType, const std::string& name); /// Skip binary data of an object's all attributes. static void Skip(Stream& source); /// Register a per-class attribute, template version. Class should always be specified in the function pointers to ensure the attribute is registered to the intended class. template <class T, class U> static void RegisterAttribute(const char* name, U (T::*getFunction)() const, void (T::*setFunction)(U), const U& defaultValue = U(), const char** enumNames = 0) { RegisterAttribute(T::TypeStatic(), new AttributeImpl<U>(name, new AttributeAccessorImpl<T, U>(getFunction, setFunction), defaultValue, enumNames)); } /// Register a per-class attribute with reference access, template version. Class should always be specified in the function pointers to ensure the attribute is registered to the intended class. template <class T, class U> static void RegisterRefAttribute(const char* name, const U& (T::*getFunction)() const, void (T::*setFunction)(const U&), const U& defaultValue = U(), const char** enumNames = 0) { RegisterAttribute(T::TypeStatic(), new AttributeImpl<U>(name, new RefAttributeAccessorImpl<T, U>(getFunction, setFunction), defaultValue, enumNames)); } /// Register a per-class attribute with mixed reference access, template version. Class should always be specified in the function pointers to ensure the attribute is registered to the intended class. template <class T, class U> static void RegisterMixedRefAttribute(const char* name, U (T::*getFunction)() const, void (T::*setFunction)(const U&), const U& defaultValue = U(), const char** enumNames = 0) { RegisterAttribute(T::TypeStatic(), new AttributeImpl<U>(name, new MixedRefAttributeAccessorImpl<T, U>(getFunction, setFunction), defaultValue, enumNames)); } /// Copy all base class attributes, template version. template <class T, class U> static void CopyBaseAttributes() { CopyBaseAttributes(T::TypeStatic(), U::TypeStatic()); } /// Copy one base class attribute, template version. template <class T, class U> static void CopyBaseAttribute(const std::string& name) { CopyBaseAttribute(T::TypeStatic(), U::TypeStatic(), name); } private: /// Per-class attributes. static std::map<StringHash, std::vector<SharedPtr<Attribute> > > classAttributes; };
412
0.911182
1
0.911182
game-dev
MEDIA
0.351048
game-dev
0.905488
1
0.905488
lancopku/agent-backdoor-attacks
1,719
AgentTuning/AgentTuning/AgentBench.old/src/tasks/card_game/AI_SDK/Python/Action.py
from typing import List, Tuple import time from llm.chatgpt.main import ChatGPT from sdk.ai_client import Action, AIClient, Game import random class AI(AIClient): def __init__(self) -> None: super().__init__() self.chatgpt = ChatGPT() self.fish_id = {"spray": 1, "flame": 2, "eel": 3, "sunfish": 4} self.action_type = {'normal': 0, 'active': 1} def Pick(self, game: Game) -> List[int]: pick_list = [1, 2, 3, 4] # random.shuffle(pick_list) return pick_list def Assert(self, game: Game) -> Tuple[int, int]: return (-1, -1) def Act(self, game: Game) -> Action: enemy_fish = [{'pos': pos, 'id': self.get_enemy_id(pos), 'hp': self.get_enemy_hp(pos), 'atk': 'unknown'} for pos in range(4)] my_fish = [{'pos': pos, 'id': abs(self.get_my_id(pos)), 'hp': self.get_my_hp(pos), 'atk': self.get_my_atk(pos)} for pos in range(4)] # ChatGPT Output action_success, output = self.chatgpt._act(enemy_fish, my_fish, self, game) if not action_success: raise act = Action(game) action_fish_id = self.fish_id[output['pick_fish']] for fish in my_fish: if fish['id'] == action_fish_id: action_fish_pos = fish['pos'] action_type = self.action_type[output['action']] target = int(output['target_position']) act.set_action_fish(action_fish_pos) act.set_action_type(action_type) if action_type == 1 and (action_fish_id == 2 or action_fish_id == 4): act.set_friend_target(target) else: act.set_enemy_target(target) return act
412
0.738077
1
0.738077
game-dev
MEDIA
0.88767
game-dev
0.793687
1
0.793687
qnpiiz/rich-2.0
2,176
src/main/java/net/minecraft/scoreboard/ScoreObjective.java
package net.minecraft.scoreboard; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextComponentUtils; import net.minecraft.util.text.event.HoverEvent; public class ScoreObjective { private final Scoreboard scoreboard; private final String name; private final ScoreCriteria objectiveCriteria; private ITextComponent displayName; private ITextComponent field_237496_e_; private ScoreCriteria.RenderType renderType; public ScoreObjective(Scoreboard p_i49788_1_, String p_i49788_2_, ScoreCriteria p_i49788_3_, ITextComponent p_i49788_4_, ScoreCriteria.RenderType p_i49788_5_) { this.scoreboard = p_i49788_1_; this.name = p_i49788_2_; this.objectiveCriteria = p_i49788_3_; this.displayName = p_i49788_4_; this.field_237496_e_ = this.func_237498_g_(); this.renderType = p_i49788_5_; } public Scoreboard getScoreboard() { return this.scoreboard; } public String getName() { return this.name; } public ScoreCriteria getCriteria() { return this.objectiveCriteria; } public ITextComponent getDisplayName() { return this.displayName; } private ITextComponent func_237498_g_() { return TextComponentUtils.wrapWithSquareBrackets(this.displayName.deepCopy().modifyStyle((p_237497_1_) -> { return p_237497_1_.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent(this.name))); })); } public ITextComponent func_197890_e() { return this.field_237496_e_; } public void setDisplayName(ITextComponent p_199864_1_) { this.displayName = p_199864_1_; this.field_237496_e_ = this.func_237498_g_(); this.scoreboard.onObjectiveChanged(this); } public ScoreCriteria.RenderType getRenderType() { return this.renderType; } public void setRenderType(ScoreCriteria.RenderType p_199866_1_) { this.renderType = p_199866_1_; this.scoreboard.onObjectiveChanged(this); } }
412
0.613143
1
0.613143
game-dev
MEDIA
0.581536
game-dev
0.896766
1
0.896766
magarena/magarena
1,586
release/Magarena/scripts/Arcbond.groovy
def dealDamage = new DamageIsDealtTrigger() { @Override public MagicEvent executeTrigger(final MagicGame game, final MagicPermanent permanent, final MagicDamage damage) { return damage.getTarget() == permanent ? new MagicEvent( permanent, damage.getAmount(), this, "SN deals RN damage to each other creature and each player." ): MagicEvent.NONE; } @Override public void executeEvent(final MagicGame game, final MagicEvent event) { final int amount = event.getRefInt(); CREATURE.except(event.getPermanent()).filter(event) each { game.doAction(new DealDamageAction(event.getSource(), it, amount)); } game.getAPNAP() each { game.doAction(new DealDamageAction(event.getSource(), it, amount)); } } }; [ new MagicSpellCardEvent() { @Override public MagicEvent getEvent(final MagicCardOnStack cardOnStack,final MagicPayedCost payedCost) { return new MagicEvent( cardOnStack, TARGET_CREATURE, this, "Whenever target creature\$ is dealt damage this turn, it deals that much damage to each other creature and each player." ); } @Override public void executeEvent(final MagicGame game, final MagicEvent event) { event.processTargetPermanent(game, { game.doAction(new AddTurnTriggerAction(it, dealDamage)); }); } } ]
412
0.8831
1
0.8831
game-dev
MEDIA
0.902569
game-dev
0.893605
1
0.893605
AionGermany/aion-germany
3,633
AL-Game/src/com/aionemu/gameserver/taskmanager/tasks/MoveTaskManager.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.taskmanager.tasks; import com.aionemu.gameserver.ai2.event.AIEventType; import com.aionemu.gameserver.ai2.poll.AIQuestion; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.taskmanager.AbstractPeriodicTaskManager; import com.aionemu.gameserver.taskmanager.FIFOSimpleExecutableQueue; import com.aionemu.gameserver.world.zone.ZoneUpdateService; import javolution.util.FastList; import javolution.util.FastMap; /** * @author ATracer * @reworked Rolandas, parallelized by using Fork/Join framework */ public class MoveTaskManager extends AbstractPeriodicTaskManager { private final FastMap<Integer, Creature> movingCreatures = new FastMap<Integer, Creature>().shared(); private final TargetReachedManager targetReachedManager = new TargetReachedManager(); private final TargetTooFarManager targetTooFarManager = new TargetTooFarManager(); private MoveTaskManager() { super(100); } public void addCreature(Creature creature) { movingCreatures.put(creature.getObjectId(), creature); } public void removeCreature(Creature creature) { movingCreatures.remove(creature.getObjectId()); } @Override public void run() { final FastList<Creature> arrivedCreatures = FastList.newInstance(); final FastList<Creature> followingCreatures = FastList.newInstance(); for (FastMap.Entry<Integer, Creature> e = movingCreatures.head(), mapEnd = movingCreatures.tail(); (e = e.getNext()) != mapEnd;) { Creature creature = e.getValue(); creature.getMoveController().moveToDestination(); if (creature.getAi2().poll(AIQuestion.DESTINATION_REACHED)) { movingCreatures.remove(e.getKey()); arrivedCreatures.add(e.getValue()); } else { followingCreatures.add(e.getValue()); } } targetReachedManager.executeAll(arrivedCreatures); targetTooFarManager.executeAll(followingCreatures); FastList.recycle(arrivedCreatures); FastList.recycle(followingCreatures); } public static MoveTaskManager getInstance() { return SingletonHolder.INSTANCE; } private final class TargetReachedManager extends FIFOSimpleExecutableQueue<Creature> { @Override protected void removeAndExecuteFirst() { final Creature creature = removeFirst(); try { creature.getAi2().onGeneralEvent(AIEventType.MOVE_ARRIVED); ZoneUpdateService.getInstance().add(creature); } catch (RuntimeException e) { log.warn("", e); } } } private final class TargetTooFarManager extends FIFOSimpleExecutableQueue<Creature> { @Override protected void removeAndExecuteFirst() { final Creature creature = removeFirst(); try { creature.getAi2().onGeneralEvent(AIEventType.MOVE_VALIDATE); } catch (RuntimeException e) { log.warn("", e); } } } private static final class SingletonHolder { private static final MoveTaskManager INSTANCE = new MoveTaskManager(); } }
412
0.92351
1
0.92351
game-dev
MEDIA
0.957147
game-dev
0.968423
1
0.968423
kiku-jw/TON
2,131
lite-client/third-party/abseil-cpp/absl/strings/internal/resize_uninitialized_test.cc
// Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "absl/strings/internal/resize_uninitialized.h" #include "gtest/gtest.h" namespace { int resize_call_count = 0; struct resizable_string { void resize(size_t) { resize_call_count += 1; } }; int resize_uninitialized_call_count = 0; struct resize_uninitializable_string { void resize(size_t) { resize_call_count += 1; } void resize_uninitialized(size_t) { resize_uninitialized_call_count += 1; } }; TEST(ResizeUninit, WithAndWithout) { resize_call_count = 0; resize_uninitialized_call_count = 0; { resizable_string rs; EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(resize_uninitialized_call_count, 0); EXPECT_FALSE( absl::strings_internal::STLStringSupportsNontrashingResize(&rs)); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(resize_uninitialized_call_count, 0); absl::strings_internal::STLStringResizeUninitialized(&rs, 237); EXPECT_EQ(resize_call_count, 1); EXPECT_EQ(resize_uninitialized_call_count, 0); } resize_call_count = 0; resize_uninitialized_call_count = 0; { resize_uninitializable_string rus; EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(resize_uninitialized_call_count, 0); EXPECT_TRUE( absl::strings_internal::STLStringSupportsNontrashingResize(&rus)); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(resize_uninitialized_call_count, 0); absl::strings_internal::STLStringResizeUninitialized(&rus, 237); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(resize_uninitialized_call_count, 1); } } } // namespace
412
0.969701
1
0.969701
game-dev
MEDIA
0.382488
game-dev
0.918948
1
0.918948
Grimrukh/soulstruct
10,397
src/soulstruct/darksouls1ptde/game_types/param_types.py
"""GameParam types that refer to entry IDs in a certain game parameter table.""" __all__ = [ "BaseParam", "BaseGameParam", "BaseItemParam", "BaseDrawParam", "AIParam", "ArmorParam", "ArmorUpgradeParam", "AttackParam", "BehaviorParam", "BossParam", "BulletParam", "CameraParam", "CharacterParam", "DialogueParam", "FaceGenParam", "GoodParam", "GrowthCurveParam", "ItemLotParam", "KnockbackParam", "MenuColorsParam", "MovementParam", "ObjActParam", "ObjectParam", "PlayerParam", "AccessoryParam", "ShopParam", "SpecialEffectParam", "SpecialEffectVisualParam", "SpellParam", "TerrainParam", "ThrowParam", "UpgradeMaterialParam", "WeaponParam", "WeaponUpgradeParam", "FogParam", "EnvLightTexParam", "BakedLightParam", "ScatteredLightParam", "PointLightParam", "LensFlareParam", "LensFlareSourceParam", "DepthOfFieldParam", "ToneMappingParam", "ToneCorrectionParam", "ShadowParam", "AITyping", "ArmorTyping", "ArmorUpgradeTyping", "AttackTyping", "BehaviorTyping", "BulletTyping", "CameraTyping", "DialogueTyping", "FaceTyping", "GoodTyping", "ItemTyping", "ItemLotTyping", "KnockbackTyping", "AccessoryTyping", "SpecialEffectTyping", "SpellTyping", "TerrainTyping", "UpgradeMaterialTyping", "WeaponTyping", "WeaponUpgradeTyping", ] import typing as tp from soulstruct.base.game_types import BaseParam, BaseGameParam class BaseItemParam(BaseGameParam): """Base class for items. Unfortunately, the naming of item types is inconsistent. There are four types of items, which are internally called 'Weapon', 'Protector', 'Accessory', and 'Good'. (Note that the 'Accessory' type is used for Runes in Bloodborne.) The name 'Equipment' is sometimes used to describe this general item type, and in the internal text of Dark Souls Remastered, the name 'Item' is used to refer to the type 'Good' (which is probably what most people think of when they read the name 'Item'). In Soulstruct, the name 'Item' exclusively refers to this base type (i.e. anything that can appear in your in-game inventory) and the name 'Good' is used for the main item type (i.e. things you do not wear). This is consistent with terms such as ItemLot. The name 'Equipment' is not used. I have also renamed 'Protector' to 'Armor', and 'Accessory' to 'Ring' (with an alias 'Rune'). You can call an instance of any Item to test if the player currently has that item (excluding storage). """ @classmethod def get_event_arg_fmt(cls): return "I" @classmethod def get_item_enum(cls): raise NotImplementedError("You must use a subclass of `BaseItemParam`.") @classmethod def get_param_nickname(cls): raise NotImplementedError class BaseDrawParam(BaseParam): """Base class for DrawParam types.""" @classmethod def get_param_nickname(cls): raise NotImplementedError # region Game Params class AIParam(BaseGameParam): """AI entry.""" @classmethod def get_param_nickname(cls): return "AI" class ArmorParam(BaseItemParam): """Armor entry.""" @classmethod def get_item_enum(cls): from ..events.enums import ItemType return ItemType.Armor @classmethod def get_param_nickname(cls): return "Armor" class ArmorUpgradeParam(BaseGameParam): """ArmorUpgrade entry.""" @classmethod def get_param_nickname(cls): return "ArmorUpgrades" class AttackParam(BaseGameParam): """Attack entry.""" @classmethod def get_param_nickname(cls): raise ValueError("Param nickname for `Attack` could be 'PlayerAttacks' or 'NonPlayerAttacks'.") class BehaviorParam(BaseGameParam): """Behavior entry.""" @classmethod def get_param_nickname(cls): raise ValueError("Param nickname for `Behavior` could be 'PlayerBehaviors' or 'NonPlayerBehaviors'.") class BossParam(BaseGameParam): """Boss (or 'GameArea') param entry.""" @classmethod def get_param_nickname(cls): return "Bosses" class BulletParam(BaseGameParam): """Bullet entry.""" @classmethod def get_param_nickname(cls): return "Bullets" class CameraParam(BaseGameParam): """Camera entry.""" @classmethod def get_param_nickname(cls): return "Cameras" class CharacterParam(BaseGameParam): """Character entry.""" @classmethod def get_param_nickname(cls): return "Characters" class DialogueParam(BaseGameParam): """Dialogue entry.""" @classmethod def get_param_nickname(cls): return "Dialogue" class FaceGenParam(BaseGameParam): """Face entry.""" @classmethod def get_param_nickname(cls): return "FaceGenerators" class GoodParam(BaseItemParam): """Good entry.""" @classmethod def get_item_enum(cls): from ..events.enums import ItemType return ItemType.Good @classmethod def get_param_nickname(cls): return "Goods" class GrowthCurveParam(BaseGameParam): """Growth curve entry.""" @classmethod def get_param_nickname(cls): return "GrowthCurves" class ItemLotParam(BaseGameParam): """ItemLot entry.""" @classmethod def get_event_arg_fmt(cls) -> str: return "i" @classmethod def get_param_nickname(cls): return "ItemLots" class KnockbackParam(BaseGameParam): """Knockback entry.""" @classmethod def get_param_nickname(cls): return "Knockbacks" class MenuColorsParam(BaseGameParam): """MenuColors entry.""" @classmethod def get_param_nickname(cls): return "MenuColors" class MovementParam(BaseGameParam): """Movement entry.""" @classmethod def get_param_nickname(cls): return "Movement" class ObjActParam(BaseGameParam): """ObjAct entry.""" @classmethod def get_param_nickname(cls): return "ObjectActivations" class ObjectParam(BaseGameParam): """Object param. Not to be confused with `ObjActParam`.""" @classmethod def get_param_nickname(cls): return "Objects" class PlayerParam(BaseGameParam): """Player entry.""" @classmethod def get_param_nickname(cls): return "Players" class AccessoryParam(BaseItemParam): """Ring entry.""" @classmethod def get_item_enum(cls): from ..events.enums import ItemType return ItemType.Ring @classmethod def get_param_nickname(cls): return "Rings" class ShopParam(BaseGameParam): """Shop entry.""" @classmethod def get_param_nickname(cls): return "Shops" class SpecialEffectParam(BaseGameParam): """SpecialEffect entry.""" @classmethod def get_param_nickname(cls): return "SpecialEffects" class SpecialEffectVisualParam(BaseGameParam): """SpecialEffectVisuals entry.""" @classmethod def get_param_nickname(cls): return "SpecialEffectVisuals" class SpellParam(BaseGameParam): """Spell entry.""" @classmethod def get_param_nickname(cls): return "Spells" class TerrainParam(BaseGameParam): """Terrain entry.""" @classmethod def get_param_nickname(cls): return "Terrains" class ThrowParam(BaseGameParam): """Throw entry.""" @classmethod def get_param_nickname(cls): return "Throws" class UpgradeMaterialParam(BaseGameParam): """UpgradeMaterial entry.""" @classmethod def get_param_nickname(cls): return "UpgradeMaterials" class WeaponParam(BaseItemParam): """Weapon entry.""" @classmethod def get_item_enum(cls): from ..events.enums import ItemType return ItemType.Weapon @classmethod def get_param_nickname(cls): return "Weapons" class WeaponUpgradeParam(BaseGameParam): """WeaponUpgrade entry.""" @classmethod def get_param_nickname(cls): return "WeaponUpgrades" # endregion # region Draw Params class FogParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "Fog" class EnvLightTexParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "EnvLightTex" class BakedLightParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "BakedLight" class ScatteredLightParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "ScatteredLight" class PointLightParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "PointLights" class LensFlareParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "LensFlares" class LensFlareSourceParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "LensFlareSources" class DepthOfFieldParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "DepthOfField" class ToneMappingParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "ToneMapping" class ShadowParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "Shadows" class ToneCorrectionParam(BaseDrawParam): @classmethod def get_param_nickname(cls): return "ToneCorrection" # endregion AITyping = tp.Union[AIParam, int] AttackTyping = tp.Union[AttackParam, int] BehaviorTyping = tp.Union[BehaviorParam, int] BulletTyping = tp.Union[BulletParam, int] DialogueTyping = tp.Union[DialogueParam, int] ItemTyping = tp.Union[BaseItemParam, int] WeaponTyping = tp.Union[WeaponParam, int] ArmorTyping = tp.Union[ArmorParam, int] AccessoryTyping = tp.Union[AccessoryParam, int] GoodTyping = tp.Union[GoodParam, int] CameraTyping = tp.Union[CameraParam, int] FaceTyping = tp.Union[FaceGenParam, int] ItemLotTyping = tp.Union[ItemLotParam, int] KnockbackTyping = tp.Union[KnockbackParam, int] SpecialEffectTyping = tp.Union[SpecialEffectParam, int] SpellTyping = tp.Union[SpellParam, int] TerrainTyping = tp.Union[TerrainParam, int] UpgradeMaterialTyping = tp.Union[UpgradeMaterialParam, int] WeaponUpgradeTyping = tp.Union[WeaponUpgradeParam, int] ArmorUpgradeTyping = tp.Union[ArmorUpgradeParam, int]
412
0.775194
1
0.775194
game-dev
MEDIA
0.856641
game-dev
0.694396
1
0.694396
frankfenghua/ios
15,436
Creating Games with cocos2d for iPhone/9007OS_Code bundle/Chapter 05 -Brick/ch5-brick/libs/Box2D/Collision/b2CollideEdge.cpp
/* * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> // Compute contact points for edge versus circle. // This accounts for edge connectivity. void b2CollideEdgeAndCircle(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2CircleShape* circleB, const b2Transform& xfB) { manifold->pointCount = 0; // Compute circle in frame of edge b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; b2Vec2 e = B - A; // Barycentric coordinates float32 u = b2Dot(e, B - Q); float32 v = b2Dot(e, Q - A); float32 radius = edgeA->m_radius + circleB->m_radius; b2ContactFeature cf; cf.indexB = 0; cf.typeB = b2ContactFeature::e_vertex; // Region A if (v <= 0.0f) { b2Vec2 P = A; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA->m_hasVertex0) { b2Vec2 A1 = edgeA->m_vertex0; b2Vec2 B1 = A; b2Vec2 e1 = B1 - A1; float32 u1 = b2Dot(e1, B1 - Q); // Is the circle in Region AB of the previous edge? if (u1 > 0.0f) { return; } } cf.indexA = 0; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region B if (u <= 0.0f) { b2Vec2 P = B; b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA->m_hasVertex3) { b2Vec2 B2 = edgeA->m_vertex3; b2Vec2 A2 = B; b2Vec2 e2 = B2 - A2; float32 v2 = b2Dot(e2, Q - A2); // Is the circle in Region AB of the next edge? if (v2 > 0.0f) { return; } } cf.indexA = 1; cf.typeA = b2ContactFeature::e_vertex; manifold->pointCount = 1; manifold->type = b2Manifold::e_circles; manifold->localNormal.SetZero(); manifold->localPoint = P; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; return; } // Region AB float32 den = b2Dot(e, e); b2Assert(den > 0.0f); b2Vec2 P = (1.0f / den) * (u * A + v * B); b2Vec2 d = Q - P; float32 dd = b2Dot(d, d); if (dd > radius * radius) { return; } b2Vec2 n(-e.y, e.x); if (b2Dot(n, Q - A) < 0.0f) { n.Set(-n.x, -n.y); } n.Normalize(); cf.indexA = 0; cf.typeA = b2ContactFeature::e_face; manifold->pointCount = 1; manifold->type = b2Manifold::e_faceA; manifold->localNormal = n; manifold->localPoint = A; manifold->points[0].id.key = 0; manifold->points[0].id.cf = cf; manifold->points[0].localPoint = circleB->m_p; } // This structure is used to keep track of the best separating axis. struct b2EPAxis { enum Type { e_unknown, e_edgeA, e_edgeB }; Type type; int32 index; float32 separation; }; // This holds polygon B expressed in frame A. struct b2TempPolygon { b2Vec2 vertices[b2_maxPolygonVertices]; b2Vec2 normals[b2_maxPolygonVertices]; int32 count; }; // Reference face used for clipping struct b2ReferenceFace { int32 i1, i2; b2Vec2 v1, v2; b2Vec2 normal; b2Vec2 sideNormal1; float32 sideOffset1; b2Vec2 sideNormal2; float32 sideOffset2; }; // This class collides and edge and a polygon, taking into account edge adjacency. struct b2EPCollider { void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB); b2EPAxis ComputeEdgeSeparation(); b2EPAxis ComputePolygonSeparation(); enum VertexType { e_isolated, e_concave, e_convex }; b2TempPolygon m_polygonB; b2Transform m_xf; b2Vec2 m_centroidB; b2Vec2 m_v0, m_v1, m_v2, m_v3; b2Vec2 m_normal0, m_normal1, m_normal2; b2Vec2 m_normal; VertexType m_type1, m_type2; b2Vec2 m_lowerLimit, m_upperLimit; float32 m_radius; bool m_front; }; // Algorithm: // 1. Classify v1 and v2 // 2. Classify polygon centroid as front or back // 3. Flip normal if necessary // 4. Initialize normal range to [-pi, pi] about face normal // 5. Adjust normal range according to adjacent edges // 6. Visit each separating axes, only accept axes within the range // 7. Return if _any_ axis indicates separation // 8. Clip void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { m_xf = b2MulT(xfA, xfB); m_centroidB = b2Mul(m_xf, polygonB->m_centroid); m_v0 = edgeA->m_vertex0; m_v1 = edgeA->m_vertex1; m_v2 = edgeA->m_vertex2; m_v3 = edgeA->m_vertex3; bool hasVertex0 = edgeA->m_hasVertex0; bool hasVertex3 = edgeA->m_hasVertex3; b2Vec2 edge1 = m_v2 - m_v1; edge1.Normalize(); m_normal1.Set(edge1.y, -edge1.x); float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); float32 offset0 = 0.0f, offset2 = 0.0f; bool convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { b2Vec2 edge0 = m_v1 - m_v0; edge0.Normalize(); m_normal0.Set(edge0.y, -edge0.x); convex1 = b2Cross(edge0, edge1) >= 0.0f; offset0 = b2Dot(m_normal0, m_centroidB - m_v0); } // Is there a following edge? if (hasVertex3) { b2Vec2 edge2 = m_v3 - m_v2; edge2.Normalize(); m_normal2.Set(edge2.y, -edge2.x); convex2 = b2Cross(edge1, edge2) > 0.0f; offset2 = b2Dot(m_normal2, m_centroidB - m_v2); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } } else if (convex1) { m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal1; } } else if (convex2) { m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal0; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = -m_normal0; } } } else if (hasVertex0) { if (convex1) { m_front = offset0 >= 0.0f || offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal0; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } } else { m_front = offset0 >= 0.0f && offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = -m_normal0; } } } else if (hasVertex3) { if (convex2) { m_front = offset1 >= 0.0f || offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal2; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } } else { m_front = offset1 >= 0.0f && offset2 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = -m_normal2; m_upperLimit = m_normal1; } } } else { m_front = offset1 >= 0.0f; if (m_front) { m_normal = m_normal1; m_lowerLimit = -m_normal1; m_upperLimit = -m_normal1; } else { m_normal = -m_normal1; m_lowerLimit = m_normal1; m_upperLimit = m_normal1; } } // Get polygonB in frameA m_polygonB.count = polygonB->m_vertexCount; for (int32 i = 0; i < polygonB->m_vertexCount; ++i) { m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); } m_radius = 2.0f * b2_polygonRadius; manifold->pointCount = 0; b2EPAxis edgeAxis = ComputeEdgeSeparation(); // If no valid normal can be found than this edge should not collide. if (edgeAxis.type == b2EPAxis::e_unknown) { return; } if (edgeAxis.separation > m_radius) { return; } b2EPAxis polygonAxis = ComputePolygonSeparation(); if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) { return; } // Use hysteresis for jitter reduction. const float32 k_relativeTol = 0.98f; const float32 k_absoluteTol = 0.001f; b2EPAxis primaryAxis; if (polygonAxis.type == b2EPAxis::e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } b2ClipVertex ie[2]; b2ReferenceFace rf; if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->type = b2Manifold::e_faceA; // Search for the polygon normal that is most anti-parallel to the edge normal. int32 bestIndex = 0; float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); for (int32 i = 1; i < m_polygonB.count; ++i) { float32 value = b2Dot(m_normal, m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int32 i1 = bestIndex; int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; ie[0].v = m_polygonB.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = b2ContactFeature::e_face; ie[0].id.cf.typeB = b2ContactFeature::e_vertex; ie[1].v = m_polygonB.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = b2ContactFeature::e_face; ie[1].id.cf.typeB = b2ContactFeature::e_vertex; if (m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = m_v1; rf.v2 = m_v2; rf.normal = m_normal1; } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = m_v2; rf.v2 = m_v1; rf.normal = -m_normal1; } } else { manifold->type = b2Manifold::e_faceB; ie[0].v = m_v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = b2ContactFeature::e_vertex; ie[0].id.cf.typeB = b2ContactFeature::e_face; ie[1].v = m_v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = b2ContactFeature::e_vertex; ie[1].id.cf.typeB = b2ContactFeature::e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; rf.v1 = m_polygonB.vertices[rf.i1]; rf.v2 = m_polygonB.vertices[rf.i2]; rf.normal = m_polygonB.normals[rf.i1]; } rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); rf.sideNormal2 = -rf.sideNormal1; rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. b2ClipVertex clipPoints1[2]; b2ClipVertex clipPoints2[2]; int32 np; // Clip to box side 1 np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < b2_maxManifoldPoints) { return; } // Clip to negative box side 1 np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < b2_maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type == b2EPAxis::e_edgeA) { manifold->localNormal = rf.normal; manifold->localPoint = rf.v1; } else { manifold->localNormal = polygonB->m_normals[rf.i1]; manifold->localPoint = polygonB->m_vertices[rf.i1]; } int32 pointCount = 0; for (int32 i = 0; i < b2_maxManifoldPoints; ++i) { float32 separation; separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); if (separation <= m_radius) { b2ManifoldPoint* cp = manifold->points + pointCount; if (primaryAxis.type == b2EPAxis::e_edgeA) { cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); cp->id = clipPoints2[i].id; } else { cp->localPoint = clipPoints2[i].v; cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold->pointCount = pointCount; } b2EPAxis b2EPCollider::ComputeEdgeSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_edgeA; axis.index = m_front ? 0 : 1; axis.separation = FLT_MAX; for (int32 i = 0; i < m_polygonB.count; ++i) { float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); if (s < axis.separation) { axis.separation = s; } } return axis; } b2EPAxis b2EPCollider::ComputePolygonSeparation() { b2EPAxis axis; axis.type = b2EPAxis::e_unknown; axis.index = -1; axis.separation = -FLT_MAX; b2Vec2 perp(-m_normal.y, m_normal.x); for (int32 i = 0; i < m_polygonB.count; ++i) { b2Vec2 n = -m_polygonB.normals[i]; float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); float32 s = b2Min(s1, s2); if (s > m_radius) { // No collision axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; return axis; } // Adjacency if (b2Dot(n, perp) >= 0.0f) { if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) { continue; } } else { if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) { continue; } } if (s > axis.separation) { axis.type = b2EPAxis::e_edgeB; axis.index = i; axis.separation = s; } } return axis; } void b2CollideEdgeAndPolygon( b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, const b2PolygonShape* polygonB, const b2Transform& xfB) { b2EPCollider collider; collider.Collide(manifold, edgeA, xfA, polygonB, xfB); }
412
0.988231
1
0.988231
game-dev
MEDIA
0.516735
game-dev,graphics-rendering
0.996258
1
0.996258
Gibberlings3/SwordCoastStratagems
10,632
stratagems/iwdspells/lib/iwd_divine_spells_postproduction.tpa
DEFINE_ACTION_FUNCTION iwd_divine_spells_postproduction BEGIN LAF array_read STR_VAR file=iwd_spells_installed.txt path="%data_loc%" RET_ARRAY IWD_spell_installed=array END LAM data_spells_by_level // needed for scroll LAF make_physical_mirror_level_5 END LAM data_spell_resrefs // load in new physical mirror as well as new IWD spells ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_ENTROPY_SHIELD") BEGIN LAF entropy_shield_flame_strike END END LAF monster_summoning_divine_cosmetic END LAF no_chant_spell_failure END LAF patch_cures_into_stores END ACTION_IF !MOD_IS_INSTALLED "spell_rev/setup-spell_rev.tp2" 0 BEGIN LAF bg2ify_cure_moderate_wounds END LAF hide_old_cause_wounds END END LAF cre_set_joinable_priest_spells END LAF clearair_divine END LAF surplus_cleric_protections END LAF run STR_VAR file=summoned_monsters_divine location=lib END LAF run STR_VAR file=dealign_cleric_spells version=1 location=lib END INCLUDE "%MOD_FOLDER%/%component_loc%/lib/cd_divine_post.tpa" // just in case Cam's code isn't SFO-sugar-compliant LAF cd_divine_post END ACTION_IF !enhanced_edition BEGIN OUTER_SPRINT obg2_res_path "%MOD_FOLDER%/%component_loc%/obg2_res" INCLUDE "%MOD_FOLDER%/%component_loc%/lib/obg2_divine.tpa" LAF obg2_divine END END ACTION_IF MOD_IS_INSTALLED "spell_rev/setup-spell_rev.tp2" 55 BEGIN LAF run STR_VAR file=sr_nwn_spelldeflection location=lib version=sr_nwn_arcane END END END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION surplus_cleric_protections BEGIN // these protect against spells that aren't moved over, and whose namespace might be occupied; we need to clear the cruft out ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_CLOUDBURST") BEGIN // Cloudburst protects against salamander auras COPY_EXISTING "%CLERIC_CLOUDBURST%.spl" override LPF DELETE_EFFECT STR_VAR match_function="READ_ASCII 0x14 resref;; PATCH_MATCH ~%resref%~ WITH SPIN193 SPIN194 SPIN187 SPIN128 BEGIN value=1 END DEFAULT value=0 END" END BUT_ONLY END ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_ENTROPY_SHIELD") BEGIN //entropy shield protects against MM trap COPY_EXISTING "%CLERIC_ENTROPY_SHIELD%.spl" override LPF DELETE_EFFECT STR_VAR match_resource="SPWI033" END BUT_ONLY END ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_RIGHTEOUS_WRATH_OF_THE_FAITHFUL") BEGIN //same-alignment version of RWotF cancels haste, but not Mazzy's version; also in bgee, no need to gate this with a game check COPY_EXISTING "%CLERIC_RIGHTEOUS_WRATH_OF_THE_FAITHFUL%a.spl" override LPF CLONE_EFFECT STR_VAR match_resource="SPWI305" resource="spin828" END // should dupe both the 321 and 206 BUT_ONLY END END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION no_chant_spell_failure BEGIN ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_CHANT") BEGIN // remove spell-failure effect from CHANT COPY_EXISTING "%CLERIC_CHANT%.spl" override LPF DELETE_EFFECT INT_VAR match_opcode=145 END SAY 0x50 @101 BUT_ONLY END END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION patch_cures_into_stores BEGIN ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_CURE_MODERATE_WOUNDS") BEGIN // patch Cure Moderate Wounds into temples // (while we're at it, do Cure Medium Wounds, which gets left out quite often) // get the data LAF array_read STR_VAR file=strref_map.txt path="%data_loc%" RET_ARRAY strref_map=array END OUTER_SET desc=$strref_map(19397) APPEND ~speldesc.2da~ ~%CLERIC_CURE_MODERATE_WOUNDS%%TAB%%desc%~ ACTION_CLEAR_ARRAY has_light ACTION_CLEAR_ARRAY no_medium COPY_EXISTING_REGEXP GLOB ".*\.sto" "%workspace%" PATCH_IF INDEX_BUFFER ("%CLERIC_CURE_LIGHT_WOUNDS%")>=0 BEGIN SPRINT $has_light("%SOURCE_RES%") "" PATCH_IF INDEX_BUFFER ("%CLERIC_CURE_MEDIUM_WOUNDS%")<0 BEGIN SPRINT $no_medium("%SOURCE_RES%") "" END END BUT_ONLY // do the patching ACTION_PHP_EACH no_medium AS sto=>discard BEGIN sto.edit["%sto%"] [ m.cure.clone{s_resref:=%CLERIC_CURE_MEDIUM_WOUNDS%;; s_price=3*s_price|match="~%s_resref%~==sppr103"} ] END ACTION_PHP_EACH has_light AS sto=>discard BEGIN sto.edit["%sto%"] [ m.cure.clone{s_resref:=%CLERIC_CURE_MODERATE_WOUNDS%;; s_price=2*s_price|match="~%s_resref%~==sppr103"} ] END END END ////////////////////////////////////////////////////////////////////////////////////////////////// // update CLEARAIR.2DA to include Cloud of Pestilence DEFINE_ACTION_FUNCTION clearair_divine BEGIN ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_CLOUD_OF_PESTILENCE") BEGIN COPY_EXISTING "%CLERIC_CLOUD_OF_PESTILENCE%.spl" "%override%" READ_LONG 0x64 ab_off READ_SHORT (0x26+ab_off) proj BUT_ONLY OUTER_SET proj -= 1 APPEND "clearair.2da" "cloud_of_pest %proj%" COPY_EXISTING "clearair.2da" override PRETTY_PRINT_2DA END END /////////////////////////////////////////////////////////////////////////////////////////////////// // make Physical Mirror 5th level DEFINE_ACTION_FUNCTION make_physical_mirror_level_5 BEGIN // we leave the old one in to aid mod compatibility LAF RES_NUM_OF_SPELL_NAME STR_VAR spell_name=CLERIC_PHYSICAL_MIRROR RET resref_old=spell_res END // disable original version from spell.ids and from the selection screen (no need to remove it from spellbooks since we redo them globally for IWD anyway) COPY_EXISTING spell.ids override REPLACE_TEXTUALLY CLERIC_PHYSICAL_MIRROR CLERIC_MIRROR_OLD // avoid 'CLERIC_PHYSICAL_MIRROR' because it's better not to have an ids entry that's a substring of another one BUT_ONLY ACTION_IF FILE_EXISTS_IN_GAME "hidespl.2da" BEGIN ACTION_IF enhanced_edition BEGIN APPEND "hidespl.2da" "%CLERIC_PHYSICAL_MIRROR% 1 0 0" END ELSE BEGIN APPEND "hidespl.2da" "%CLERIC_PHYSICAL_MIRROR% ****" END END ELSE BEGIN spl.edit[%resref_old%] [ m_unusable_druid=1 m_unusable_cleric=1 ] END // copy in new version CLEAR_IDS_MAP spl.copy["%resref_old%"=>CLERIC_PHYSICAL_MIRROR|standard_icons:i=0] [ m_level=5 m.ab.alter{s_casting_time=5} m.ab_fx.alter{s_power=5} INNER_PATCH_SAVE m_description "%m_description%" BEGIN REPLACE_TEXTUALLY 6 5 END ] END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION entropy_shield_flame_strike BEGIN ACTION_DEFINE_ASSOCIATIVE_ARRAY flame_strike_map BEGIN sppr503=>sppr503d sppr985=>sppr985d spin799=>spin799d ohbeflam=>"dw#ohbef" spimix01=>"dw#spimi" END ACTION_PHP_EACH flame_strike_map AS spell=>helper BEGIN LAF externalise_flame_strike_damage STR_VAR spell helper END END END DEFINE_ACTION_FUNCTION externalise_flame_strike_damage STR_VAR spell="" helper="" BEGIN ACTION_IF FILE_EXISTS_IN_GAME "%spell%.spl" BEGIN // make duplicate of spell that only does damage ACTION_IF !FILE_EXISTS_IN_GAME "%helper%.spl" BEGIN COPY_EXISTING "%spell%.spl" "override/%helper%.spl" LPF DELETE_EFFECT STR_VAR match_function="!(SHORT_AT 0x0=12)" END LPF ALTER_SPELL_HEADER INT_VAR projectile=0 speed=0 END WRITE_LONG 0x8 "-1" // replace damage effects in spell with casting of new spell COPY_EXISTING "%spell%.spl" override LPF ALTER_EFFECT INT_VAR match_opcode=12 dicenumber=0 dicesize=0 opcode=146 savingthrow=0 savebonus=0 parameter1=0 parameter2=1 STR_VAR resource="%helper%" END BUT_ONLY END // alter protection from Entropy Shield to protect against helper COPY_EXISTING "%CLERIC_ENTROPY_SHIELD%.spl" override REPLACE_TEXTUALLY "%spell%" "%helper%" (8) END END ///////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION monster_summoning_divine_cosmetic BEGIN ACTION_FOR_EACH 2da IN ginsect sshamb BEGIN ACTION_IF FILE_EXISTS_IN_GAME "%2da%.2da" BEGIN COPY_EXISTING "%2da%.2da" override REPLACE_TEXTUALLY "msumm1h.*" "spanisum none" BUT_ONLY END END END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION bg2ify_cure_moderate_wounds BEGIN ACTION_IF VARIABLE_IS_SET $IWD_spell_installed("CLERIC_CURE_MODERATE_WOUNDS") BEGIN COPY_EXISTING "%CLERIC_CURE_MODERATE_WOUNDS%.spl" "override" READ_LONG 0x8 name_new_strref READ_STRREF 0x8 name_new BUT_ONLY COPY_EXISTING "%CLERIC_CURE_MEDIUM_WOUNDS%.spl" "override/%CLERIC_CURE_MODERATE_WOUNDS%.spl" READ_STRREF 0x8 name_old WRITE_LONG 0x8 name_new_strref WRITE_LONG 0x34 2 READ_STRREF 0x50 desc INNER_PATCH_SAVE desc "%desc%" BEGIN REPLACE_TEXTUALLY 14 11 REPLACE_TEXTUALLY 3 2 REPLACE_TEXTUALLY "%name_old%" "%name_new%" END SAY_EVALUATED 0x50 "%desc%" WRITE_ASCIIE 0x3a "%CLERIC_CURE_MODERATE_WOUNDS%C" (8) WRITE_ASCIIE 0x76 "%CLERIC_CURE_MODERATE_WOUNDS%B" (8) LPF ALTER_EFFECT INT_VAR power=2 END LPF ALTER_EFFECT INT_VAR match_opcode=17 parameter1=11 END BUT_ONLY END END ////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_ACTION_FUNCTION hide_old_cause_wounds BEGIN // hide BG2 versions of Cause Serious/Critical Wounds (we leave them in just to avoid AI confusions in other mods) ACTION_IF FILE_EXISTS_IN_GAME "hidespl.2da" BEGIN ACTION_IF enhanced_edition BEGIN APPEND "hidespl.2da" "%CLERIC_CAUSE_SERIOUS_WOUNDS% 1 0 0" APPEND "hidespl.2da" "%CLERIC_CAUSE_CRITICAL_WOUNDS% 1 0 0" END ELSE BEGIN APPEND "hidespl.2da" "%CLERIC_CAUSE_SERIOUS_WOUNDS% ****" APPEND "hidespl.2da" "%CLERIC_CAUSE_CRITICAL_WOUNDS% ****" END END ELSE BEGIN spl.edit[%CLERIC_CAUSE_SERIOUS_WOUNDS% %CLERIC_CAUSE_CRITICAL_WOUNDS%] [ m_unusable_druid=1 m_unusable_cleric=1 ] END END //////////////////////////////////////////////////////////////////////////////////////////////////
412
0.774074
1
0.774074
game-dev
MEDIA
0.710527
game-dev
0.655634
1
0.655634
TartaricAcid/TouhouLittleMaid
9,111
src/main/java/com/github/tartaricacid/touhoulittlemaid/entity/passive/MaidNavigationManager.java
package com.github.tartaricacid.touhoulittlemaid.entity.passive; import com.github.tartaricacid.touhoulittlemaid.api.mixin.INavigationMixin; import com.github.tartaricacid.touhoulittlemaid.entity.ai.navigation.MaidPathNavigation; import com.github.tartaricacid.touhoulittlemaid.entity.ai.navigation.MaidUnderWaterPathNavigation; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.ai.memory.MemoryModuleType; import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; import net.minecraft.world.entity.ai.navigation.PathNavigation; import net.minecraft.world.level.Level; import net.minecraft.world.level.pathfinder.Path; import net.minecraft.world.level.pathfinder.PathComputationType; import org.jetbrains.annotations.Nullable; public class MaidNavigationManager { private final MaidPathNavigation basicNavigation; private final AmphibiousPathNavigation waterNavigation; private final EntityMaid maid; private final Level level; private Mode mode = Mode.GROUND; public MaidNavigationManager(EntityMaid maid) { this.maid = maid; this.level = maid.level; this.basicNavigation = new MaidPathNavigation(maid, maid.level); this.waterNavigation = new MaidUnderWaterPathNavigation(maid, maid.level); maid.setNavigation(basicNavigation); } public void tick() { if (!level.isClientSide && maid.isEffectiveAi()) { if (mode != Mode.WATER && maid.isInWater() && shouldStartOrStopSwim(5)) { // 对于一般寻路,当满足:女仆接触到水,前方有长水面时,切换到水中寻路 if (switchToNavigation(Mode.WATER, waterNavigation)) { maid.getSwimManager().setWantToSwim(true); maid.getSwimManager().setReadyToLand(false); } } else if (mode != Mode.WATER && maid.isUnderWater() && mayBeStuckUnderWater(maid.blockPosition())) { // 如果女仆发现其所在位置不能上浮,那么也应该进入游泳状态(顶着头呆呆的) if (switchToNavigation(Mode.WATER, waterNavigation)) { maid.getSwimManager().setWantToSwim(true); maid.getSwimManager().setReadyToLand(false); } } else if (mode != Mode.WATER && maid.isInWater() && targetingUnderWater()) { // 如果目标在水下,那么女仆显然也应该进行水下寻路 if (switchToNavigation(Mode.WATER, waterNavigation)) { maid.getSwimManager().setWantToSwim(true); maid.getSwimManager().setReadyToLand(false); } } else if (mode == Mode.WATER) { // 女仆当前正在使用水下寻路(不保证游泳的状态) // 如果满足使用水下寻路的附加条件,则不进行下面的判断(目标水下或者无法上浮),防止状态之间的闪烁 boolean shouldUseWater = (maid.isInWater() && targetingUnderWater()) || (maid.isUnderWater() && mayBeStuckUnderWater(maid.blockPosition())); // 要判断出水,需要当前存在路径 BlockPos endPos = getEndPos(waterNavigation); if (!shouldUseWater && endPos != null) { if (!shouldStartOrStopSwim(2)) { // 即将走到水中寻路的尽头,你的女仆是否还需要游泳呢? if (!level.isWaterAt(endPos) && !level.isWaterAt(endPos.below())) { // a:如果最终女仆是要上岸的,那么这时就没必要继续游泳了。立刻停止并切换到常规模式 if (switchToNavigation(Mode.GROUND, basicNavigation)) { maid.getSwimManager().setReadyToLand(true); maid.getSwimManager().setWantToSwim(false); } } else if (isWaterSurface(endPos)) { // b:女仆最终来到了水面上 maid.getSwimManager().setWantToSwim(false); maid.getSwimManager().setReadyToLand(false); } else { // c:仅仅是走到头了( maid.getSwimManager().setWantToSwim(true); maid.getSwimManager().setReadyToLand(false); } } else if (!maid.isInWater()) { // b:女仆上岸了,立刻切换到常规寻路 if (switchToNavigation(Mode.GROUND, basicNavigation)) { maid.getSwimManager().setWantToSwim(false); maid.getSwimManager().setReadyToLand(false); } } else if (!maid.isUnderWater()) { // 女仆半身入水(那貌似游泳就不大礼貌了) maid.getSwimManager().setWantToSwim(false); } else { maid.getSwimManager().setWantToSwim(true); maid.getSwimManager().setSwimTarget(endPos); } } else if (endPos == null && maid.getSwimManager().isGoingToBreath()) { // 有一种走完路径的特殊情况:女仆是想要去呼吸的。此时依然走的是水中寻路,但是应该取消游泳状态 maid.getSwimManager().setWantToSwim(false); } else if (shouldUseWater) { // 当前满足游泳的条件(见上) maid.getSwimManager().setWantToSwim(true); // 没有走完路径,更新终点 if (endPos != null) { maid.getSwimManager().setSwimTarget(endPos); } } } } // 其他情况,如女仆进行一次传送,可能导致寻路中断,因此需要重新设置女仆是否要游泳 if (mode != Mode.WATER) { maid.getSwimManager().setWantToSwim(false); } } private boolean targetingUnderWater() { // 判断 Target 是否在水下 if (!maid.getBrain().hasMemoryValue(MemoryModuleType.WALK_TARGET)) { return false; } return isUnderWater(maid .getBrain() .getMemory(MemoryModuleType.WALK_TARGET) .get() .getTarget() .currentBlockPosition() ); } @SuppressWarnings("all") private boolean switchToNavigation(Mode mode, PathNavigation navigation) { PathNavigation currentNavigation = maid.getNavigation(); if (!currentNavigation.isDone()) { Path path = navigation.createPath(currentNavigation.getPath().getEndNode().asBlockPos(), 0); if (path != null && path.canReach()) { if (navigation.moveTo(path, ((INavigationMixin) currentNavigation).touhouLittleMaid$GetSpeedModifier())) { // 删除第一个寻路节点,有助于路径切换更加平滑(第一个巡路点的 center 可能会出现在身后) path.advance(); maid.setNavigation(navigation); this.mode = mode; currentNavigation.stop(); return true; } } } else { maid.setNavigation(navigation); navigation.stop(); currentNavigation.stop(); return true; } return false; } private boolean shouldStartOrStopSwim(int minimumDistance) { Path path = maid.getNavigation().getPath(); if (path == null || path.isDone() || path.getNextNodeIndex() > path.getNodeCount() - minimumDistance) { return false; } for (int i = path.getNextNodeIndex(), c = 0; c < minimumDistance; c++, i++) { if (!level.isWaterAt(path.getNode(i).asBlockPos())) { return false; } } return true; } /** * 判断女仆是否可能被卡在水下(头顶方块) * 即判断在水中的女仆头顶有没有方块 */ private boolean mayBeStuckUnderWater(BlockPos pos) { return level.isWaterAt(pos) && !level.getBlockState(pos.above()).isPathfindable(level, pos, PathComputationType.LAND); } public PathNavigation getBasicNavigation() { return basicNavigation; } public PathNavigation getWaterNavigation() { return waterNavigation; } public boolean isWaterSurface(BlockPos pos) { // 向上两层(主人浮在水上的话 target 可能是 -1Y 的),向上一层(寻路规则) return (level.isWaterAt(pos) && level.getBlockState(pos.above()).isAir()) || (level.isWaterAt(pos.below()) && level.getBlockState(pos).isAir()) || (level.isWaterAt(pos.above()) && level.getBlockState(pos.above(2)).isAir()); } /** * 判断目标位置是否两格或更深 */ private boolean isUnderWater(BlockPos blockPos) { return level.isWaterAt(blockPos) && level.isWaterAt(blockPos.above()) && level.isWaterAt(blockPos.above(2)); } @Nullable public BlockPos getEndPos(PathNavigation navigation) { if (navigation.getPath() == null) { return null; } if (navigation.getPath().getEndNode() == null) { return null; } return navigation.getPath().getEndNode().asBlockPos(); } public void resetNavigation() { maid.setNavigation(basicNavigation); basicNavigation.stop(); waterNavigation.stop(); maid.getSwimManager().setWantToSwim(false); maid.getSwimManager().setReadyToLand(false); mode = Mode.GROUND; } public enum Mode { GROUND, WATER } }
412
0.792107
1
0.792107
game-dev
MEDIA
0.640463
game-dev
0.956166
1
0.956166
mjx-project/mjx
2,257
tests_cpp/internal_game_result_summarizer_test.cpp
#include <mjx/internal/game_result_summarizer.h> #include "gtest/gtest.h" using namespace mjx::internal; TEST(internal_game_result_summarizer, Add) { GameResultSummarizer& summarizer = GameResultSummarizer::instance(); summarizer.Initialize(); EXPECT_EQ(summarizer.num_games(), 0); summarizer.Add(GameResult{0, {{"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}}}); EXPECT_EQ(summarizer.num_games(), 1); // thread-safe test summarizer.Initialize(); std::thread th1([&] { for (int i = 0; i < 1000; i++) { summarizer.Add(GameResult{0, {{"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}}}); summarizer.Add(GameResult{0, {{"A", 2}, {"B", 3}, {"C", 4}, {"D", 1}}}); summarizer.Add(GameResult{0, {{"A", 3}, {"B", 4}, {"C", 1}, {"D", 2}}}); summarizer.Add(GameResult{0, {{"A", 4}, {"B", 1}, {"C", 2}, {"D", 3}}}); } }); std::thread th2([&] { for (int i = 0; i < 1000; i++) { summarizer.Add(GameResult{0, {{"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}}}); summarizer.Add(GameResult{0, {{"A", 2}, {"B", 3}, {"C", 4}, {"D", 1}}}); summarizer.Add(GameResult{0, {{"A", 3}, {"B", 4}, {"C", 1}, {"D", 2}}}); summarizer.Add(GameResult{0, {{"A", 4}, {"B", 1}, {"C", 2}, {"D", 3}}}); } }); th1.join(); th2.join(); EXPECT_EQ(summarizer.num_games(), 8000); for (const auto& player_id : {"A", "B", "C", "D"}) { EXPECT_EQ(summarizer.player_performance(player_id).avg_ranking, 2.5); EXPECT_EQ(summarizer.player_performance(player_id).stable_dan, 5.0); } } TEST(internal_game_result_summarizer, player_performance) { // avg ranking, stable dan GameResultSummarizer& summarizer = GameResultSummarizer::instance(); summarizer.Initialize(); summarizer.Add(GameResult{0, {{"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}}}); summarizer.Add(GameResult{0, {{"A", 2}, {"B", 3}, {"C", 4}, {"D", 1}}}); summarizer.Add(GameResult{0, {{"A", 3}, {"B", 4}, {"C", 1}, {"D", 2}}}); summarizer.Add(GameResult{0, {{"A", 4}, {"B", 1}, {"C", 2}, {"D", 3}}}); for (const auto& player_id : {"A", "B", "C", "D"}) { EXPECT_EQ(summarizer.player_performance(player_id).avg_ranking, 2.5); EXPECT_EQ(summarizer.player_performance(player_id).stable_dan, 5.0); } std::cout << summarizer.string() << std::endl; }
412
0.735028
1
0.735028
game-dev
MEDIA
0.718194
game-dev
0.745285
1
0.745285
fulpstation/fulpstation
35,557
code/game/objects/items/devices/flashlight.dm
#define FAILURE 0 #define SUCCESS 1 #define NO_FUEL 2 #define ALREADY_LIT 3 /obj/item/flashlight name = "flashlight" desc = "A hand-held emergency light." custom_price = PAYCHECK_CREW icon = 'icons/obj/lighting.dmi' dir = WEST icon_state = "flashlight" inhand_icon_state = "flashlight" worn_icon_state = "flashlight" lefthand_file = 'icons/mob/inhands/items/devices_lefthand.dmi' righthand_file = 'icons/mob/inhands/items/devices_righthand.dmi' w_class = WEIGHT_CLASS_SMALL obj_flags = CONDUCTS_ELECTRICITY slot_flags = ITEM_SLOT_BELT custom_materials = list(/datum/material/iron= SMALL_MATERIAL_AMOUNT * 0.5, /datum/material/glass= SMALL_MATERIAL_AMOUNT * 0.2) actions_types = list(/datum/action/item_action/toggle_light) action_slots = ALL light_system = OVERLAY_LIGHT_DIRECTIONAL light_color = COLOR_LIGHT_ORANGE light_range = 4 light_power = 1 light_on = FALSE /// If we've been forcibly disabled for a temporary amount of time. COOLDOWN_DECLARE(disabled_time) /// Can we toggle this light on and off (used for contexual screentips only) var/toggle_context = TRUE /// The sound the light makes when it's turned on var/sound_on = 'sound/items/weapons/magin.ogg' /// The sound the light makes when it's turned off var/sound_off = 'sound/items/weapons/magout.ogg' /// Should the flashlight start turned on? var/start_on = FALSE /// When true, painting the flashlight won't change its light color var/ignore_base_color = FALSE /obj/item/flashlight/Initialize(mapload) . = ..() if(start_on) set_light_on(TRUE) update_brightness() register_context() var/static/list/slapcraft_recipe_list = list(/datum/crafting_recipe/flashlight_eyes) AddElement( /datum/element/slapcrafting,\ slapcraft_recipes = slapcraft_recipe_list,\ ) /obj/item/flashlight/add_context(atom/source, list/context, obj/item/held_item, mob/living/user) // single use lights can be toggled on once if(isnull(held_item) && (toggle_context || !light_on)) context[SCREENTIP_CONTEXT_RMB] = "Toggle light" return CONTEXTUAL_SCREENTIP_SET if(istype(held_item, /obj/item/flashlight) && (toggle_context || !light_on)) context[SCREENTIP_CONTEXT_LMB] = "Toggle light" return CONTEXTUAL_SCREENTIP_SET return NONE /obj/item/flashlight/update_icon_state() . = ..() if(light_on) icon_state = "[initial(icon_state)]-on" if(!isnull(inhand_icon_state)) inhand_icon_state = "[initial(inhand_icon_state)]-on" else icon_state = initial(icon_state) if(!isnull(inhand_icon_state)) inhand_icon_state = initial(inhand_icon_state) /obj/item/flashlight/proc/update_brightness() update_appearance(UPDATE_ICON) if(light_system == COMPLEX_LIGHT) update_light() /obj/item/flashlight/proc/toggle_light(mob/user) playsound(src, light_on ? sound_off : sound_on, 40, TRUE) if(!COOLDOWN_FINISHED(src, disabled_time)) if(user) balloon_alert(user, "disrupted!") set_light_on(FALSE) update_brightness() update_item_action_buttons() return FALSE var/old_light_on = light_on set_light_on(!light_on) update_brightness() update_item_action_buttons() return light_on != old_light_on // If the value of light_on didn't change, return false. Otherwise true. /obj/item/flashlight/attack_self(mob/user) return toggle_light(user) /obj/item/flashlight/attack_hand_secondary(mob/user, list/modifiers) attack_self(user) return SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN /obj/item/flashlight/suicide_act(mob/living/carbon/human/user) if (user.is_blind()) user.visible_message(span_suicide("[user] is putting [src] close to [user.p_their()] eyes and turning it on... but [user.p_theyre()] blind!")) return SHAME user.visible_message(span_suicide("[user] is putting [src] close to [user.p_their()] eyes and turning it on! It looks like [user.p_theyre()] trying to commit suicide!")) return FIRELOSS /obj/item/flashlight/proc/eye_examine(mob/living/carbon/human/M, mob/living/user) . = list() if((M.head && M.head.flags_cover & HEADCOVERSEYES) || (M.wear_mask && M.wear_mask.flags_cover & MASKCOVERSEYES) || (M.glasses && M.glasses.flags_cover & GLASSESCOVERSEYES)) to_chat(user, span_warning("You're going to need to remove that [(M.head && M.head.flags_cover & HEADCOVERSEYES) ? "helmet" : (M.wear_mask && M.wear_mask.flags_cover & MASKCOVERSEYES) ? "mask": "glasses"] first!")) return var/obj/item/organ/eyes/E = M.get_organ_slot(ORGAN_SLOT_EYES) var/obj/item/organ/brain = M.get_organ_slot(ORGAN_SLOT_BRAIN) if(!E) to_chat(user, span_warning("[M] doesn't have any eyes!")) return M.flash_act(visual = TRUE, length = (user.combat_mode) ? 2.5 SECONDS : 1 SECONDS) // Apply a 1 second flash effect to the target. The duration increases to 2.5 Seconds if you have combat mode on. if(M == user) //they're using it on themselves user.visible_message(span_warning("[user] shines [src] into [M.p_their()] eyes."), ignored_mobs = user) . += span_info("You direct [src] to into your eyes:\n") if(M.is_blind()) . += "<span class='notice ml-1'>You're not entirely certain what you were expecting...</span>\n" else . += "<span class='notice ml-1'>Trippy!</span>\n" else user.visible_message(span_warning("[user] directs [src] to [M]'s eyes."), ignored_mobs = user) . += span_info("You direct [src] to [M]'s eyes:\n") if(M.stat == DEAD || M.is_blind() || M.get_eye_protection() > FLASH_PROTECTION_WELDER) . += "<span class='danger ml-1'>[M.p_Their()] pupils don't react to the light!</span>\n"//mob is dead else if(brain.damage > 20) . += "<span class='danger ml-1'>[M.p_Their()] pupils contract unevenly!</span>\n"//mob has sustained damage to their brain else . += "<span class='notice ml-1'>[M.p_Their()] pupils narrow.</span>\n"//they're okay :D if(M.dna && M.dna.check_mutation(/datum/mutation/human/xray)) . += "<span class='danger ml-1'>[M.p_Their()] pupils give an eerie glow!</span>\n"//mob has X-ray vision return . /obj/item/flashlight/proc/mouth_examine(mob/living/carbon/human/M, mob/living/user) . = list() if(M.is_mouth_covered()) to_chat(user, span_warning("You're going to need to remove that [(M.head && M.head.flags_cover & HEADCOVERSMOUTH) ? "helmet" : "mask"] first!")) return var/list/mouth_organs = list() for(var/obj/item/organ/organ as anything in M.organs) if(organ.zone == BODY_ZONE_PRECISE_MOUTH) mouth_organs.Add(organ) var/organ_list = "" var/organ_count = LAZYLEN(mouth_organs) if(organ_count) for(var/I in 1 to organ_count) if(I > 1) if(I == mouth_organs.len) organ_list += ", and " else organ_list += ", " var/obj/item/organ/O = mouth_organs[I] organ_list += (O.gender == "plural" ? O.name : "\an [O.name]") var/pill_count = 0 for(var/datum/action/item_action/activate_pill/AP in M.actions) pill_count++ if(M == user)//if we're looking on our own mouth var/can_use_mirror = FALSE if(isturf(user.loc)) var/obj/structure/mirror/mirror = locate(/obj/structure/mirror, user.loc) if(mirror) switch(user.dir) if(NORTH) can_use_mirror = mirror.pixel_y > 0 if(SOUTH) can_use_mirror = mirror.pixel_y < 0 if(EAST) can_use_mirror = mirror.pixel_x > 0 if(WEST) can_use_mirror = mirror.pixel_x < 0 M.visible_message(span_notice("[M] directs [src] to [ M.p_their()] mouth."), ignored_mobs = user) . += span_info("You point [src] into your mouth:\n") if(!can_use_mirror) to_chat(user, span_notice("You can't see anything without a mirror.")) return if(organ_count) . += "<span class='notice ml-1'>Inside your mouth [organ_count > 1 ? "are" : "is"] [organ_list].</span>\n" else . += "<span class='notice ml-1'>There's nothing inside your mouth.</span>\n" if(pill_count) . += "<span class='notice ml-1'>You have [pill_count] implanted pill[pill_count > 1 ? "s" : ""].</span>\n" else //if we're looking in someone elses mouth user.visible_message(span_notice("[user] directs [src] to [M]'s mouth."), ignored_mobs = user) . += span_info("You point [src] into [M]'s mouth:\n") if(organ_count) . += "<span class='notice ml-1'>Inside [ M.p_their()] mouth [organ_count > 1 ? "are" : "is"] [organ_list].</span>\n" else . += "<span class='notice ml-1'>[M] doesn't have any organs in [ M.p_their()] mouth.</span>\n" if(pill_count) . += "<span class='notice ml-1'>[M] has [pill_count] pill[pill_count > 1 ? "s" : ""] implanted in [ M.p_their()] teeth.</span>\n" //assess any suffocation damage var/hypoxia_status = M.getOxyLoss() > 20 if(M == user) if(hypoxia_status) . += "<span class='danger ml-1'>Your lips appear blue!</span>\n"//you have suffocation damage else . += "<span class='notice ml-1'>Your lips appear healthy.</span>\n"//you're okay! else if(hypoxia_status) . += "<span class='danger ml-1'>[M.p_Their()] lips appear blue!</span>\n"//they have suffocation damage else . += "<span class='notice ml-1'>[M.p_Their()] lips appear healthy.</span>\n"//they're okay! //assess blood level if(M == user) . += span_info("You press a finger to your gums:\n") else . += span_info("You press a finger to [M.p_their()] gums:\n") if(M.blood_volume <= BLOOD_VOLUME_SAFE && M.blood_volume > BLOOD_VOLUME_OKAY) . += "<span class='danger ml-1'>Color returns slowly!</span>\n"//low blood else if(M.blood_volume <= BLOOD_VOLUME_OKAY) . += "<span class='danger ml-1'>Color does not return!</span>\n"//critical blood else . += "<span class='notice ml-1'>Color returns quickly.</span>\n"//they're okay :D /obj/item/flashlight/interact_with_atom(atom/interacting_with, mob/living/user, list/modifiers) if(!ishuman(interacting_with)) return NONE if(!light_on) return NONE add_fingerprint(user) if(user.combat_mode || (user.zone_selected != BODY_ZONE_PRECISE_EYES && user.zone_selected != BODY_ZONE_PRECISE_MOUTH)) return NONE if((HAS_TRAIT(user, TRAIT_CLUMSY) || HAS_TRAIT(user, TRAIT_DUMB)) && prob(50)) //too dumb to use flashlight properly return ITEM_INTERACT_SKIP_TO_ATTACK //just hit them in the head . = ITEM_INTERACT_BLOCKING if(!ISADVANCEDTOOLUSER(user)) to_chat(user, span_warning("You don't have the dexterity to do this!")) return var/mob/living/scanning = interacting_with if(!scanning.get_bodypart(BODY_ZONE_HEAD)) to_chat(user, span_warning("[scanning] doesn't have a head!")) return if(light_power < 0.5) to_chat(user, span_warning("[src] isn't bright enough to see anything!")) return var/list/render_list = list() switch(user.zone_selected) if(BODY_ZONE_PRECISE_EYES) render_list += eye_examine(scanning, user) if(BODY_ZONE_PRECISE_MOUTH) render_list += mouth_examine(scanning, user) if(length(render_list)) //display our packaged information in an examine block for easy reading to_chat(user, boxed_message(jointext(render_list, "")), type = MESSAGE_TYPE_INFO) return ITEM_INTERACT_SUCCESS return ITEM_INTERACT_BLOCKING /// for directional sprites - so we get the same sprite in the inventory each time we pick one up /obj/item/flashlight/equipped(mob/user, slot, initial) . = ..() setDir(initial(dir)) SEND_SIGNAL(user, COMSIG_ATOM_DIR_CHANGE, user.dir, user.dir) // This is dumb, but if we don't do this then the lighting overlay may be facing the wrong direction depending on how it is picked up /// for directional sprites - so when we drop the flashlight, it drops facing the same way the user is facing /obj/item/flashlight/dropped(mob/user, silent = FALSE) . = ..() if(istype(user) && dir != user.dir) setDir(user.dir) /// when hit by a light disruptor - turns the light off, forces the light to be disabled for a few seconds /obj/item/flashlight/on_saboteur(datum/source, disrupt_duration) . = ..() if(light_on) toggle_light() COOLDOWN_START(src, disabled_time, disrupt_duration) return TRUE /obj/item/flashlight/update_atom_colour() . = ..() if (ignore_base_color) return var/list/applied_matrix = cached_color_filter if (!applied_matrix) applied_matrix = color_transition_filter(color, SATURATION_OVERRIDE) var/new_light_color = apply_matrix_to_color(initial(light_color), applied_matrix["color"], applied_matrix["space"] || COLORSPACE_RGB) set_light_color(new_light_color) /obj/item/flashlight/pen name = "penlight" desc = "A pen-sized light, used by medical staff. It can also be used to create a hologram to alert people of incoming medical assistance." dir = EAST icon_state = "penlight" inhand_icon_state = "" worn_icon_state = "pen" w_class = WEIGHT_CLASS_TINY obj_flags = CONDUCTS_ELECTRICITY light_range = 2 light_power = 0.8 light_color = "#CCFFFF" COOLDOWN_DECLARE(holosign_cooldown) /obj/item/flashlight/pen/ranged_interact_with_atom(atom/interacting_with, mob/living/user, list/modifiers) if(!COOLDOWN_FINISHED(src, holosign_cooldown)) balloon_alert(user, "not ready!") return ITEM_INTERACT_BLOCKING var/turf/target_turf = get_turf(interacting_with) var/mob/living/living_target = locate(/mob/living) in target_turf if(!living_target || (living_target == user)) return ITEM_INTERACT_BLOCKING to_chat(living_target, span_boldnotice("[user] is offering medical assistance; please halt your actions.")) new /obj/effect/temp_visual/medical_holosign(target_turf, user) //produce a holographic glow COOLDOWN_START(src, holosign_cooldown, 10 SECONDS) return ITEM_INTERACT_SUCCESS // see: [/datum/wound/burn/flesh/proc/uv()] /obj/item/flashlight/pen/paramedic name = "paramedic penlight" desc = "A high-powered UV penlight intended to help stave off infection in the field on serious burned patients. Probably really bad to look into." icon_state = "penlight_surgical" light_color = LIGHT_COLOR_PURPLE /// Our current UV cooldown COOLDOWN_DECLARE(uv_cooldown) /// How long between UV fryings var/uv_cooldown_length = 30 SECONDS /// How much sanitization to apply to the burn wound var/uv_power = 1 /obj/effect/temp_visual/medical_holosign name = "medical holosign" desc = "A small holographic glow that indicates a medic is coming to treat a patient." icon_state = "medi_holo" duration = 30 /obj/effect/temp_visual/medical_holosign/Initialize(mapload, creator) . = ..() playsound(loc, 'sound/machines/ping.ogg', 50, FALSE) //make some noise! if(creator) visible_message(span_danger("[creator] created a medical hologram!")) /obj/item/flashlight/seclite name = "seclite" desc = "A robust flashlight used by security." dir = EAST icon_state = "seclite" inhand_icon_state = "seclite" worn_icon_state = "seclite" lefthand_file = 'icons/mob/inhands/equipment/security_lefthand.dmi' righthand_file = 'icons/mob/inhands/equipment/security_righthand.dmi' force = 9 // Not as good as a stun baton. light_range = 5 // A little better than the standard flashlight. light_power = 0.8 light_color = "#99ccff" hitsound = 'sound/items/weapons/genhit1.ogg' // the desk lamps are a bit special /obj/item/flashlight/lamp name = "desk lamp" desc = "A desk lamp with an adjustable mount." icon_state = "lamp" inhand_icon_state = "lamp" lefthand_file = 'icons/mob/inhands/items_lefthand.dmi' righthand_file = 'icons/mob/inhands/items_righthand.dmi' force = 10 light_range = 3.5 light_system = COMPLEX_LIGHT light_color = LIGHT_COLOR_FAINT_BLUE w_class = WEIGHT_CLASS_BULKY obj_flags = CONDUCTS_ELECTRICITY custom_materials = null start_on = TRUE // green-shaded desk lamp /obj/item/flashlight/lamp/green desc = "A classic green-shaded desk lamp." icon_state = "lampgreen" inhand_icon_state = "lampgreen" light_color = LIGHT_COLOR_TUNGSTEN //Bananalamp /obj/item/flashlight/lamp/bananalamp name = "banana lamp" desc = "Only a clown would think to make a ghetto banana-shaped lamp. Even has a goofy pullstring." icon_state = "bananalamp" inhand_icon_state = null light_color = LIGHT_COLOR_BRIGHT_YELLOW // FLARES /obj/item/flashlight/flare name = "flare" desc = "A red Nanotrasen issued flare. There are instructions on the side, it reads 'pull cord, make light'." light_range = 7 // Pretty bright. icon_state = "flare" inhand_icon_state = "flare" worn_icon_state = "flare" actions_types = list() heat = 1000 light_color = LIGHT_COLOR_FLARE light_system = OVERLAY_LIGHT light_power = 2 grind_results = list(/datum/reagent/sulfur = 15) sound_on = 'sound/items/match_strike.ogg' toggle_context = FALSE /// How many seconds of fuel we have left var/fuel = 0 /// Do we randomize the fuel when initialized var/randomize_fuel = TRUE /// How much damage it does when turned on var/on_damage = 7 /// Type of atom thats spawns after fuel is used up var/trash_type = /obj/item/trash/flare /// If the light source can be extinguished var/can_be_extinguished = FALSE custom_materials = list(/datum/material/plastic= SMALL_MATERIAL_AMOUNT * 0.5) /obj/item/flashlight/flare/Initialize(mapload) . = ..() if(randomize_fuel) fuel = rand(10 MINUTES, 15 MINUTES) if(light_on) attack_verb_continuous = string_list(list("burns", "singes")) attack_verb_simple = string_list(list("burn", "singe")) hitsound = 'sound/items/tools/welder.ogg' force = on_damage damtype = BURN update_brightness() /obj/item/flashlight/flare/Destroy() STOP_PROCESSING(SSobj, src) return ..() /obj/item/flashlight/flare/attack(mob/living/carbon/victim, mob/living/carbon/user) if(!isliving(victim)) return ..() if(light_on && victim.ignite_mob()) message_admins("[ADMIN_LOOKUPFLW(user)] set [key_name_admin(victim)] on fire with [src] at [AREACOORD(user)]") user.log_message("set [key_name(victim)] on fire with [src]", LOG_ATTACK) return ..() /obj/item/flashlight/flare/toggle_light() if(light_on || !fuel) return FALSE . = ..() name = "lit [initial(name)]" attack_verb_continuous = string_list(list("burns", "singes")) attack_verb_simple = string_list(list("burn", "singe")) hitsound = 'sound/items/tools/welder.ogg' force = on_damage damtype = BURN /obj/item/flashlight/flare/proc/turn_off() set_light_on(FALSE) name = initial(name) attack_verb_continuous = initial(attack_verb_continuous) attack_verb_simple = initial(attack_verb_simple) hitsound = initial(hitsound) force = initial(force) damtype = initial(damtype) update_brightness() /obj/item/flashlight/flare/extinguish() . = ..() if((fuel != INFINITY) && can_be_extinguished) turn_off() /obj/item/flashlight/flare/update_brightness() ..() inhand_icon_state = "[initial(inhand_icon_state)]" + (light_on ? "-on" : "") update_appearance() /obj/item/flashlight/flare/process(seconds_per_tick) open_flame(heat) fuel = max(fuel - seconds_per_tick * (1 SECONDS), 0) if(!fuel || !light_on) turn_off() STOP_PROCESSING(SSobj, src) if(!fuel && trash_type) new trash_type(loc) qdel(src) /obj/item/flashlight/flare/proc/ignition(mob/user) if(!fuel) if(user) balloon_alert(user, "out of fuel!") return NO_FUEL if(light_on) if(user) balloon_alert(user, "already lit!") return ALREADY_LIT if(!toggle_light()) return FAILURE if(fuel != INFINITY) START_PROCESSING(SSobj, src) return SUCCESS /obj/item/flashlight/flare/fire_act(exposed_temperature, exposed_volume) ignition() return ..() /obj/item/flashlight/flare/attack_self(mob/user) if(ignition(user) == SUCCESS) user.visible_message(span_notice("[user] lights \the [src]."), span_notice("You light \the [initial(src.name)]!")) /obj/item/flashlight/flare/get_temperature() return light_on * heat /obj/item/flashlight/flare/candle name = "red candle" desc = "In Greek myth, Prometheus stole fire from the Gods and gave it to \ humankind. The jewelry he kept for himself." icon = 'icons/obj/candle.dmi' icon_state = "candle1" inhand_icon_state = "candle" lefthand_file = 'icons/mob/inhands/items_lefthand.dmi' righthand_file = 'icons/mob/inhands/items_righthand.dmi' w_class = WEIGHT_CLASS_TINY heat = 1000 light_range = 2 light_power = 1.5 light_color = LIGHT_COLOR_FIRE fuel = 35 MINUTES randomize_fuel = FALSE trash_type = /obj/item/trash/candle can_be_extinguished = TRUE /// The current wax level, used for drawing the correct icon var/current_wax_level = 1 /// The previous wax level, remembered so we only have to make 3 update_appearance calls total as opposed to every tick var/last_wax_level = 1 /obj/item/flashlight/flare/candle/Initialize(mapload) . = ..() AddElement(/datum/element/update_icon_updates_onmob) /** * Just checks the wax level of the candle for displaying the correct sprite. * * This gets called in process() every tick. If the wax level has changed, then we call our update. */ /obj/item/flashlight/flare/candle/proc/check_wax_level() switch(fuel) if(25 MINUTES to INFINITY) current_wax_level = 1 if(15 MINUTES to 25 MINUTES) current_wax_level = 2 if(0 to 15 MINUTES) current_wax_level = 3 if(last_wax_level != current_wax_level) last_wax_level = current_wax_level update_appearance(UPDATE_ICON | UPDATE_NAME) /obj/item/flashlight/flare/candle/update_icon_state() . = ..() icon_state = "candle[current_wax_level][light_on ? "_lit" : ""]" inhand_icon_state = "candle[light_on ? "_lit" : ""]" /** * Try to ignite the candle. * * Candles are ignited a bit differently from flares, in that they must be manually lit from other fire sources. * This will perform all the necessary checks to ensure that can happen, and display a message if it worked. * * Arguments: * * obj/item/fire_starter - the item being used to ignite the candle. * * mob/user - the user to display a message to. * * quiet - suppresses the to_chat message. * * silent - suppresses the balloon alerts as well as the to_chat message. */ /obj/item/flashlight/flare/candle/proc/try_light_candle(obj/item/fire_starter, mob/user, quiet, silent) if(!istype(fire_starter)) return if(!istype(user)) return var/success_msg = fire_starter.ignition_effect(src, user) var/ignition_result if(success_msg) ignition_result = ignition() switch(ignition_result) if(SUCCESS) update_appearance(UPDATE_ICON | UPDATE_NAME) if(!quiet && !silent) user.visible_message(success_msg) return SUCCESS if(ALREADY_LIT) if(!silent) balloon_alert(user, "already lit!") return ALREADY_LIT if(NO_FUEL) if(!silent) balloon_alert(user, "out of fuel!") return NO_FUEL /// allows lighting an unlit candle from some fire source by left clicking the candle with the source /obj/item/flashlight/flare/candle/attackby(obj/item/attacking_item, mob/user, params) if(try_light_candle(attacking_item, user, silent = istype(attacking_item, src.type))) // so we don't double balloon alerts when a candle is used to light another candle return COMPONENT_CANCEL_ATTACK_CHAIN else return ..() // allows lighting an unlit candle from some fire source by left clicking the source with the candle /obj/item/flashlight/flare/candle/pre_attack(atom/target, mob/living/user, params) if(ismob(target)) return ..() if(try_light_candle(target, user, quiet = TRUE)) return COMPONENT_CANCEL_ATTACK_CHAIN return ..() /obj/item/flashlight/flare/candle/attack_self(mob/user) if(light_on && (fuel != INFINITY || !can_be_extinguished)) // can't extinguish eternal candles turn_off() user.visible_message(span_notice("[user] snuffs [src].")) /obj/item/flashlight/flare/candle/process(seconds_per_tick) . = ..() check_wax_level() /obj/item/flashlight/flare/candle/infinite name = "eternal candle" fuel = INFINITY randomize_fuel = FALSE can_be_extinguished = FALSE start_on = TRUE /obj/item/flashlight/flare/torch name = "torch" desc = "A torch fashioned from some leaves and a log." light_range = 4 light_power = 1.3 icon_state = "torch" inhand_icon_state = "torch" lefthand_file = 'icons/mob/inhands/items_lefthand.dmi' righthand_file = 'icons/mob/inhands/items_righthand.dmi' light_color = LIGHT_COLOR_ORANGE on_damage = 10 slot_flags = null trash_type = /obj/effect/decal/cleanable/ash can_be_extinguished = TRUE /obj/item/flashlight/lantern name = "lantern" icon_state = "lantern" inhand_icon_state = "lantern" lefthand_file = 'icons/mob/inhands/equipment/mining_lefthand.dmi' righthand_file = 'icons/mob/inhands/equipment/mining_righthand.dmi' desc = "A mining lantern." light_range = 5 // luminosity when on light_power = 1.5 light_color = "#ffcc66" light_system = OVERLAY_LIGHT /obj/item/flashlight/lantern/on start_on = TRUE /obj/item/flashlight/lantern/heirloom_moth name = "old lantern" desc = "An old lantern that has seen plenty of use." light_range = 3.5 /obj/item/flashlight/lantern/syndicate name = "suspicious lantern" desc = "A suspicious looking lantern." icon_state = "syndilantern" inhand_icon_state = "syndilantern" light_range = 6 light_power = 2 light_color = "#ffffe6" /obj/item/flashlight/lantern/jade name = "jade lantern" desc = "An ornate, green lantern." color = LIGHT_COLOR_GREEN /obj/item/flashlight/lantern/jade/on start_on = TRUE /obj/item/flashlight/slime gender = PLURAL name = "glowing slime extract" desc = "Extract from a yellow slime. It emits a strong light when squeezed." icon = 'icons/obj/lighting.dmi' icon_state = "slime" inhand_icon_state = null w_class = WEIGHT_CLASS_SMALL slot_flags = ITEM_SLOT_BELT custom_materials = null light_range = 6 //luminosity when on light_color = "#ffff66" light_system = OVERLAY_LIGHT /obj/item/flashlight/emp var/emp_max_charges = 4 var/emp_cur_charges = 4 var/charge_timer = 0 /// How many seconds between each recharge var/charge_delay = 20 /obj/item/flashlight/emp/Initialize(mapload) . = ..() START_PROCESSING(SSobj, src) /obj/item/flashlight/emp/Destroy() STOP_PROCESSING(SSobj, src) return ..() /obj/item/flashlight/emp/process(seconds_per_tick) charge_timer += seconds_per_tick if(charge_timer < charge_delay) return FALSE charge_timer -= charge_delay emp_cur_charges = min(emp_cur_charges+1, emp_max_charges) return TRUE /obj/item/flashlight/emp/attack(mob/living/M, mob/living/user) if(light_on && (user.zone_selected in list(BODY_ZONE_PRECISE_EYES, BODY_ZONE_PRECISE_MOUTH))) // call original attack when examining organs ..() return /obj/item/flashlight/emp/interact_with_atom(atom/interacting_with, mob/living/user, list/modifiers) . = ..() if(. & ITEM_INTERACT_ANY_BLOCKER) return if(emp_cur_charges > 0) emp_cur_charges -= 1 if(ismob(interacting_with)) var/mob/empd = interacting_with log_combat(user, empd, "attacked", "EMP-light") empd.visible_message(span_danger("[user] blinks \the [src] at \the [empd]."), \ span_userdanger("[user] blinks \the [src] at you.")) else interacting_with.visible_message(span_danger("[user] blinks \the [src] at \the [interacting_with].")) to_chat(user, span_notice("\The [src] now has [emp_cur_charges] charge\s.")) interacting_with.emp_act(EMP_HEAVY) else to_chat(user, span_warning("\The [src] needs time to recharge!")) return ITEM_INTERACT_SUCCESS /obj/item/flashlight/emp/debug //for testing emp_act() name = "debug EMP flashlight" emp_max_charges = 100 emp_cur_charges = 100 // Glowsticks, in the uncomfortable range of similar to flares, // Flares need to process (for hotspots) tho so this becomes irrelevant /obj/item/flashlight/glowstick name = "glowstick" desc = "A military-grade glowstick." custom_price = PAYCHECK_LOWER w_class = WEIGHT_CLASS_SMALL light_range = 3.5 light_power = 2 light_system = OVERLAY_LIGHT color = LIGHT_COLOR_GREEN icon_state = "glowstick" base_icon_state = "glowstick" inhand_icon_state = null worn_icon_state = "lightstick" grind_results = list(/datum/reagent/phenol = 15, /datum/reagent/hydrogen = 10, /datum/reagent/oxygen = 5) //Meth-in-a-stick sound_on = 'sound/effects/wounds/crack2.ogg' // the cracking sound isn't just for wounds silly toggle_context = FALSE ignore_base_color = TRUE /// How much max fuel we have var/max_fuel = 0 /// How much oxygen gets added upon cracking the stick. Doesn't actually produce a reaction with the fluid but it does allow for bootleg chemical "grenades" var/oxygen_added = 5 /// How much temperature gets added for every unit of fuel burned down var/temp_per_fuel = 3 /// Type of reagent we add as fuel var/fuel_type = /datum/reagent/luminescent_fluid /// The timer id powering our burning var/timer_id = TIMER_ID_NULL /obj/item/flashlight/glowstick/Initialize(mapload, fuel_override = null, fuel_type_override = null) max_fuel = isnull(fuel_override) ? rand(20, 25) : fuel_override if (fuel_type_override) fuel_type = fuel_type_override create_reagents(max_fuel + oxygen_added, DRAWABLE | INJECTABLE) reagents.add_reagent(fuel_type, max_fuel) . = ..() set_light_color(color) AddComponentFrom( SOURCE_EDIBLE_INNATE,\ /datum/component/edible,\ food_flags = FOOD_NO_EXAMINE,\ volume = reagents.total_volume,\ bite_consumption = round(reagents.total_volume / (rand(20, 30) * 0.1)),\ ) RegisterSignal(reagents, COMSIG_REAGENTS_HOLDER_UPDATED, PROC_REF(on_reagent_change)) /obj/item/flashlight/glowstick/proc/get_fuel() return reagents.get_reagent_amount(fuel_type) /// Burns down the glowstick by the specified time /// Returns the amount of time we need to burn before a visual change will occur /obj/item/flashlight/glowstick/proc/burn_down(amount = 0) if (!reagents.remove_all(amount)) turn_off() return 0 var/fuel = get_fuel() if (fuel <= 0) turn_off() return 0 reagents.expose_temperature(amount * temp_per_fuel) if(fuel >= max_fuel * 0.4) set_light_range(3) set_light_power(1.5) else if(fuel >= max_fuel * 0.3) set_light_range(2) set_light_power(1.25) else if(fuel >= max_fuel * 0.2) set_light_power(1) else if(fuel >= max_fuel * 0.1) set_light_range(1.5) set_light_power(0.5) return round(reagents.total_volume * 0.1) /obj/item/flashlight/glowstick/proc/burn_loop(amount = 0) timer_id = TIMER_ID_NULL var/burn_next = burn_down(amount) if(burn_next <= 0) return timer_id = addtimer(CALLBACK(src, PROC_REF(burn_loop), burn_next), burn_next MINUTES, TIMER_UNIQUE|TIMER_STOPPABLE|TIMER_OVERRIDE) /obj/item/flashlight/glowstick/proc/turn_on() reagents.add_reagent(/datum/reagent/oxygen, oxygen_added) grind_results -= /datum/reagent/oxygen set_light_on(TRUE) // Just in case var/datum/action/toggle = locate(/datum/action/item_action/toggle_light) in actions // No sense having a toggle light action that we don't use eh? if(toggle) remove_item_action(toggle) burn_loop(round(reagents.total_volume * 0.1)) /obj/item/flashlight/glowstick/proc/turn_off() var/datum/action/toggle = locate(/datum/action/item_action/toggle_light) in actions if(get_fuel() && !toggle) add_item_action(/datum/action/item_action/toggle_light) if(timer_id != TIMER_ID_NULL) deltimer(timer_id) timer_id = TIMER_ID_NULL set_light_on(FALSE) update_appearance(UPDATE_ICON) /obj/item/flashlight/glowstick/proc/on_reagent_change(datum/source) SIGNAL_HANDLER if (!get_fuel() && light_on) turn_off() /obj/item/flashlight/glowstick/update_icon_state() . = ..() icon_state = "[base_icon_state][(get_fuel() <= 0) ? "-empty" : ""]" inhand_icon_state = "[base_icon_state][((get_fuel() > 0) && light_on) ? "-on" : ""]" /obj/item/flashlight/glowstick/update_overlays() . = ..() if(get_fuel() <= 0 && !light_on) return var/mutable_appearance/glowstick_overlay = mutable_appearance(icon, "glowstick-glow") glowstick_overlay.color = color . += glowstick_overlay /obj/item/flashlight/glowstick/toggle_light(mob/user) if(get_fuel() <= 0) return FALSE if(light_on) return FALSE return ..() /obj/item/flashlight/glowstick/attack_self(mob/user) if(get_fuel() <= 0) balloon_alert(user, "glowstick is spent!") return if(light_on) balloon_alert(user, "already lit!") return . = ..() if(.) user.visible_message(span_notice("[user] cracks and shakes [src]."), span_notice("You crack and shake [src], turning it on!")) turn_on() /obj/item/flashlight/glowstick/suicide_act(mob/living/carbon/human/user) if(!get_fuel()) user.visible_message(span_suicide("[user] is trying to squirt [src]'s fluids into [user.p_their()] eyes... but it's empty!")) return SHAME var/obj/item/organ/eyes/eyes = user.get_organ_slot(ORGAN_SLOT_EYES) if(!eyes) user.visible_message(span_suicide("[user] is trying to squirt [src]'s fluids into [user.p_their()] eyes... but [user.p_they()] don't have any!")) return SHAME user.visible_message(span_suicide("[user] is squirting [src]'s fluids into [user.p_their()] eyes! It looks like [user.p_theyre()] trying to commit suicide!")) burn_loop(get_fuel()) return FIRELOSS /obj/item/flashlight/glowstick/red name = "red glowstick" color = COLOR_SOFT_RED fuel_type = /datum/reagent/luminescent_fluid/red /obj/item/flashlight/glowstick/blue name = "blue glowstick" color = LIGHT_COLOR_BLUE fuel_type = /datum/reagent/luminescent_fluid/blue /obj/item/flashlight/glowstick/cyan name = "cyan glowstick" color = LIGHT_COLOR_CYAN fuel_type = /datum/reagent/luminescent_fluid/cyan /obj/item/flashlight/glowstick/orange name = "orange glowstick" color = LIGHT_COLOR_ORANGE fuel_type = /datum/reagent/luminescent_fluid/orange /obj/item/flashlight/glowstick/yellow name = "yellow glowstick" color = LIGHT_COLOR_DIM_YELLOW fuel_type = /datum/reagent/luminescent_fluid/yellow /obj/item/flashlight/glowstick/pink name = "pink glowstick" color = LIGHT_COLOR_PINK fuel_type = /datum/reagent/luminescent_fluid/pink /obj/item/flashlight/spotlight //invisible lighting source name = "disco light" desc = "Groovy..." icon_state = null light_system = OVERLAY_LIGHT light_range = 4 light_power = 2 alpha = 0 layer = ABOVE_OPEN_TURF_LAYER plane = FLOOR_PLANE anchored = TRUE resistance_flags = INDESTRUCTIBLE | LAVA_PROOF | FIRE_PROOF | UNACIDABLE | ACID_PROOF ///Boolean that switches when a full color flip ends, so the light can appear in all colors. var/even_cycle = FALSE ///Base light_range that can be set on Initialize to use in smooth light range expansions and contractions. var/base_light_range = 4 start_on = TRUE /obj/item/flashlight/spotlight/Initialize(mapload, _light_range, _light_power, _light_color) . = ..() if(!isnull(_light_range)) base_light_range = _light_range set_light_range(_light_range) if(!isnull(_light_power)) set_light_power(_light_power) if(!isnull(_light_color)) set_light_color(_light_color) /obj/item/flashlight/flashdark name = "flashdark" desc = "A powerful antiphoton projector, capable of projecting a bubble of darkness around the user." icon_state = "flashdark" inhand_icon_state = "flashdark" light_system = COMPLEX_LIGHT //The overlay light component is not yet ready to produce darkness. light_range = 0 light_color = COLOR_WHITE ///Variable to preserve old lighting behavior in flashlights, to handle darkness. var/dark_light_range = 3.5 ///Variable to preserve old lighting behavior in flashlights, to handle darkness. var/dark_light_power = -3 /obj/item/flashlight/flashdark/Initialize(mapload) . = ..() AddComponent(/datum/component/overlay_lighting, dark_light_range, dark_light_power, force = TRUE) /obj/item/flashlight/flashdark/update_brightness() . = ..() set_light(dark_light_range, dark_light_power) //type and subtypes spawned and used to give some eyes lights, /obj/item/flashlight/eyelight name = "eyelight" desc = "This shouldn't exist outside of someone's head, how are you seeing this?" obj_flags = CONDUCTS_ELECTRICITY item_flags = DROPDEL actions_types = list() /obj/item/flashlight/eyelight/glow light_system = OVERLAY_LIGHT_BEAM light_range = 4 light_power = 2 #undef FAILURE #undef SUCCESS #undef NO_FUEL #undef ALREADY_LIT
412
0.974737
1
0.974737
game-dev
MEDIA
0.959986
game-dev
0.960537
1
0.960537
ClusterLabs/pacemaker
4,978
cts/schemas/test-3/ref/nagios.ref-99
<cib crm_feature_set="3.19.7" validate-with="pacemaker-4.0" epoch="8" num_updates="0" admin_epoch="0"> <configuration> <!-- The essential elements of this test are: * There is an nagios template and an ocf template. * There are nagios and ocf primitives, defined either inline or by reference to the corresponding template. * There is a group with only nagios primitives and a group with both nagios and ocf primitives. * There is a cloned nagios resource and a cloned ocf resource. * There is a cloned group containing only nagios primitives and a cloned group containing both nagios and ocf primitives. * There is a bundle containing an nagios primitive. * There are various constraints, many of which reference nagios resources. In this situation: * The nagios templates and primitives should be dropped, while the ocf ones should be kept. * Groups and clones that would become empty should be dropped. * Groups containing ocf primitives should be kept; only their nagios members should be dropped. * The bundle should be kept so that its container remains managed; its primitive should be dropped. * Constraints with attributes referencing nagios resources should be dropped. * Resource sets containing only references to nagios resources should be dropped. * Constraints with resource sets should be dropped if all of their resource sets should be dropped. --> <crm_config/> <nodes/> <resources> <template id="template_keep" class="ocf" provider="pacemaker" type="Dummy"/> <primitive id="primitive2_keep" class="ocf" provider="pacemaker" type="Dummy"/> <primitive id="primitive4_keep" template="template_keep"/> <group id="grp2_keep"> <primitive id="grp2_rsc2_keep" class="ocf" provider="pacemaker" type="Dummy"/> <primitive id="grp2_rsc4_keep" template="template_keep"/> </group> <clone id="clone2_keep"> <primitive id="clone2_rsc_keep" class="ocf" provider="pacemaker" type="Dummy"/> </clone> <clone id="clone4_keep"> <group id="clone4_grp_keep"> <primitive id="clone4_grp_rsc2_keep" class="ocf" provider="pacemaker" type="Dummy"/> <primitive id="clone4_grp_rsc4_keep" template="template_keep"/> </group> </clone> <bundle id="bundle_keep"> <podman image="image"/> </bundle> </resources> <constraints> <rsc_location id="location2_keep" rsc="primitive2_keep" node="node1" score="INFINITY"/> <rsc_location id="location4_keep" node="node1" score="INFINITY"> <resource_set id="location4_keep-set"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_location> <rsc_location id="location5_keep" node="node1" score="INFINITY"> <resource_set id="location5_keep-set_keep"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_location> <rsc_location id="location6_keep" rsc-pattern="primitive1_drop" node="node1" score="INFINITY"/> <rsc_colocation id="colocation4_keep" rsc="primitive4_keep" with-rsc="primitive2_keep"/> <rsc_colocation id="colocation6_keep"> <resource_set id="colocation6_keep-set"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_colocation> <rsc_colocation id="colocation7_keep"> <resource_set id="colocation7_keep-set_keep"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_colocation> <rsc_order id="order4_keep" first="primitive4_keep" then="primitive2_keep"/> <rsc_order id="order6_keep"> <resource_set id="order6_keep-set"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_order> <rsc_order id="order7_keep"> <resource_set id="order7_keep-set_keep"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_order> <rsc_ticket id="ticket2_keep" rsc="primitive2_keep" ticket="ticket1"/> <rsc_ticket id="ticket4_keep" ticket="ticket1"> <resource_set id="ticket4_keep-set"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_ticket> <rsc_ticket id="ticket5_keep" ticket="ticket1"> <resource_set id="ticket5_keep-set_keep"> <resource_ref id="clone2_keep"/> <resource_ref id="clone4_keep"/> </resource_set> </rsc_ticket> </constraints> </configuration> <status/> </cib>
412
0.844655
1
0.844655
game-dev
MEDIA
0.398834
game-dev
0.855059
1
0.855059
setuppf/GameBookServer
1,488
11_02_world/src/libs/libserver/component.h
#pragma once #include "sn_object.h" #include "common.h" #include <functional> #include <list> class IEntity; class IDynamicObjectPool; class SystemManager; using TimerHandleFunction = std::function<void(void)>; class IComponent : virtual public SnObject { public: friend class EntitySystem; virtual ~IComponent() = default; void SetPool(IDynamicObjectPool* pPool); void SetParent(IEntity* pObj); void SetSystemManager(SystemManager* pObj); template<class T> T* GetParent(); IEntity* GetParent() const; SystemManager* GetSystemManager() const; virtual void BackToPool() = 0; virtual void ComponentBackToPool(); virtual const char* GetTypeName() = 0; virtual uint64 GetTypeHashCode() = 0; protected: void AddTimer(const int total, const int durations, const bool immediateDo, const int immediateDoDelaySecond, TimerHandleFunction handler); std::list<uint64> _timers; IEntity* _parent{ nullptr }; SystemManager* _pSystemManager{ nullptr }; IDynamicObjectPool* _pPool{ nullptr }; }; template <class T> T* IComponent::GetParent() { return dynamic_cast<T*>(_parent); } template<class T> class Component :public IComponent { public: const char* GetTypeName() override; uint64 GetTypeHashCode() override; }; template <class T> const char* Component<T>::GetTypeName() { return typeid(T).name(); } template <class T> uint64 Component<T>::GetTypeHashCode() { return typeid(T).hash_code(); }
412
0.936537
1
0.936537
game-dev
MEDIA
0.57385
game-dev
0.689053
1
0.689053
auQuiksilver/Apex-Framework
7,095
Apex_framework.terrain/code/functions/fn_clientVehicleEventIncomingMissile.sqf
/* File: fn_clientVehicleEventIncomingMissile.sqf Author: Quiksilver Last Modified: 27/01/2023 A3 2.12 by Quiksilver Description: Event Incoming Missile __________________________________________________________*/ params ['_vehicle','_ammo','_shooter','_instigator','_projectile']; if (!isNull _projectile) then { if (((missionNamespace getVariable ['QS_vehicle_incomingMissiles',[]]) findIf {(_projectile isEqualTo (_x # 0))}) isEqualTo -1) then { missionNamespace setVariable ['QS_vehicle_incomingMissiles',((missionNamespace getVariable 'QS_vehicle_incomingMissiles') select {(!isNull (_x # 0))}),FALSE]; missionNamespace setVariable ['QS_vehicle_incomingMissiles',((missionNamespace getVariable 'QS_vehicle_incomingMissiles') + [[_projectile,_shooter]]),FALSE]; }; if (!(_projectile in (missionNamespace getVariable 'QS_draw2D_projectiles'))) then { missionNamespace setVariable ['QS_draw2D_projectiles',((missionNamespace getVariable 'QS_draw2D_projectiles') + [_projectile]),FALSE]; }; if (!(_projectile in (missionNamespace getVariable 'QS_draw3D_projectiles'))) then { missionNamespace setVariable ['QS_draw3D_projectiles',((missionNamespace getVariable 'QS_draw3D_projectiles') + [_projectile]),FALSE]; }; if ((missionNamespace getVariable ['QS_missionConfig_APS',3]) in [2,3]) then { if (_vehicle isKindOf 'LandVehicle') then { if (!local _shooter) then { if (((vehicle _shooter) isKindOf 'CAManBase') || {((vehicle _shooter) isKindOf 'LandVehicle')} || {((vehicle _shooter) isKindOf 'StaticWeapon')}) then { [94,['HANDLE',['AT',_projectile,_shooter,_shooter,getPosATL (vehicle _shooter),TRUE]]] remoteExecCall ['QS_fnc_remoteExec',_shooter,FALSE]; }; } else { ['HANDLE',['AT',_projectile,_shooter,_shooter,getPosATL (vehicle _shooter),TRUE]] call (missionNamespace getVariable 'QS_fnc_clientProjectileManager'); }; }; }; }; private _text = ''; private _passiveResult = ''; if (local _vehicle) then { if ( ((_vehicle animationSourcePhase 'showcamonethull') isEqualTo 1) || {(_vehicle getVariable ['QS_vehicle_stealth',FALSE])} || {((toLowerANSI (typeOf _vehicle)) in (['stealth_aircraft_1'] call QS_data_listVehicles))} ) then { if ((_projectile distance _vehicle) > 300) then { if ((random 1) > 0.666) then { ['setMissileTarget',_projectile,objNull] remoteExec ['QS_fnc_remoteExecCmd',_instigator,FALSE]; _passiveResult = localize 'STR_QS_Text_383'; }; }; }; }; if ( (local _vehicle) && {((random 1) < ([_vehicle,_shooter,_projectile] call QS_fnc_vehicleGetPassiveStealth))} && {((_projectile distance _vehicle) > (_vehicle getVariable ['QS_vehicle_passiveStealth_minDist',100]))} && {((!alive _shooter) || ((alive _shooter) && (!(_shooter getVariable ['QS_vehicle_passiveStealth_ignore',FALSE]))))} ) then { [_projectile,_instigator,_vehicle] spawn { params ['_projectile','_instigator','_vehicle']; uiSleep (0.1 + (random 1.5)); ['setMissileTarget',_projectile,objNull] remoteExec ['QS_fnc_remoteExecCmd',_instigator,FALSE]; ['forgetTarget',(group _instigator),_vehicle] remoteExec ['QS_fnc_remoteExecCmd',_instigator,FALSE]; }; _passiveResult = localize 'STR_QS_Text_383'; }; if (diag_tickTime < (player getVariable ['QS_incomingMissile_active',-1])) exitWith {}; player setVariable ['QS_incomingMissile_active',diag_tickTime + 2,FALSE]; if (!( (_vehicle isKindOf 'Air') && (player isEqualTo (driver _vehicle)) && (!((toLowerANSI (typeOf _vehicle)) in (['civil_aircraft_1'] call QS_data_listVehicles))) )) then { playSoundUI ['missile_warning_1',0.25,1,FALSE]; }; if (_vehicle isKindOf 'LandVehicle') then { playSound3D [getMissionPath 'media\audio\locking_2.wss',_vehicle,FALSE,getPosASL _vehicle,5,1,50,0,FALSE]; }; if ( (_vehicle isKindOf 'Air') && {(soundVolume isEqualTo (getAudioOptionVolumes # 5))} ) then { playSoundUI ['missile_warning_1',0.25,1,FALSE]; }; private _relDir = _vehicle getRelDir _shooter; private _relDirText = ''; if ((_relDir > 337.5) || {(_relDir <= 22.5)}) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_297']; } else { if ((_relDir > 22.5) && (_relDir <= 67.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_298']; } else { if ((_relDir > 67.5) && (_relDir <= 112.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_299']; } else { if ((_relDir > 112.5) && (_relDir <= 157.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_300']; } else { if ((_relDir > 157.5) && (_relDir <= 202.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_301']; } else { if ((_relDir > 202.5) && (_relDir <= 247.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_302']; } else { if ((_relDir > 247.5) && (_relDir <= 292.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_303']; } else { if ((_relDir > 292.5) && (_relDir <= 337.5)) then { _relDirText = format ['( %1 )',localize 'STR_QS_Text_304']; }; }; }; }; }; }; }; }; private _magazines = []; private _muzzle = ''; _ammo = toLowerANSI _ammo; private _ammo2 = ''; private _missileDisplayName = ''; if (_shooter isKindOf 'CAManBase') then { _muzzle = (_shooter weaponState (currentMuzzle _shooter)) # 1; _magazines = QS_hashmap_configfile getOrDefaultCall [ format ['cfgweapons_%1_magazines',toLowerANSI _muzzle], {getArray (configFile >> 'CfgWeapons' >> _muzzle >> 'magazines')}, TRUE ]; _ammo2 = ''; _missileDisplayName = ''; { _ammo2 = QS_hashmap_configfile getOrDefaultCall [ format ['cfgmagazines_%1_ammo',toLowerANSI _x], {getText (configFile >> 'CfgMagazines' >> _x >> 'ammo')}, TRUE ]; if ((toLowerANSI _ammo2) isEqualTo _ammo) exitWith { _missileDisplayName = QS_hashmap_configfile getOrDefaultCall [ format ['cfgmagazines_%1_displayname',toLowerANSI _x], {getText (configFile >> 'CfgMagazines' >> _x >> 'displayName')}, TRUE ]; }; } forEach _magazines; } else { _missileDisplayName = QS_hashmap_configfile getOrDefault [format ['cfgammo_%1_displayname',_ammo],'']; if (_missileDisplayName isEqualTo '') then { _magazines = (magazinesAllTurrets _shooter) apply {_x # 0}; { _ammo2 = QS_hashmap_configfile getOrDefaultCall [ format ['cfgmagazines_%1_ammo',toLowerANSI _x], {getText (configFile >> 'CfgMagazines' >> _x >> 'ammo')}, TRUE ]; if ((toLowerANSI _ammo2) isEqualTo _ammo) exitWith { _missileDisplayName = QS_hashmap_configfile getOrDefaultCall [ format ['cfgmagazines_%1_displayname',toLowerANSI _x], {getText (configFile >> 'CfgMagazines' >> _x >> 'displayName')}, TRUE ]; }; } forEach _magazines; QS_hashmap_configfile set [format ['cfgammo_%1_displayname',_ammo],_missileDisplayName]; }; }; _text = format ['%1 %2 %3<br/><br/>%4',localize 'STR_QS_Text_200',(round (_vehicle getDir _shooter)),_relDirText,_missileDisplayName]; if (_passiveResult isNotEqualTo '') then { _text = _text + (format ['<br/><br/>%1',_passiveResult]); }; 50 cutText [_text,'PLAIN DOWN',0.666,TRUE,TRUE];
412
0.960697
1
0.960697
game-dev
MEDIA
0.989353
game-dev
0.933414
1
0.933414
blovemaple/mahjong
9,359
src/main/java/com/github/blovemaple/mj/local/barbot/BarBotCpgdSelectTask.java
package com.github.blovemaple.mj.local.barbot; import static com.github.blovemaple.mj.action.standard.PlayerActionTypes.*; import static com.github.blovemaple.mj.utils.LambdaUtils.*; import static com.github.blovemaple.mj.utils.MyUtils.*; import static java.util.Comparator.*; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import com.github.blovemaple.mj.action.ActionType; import com.github.blovemaple.mj.action.PlayerAction; import com.github.blovemaple.mj.action.PlayerActionType; import com.github.blovemaple.mj.cli.CliGameView; import com.github.blovemaple.mj.game.GameContextPlayerView; import com.github.blovemaple.mj.object.PlayerInfo; import com.github.blovemaple.mj.object.Tile; import com.github.blovemaple.mj.object.TileGroupPlayerView; import com.github.blovemaple.mj.object.TileType; import com.github.blovemaple.mj.rule.win.WinType; /** * 换牌n个:remove n,add n+1 * * @author blovemaple <blovemaple2010(at)gmail.com> */ @Deprecated public class BarBotCpgdSelectTask implements Callable<PlayerAction> { private static final Logger logger = Logger.getLogger(BarBotCpgdSelectTask.class.getSimpleName()); public static final Set<ActionType> ACTION_TYPES = new HashSet<>( Arrays.asList(CHI, PENG, ZHIGANG, BUGANG, ANGANG, DISCARD, DISCARD_WITH_TING)); private static final int EXTRA_CHANGE_COUNT = 2; private static final int EXTENDED_MAX_CHANGE_COUNT = 4; private static final int MAX_CHANGE_COUNT = 10; private GameContextPlayerView contextView; private Set<PlayerActionType> actionTypes; private PlayerInfo playerInfo; @SuppressWarnings("unused") private boolean stopRequest = false; public BarBotCpgdSelectTask(GameContextPlayerView contextView, Set<PlayerActionType> actionTypes) { this.contextView = contextView; this.actionTypes = actionTypes; this.playerInfo = contextView.getMyInfo(); } private String aliveTilesStr() { StringBuilder aliveTilesStr = new StringBuilder(); CliGameView.appendAliveTiles(aliveTilesStr, playerInfo.getAliveTiles(), playerInfo.getLastDrawedTile(), null); return aliveTilesStr.toString(); } @Override // interrupt public PlayerAction call() throws Exception { long startTime = System.currentTimeMillis(); // 生成所有可选动作(包括不做动作)后的状态 List<BarBotCpgdChoice> choices = allChoices(); if (choices.isEmpty()) { logger.info("[No choices]"); logger.info("Bot alivetiles " + aliveTilesStr()); return null; } // 如果只有一个选择,就直接选择 if (choices.size() == 1) { PlayerAction action = choices.get(0).getAction(); logger.info("[Single choice] " + action); logger.info("Bot alivetiles " + aliveTilesStr()); return action; } // 从0次换牌开始,计算每个状态换牌后和牌的概率 AtomicInteger minChangeCount = new AtomicInteger(-1); int aliveTileSize = playerInfo.getAliveTiles().size(); int changeCount = 0; for (; true; changeCount++) { if (changeCount >= aliveTileSize) break; if (changeCount > MAX_CHANGE_COUNT) break; if (minChangeCount.get() >= 0 && changeCount > EXTENDED_MAX_CHANGE_COUNT) break; if (minChangeCount.get() >= 0 && changeCount - minChangeCount.get() > EXTRA_CHANGE_COUNT) break; int crtChangeCount = changeCount; choices.parallelStream().map(rethrowFunction(choice -> choice.testWinProb(crtChangeCount))) .filter(result -> result == Boolean.TRUE) .forEach(win -> minChangeCount.compareAndSet(-1, crtChangeCount)); } // 算出和牌概率最大的一个动作 PlayerAction bestAction = choices.stream() .peek(choice -> logger .info("[Win prob] " + String.format("%.7f %s", choice.getFinalWinProb(), choice.getAction()))) // 第一条件:和牌概率大 .max(comparing(BarBotCpgdChoice::getFinalWinProb) // 第二条件:杠优先(因为杠了之后可以多摸一张牌,这个好处在算概率的时候没算进去) .thenComparing(choice -> choice.getAction() != null && Arrays.asList(ZHIGANG, BUGANG, ANGANG) .stream().anyMatch(gang -> gang.matchBy(choice.getAction().getType()))) // 第三条件:听牌优先 .thenComparing(choice -> choice.getPlayerInfo().isTing()) // 第四条件:前面的优先(和牌类型的返回结果中认为最差的) .thenComparing(comparing(choices::indexOf).reversed())) // 取出其动作 .map(BarBotCpgdChoice::getAction).orElse(null); StringBuilder aliveTilesStr = new StringBuilder(); CliGameView.appendAliveTiles(aliveTilesStr, playerInfo.getAliveTiles(), playerInfo.getLastDrawedTile(), null); logger.info("Bot alivetiles " + aliveTilesStr); logger.info("Bot Choose action " + bestAction); logger.info("Bot time " + (System.currentTimeMillis() - startTime)); return bestAction; } private List<BarBotCpgdChoice> allChoices() { List<BarBotCpgdChoice> choices = actionTypes.stream().filter(ACTION_TYPES::contains).flatMap(actionType -> { Stream<Set<Tile>> legalTileSets = actionType.getLegalActionTiles(contextView).stream(); legalTileSets = distinctCollBy(legalTileSets, Tile::type); if (DISCARD != actionType || playerInfo.isTing()) { return legalTileSets.map(tiles -> new BarBotCpgdChoice(contextView, playerInfo, new PlayerAction(contextView.getMyLocation(), actionType, tiles), this, contextView.getGameStrategy().getAllWinTypes())); } else { Map<? extends WinType, List<Tile>> discardsByWinType = contextView.getGameStrategy().getAllWinTypes() .stream().collect(Collectors.toMap(Function.identity(), winType -> winType.getDiscardCandidates(playerInfo.getAliveTiles(), remainTiles()))); Set<Tile> legalTiles = legalTileSets.flatMap(Set::stream).collect(Collectors.toSet()); Map<Tile, Double> tilesAndPriv = discardsByWinType.values().stream().flatMap(List::stream).distinct() .filter(legalTiles::contains).collect( Collectors.toMap(Function.identity(), tile -> discardsByWinType.values().stream().map(list -> list.indexOf(tile)) .mapToInt(index -> index >= 0 ? index : playerInfo.getAliveTiles().size() - 1) .average().getAsDouble())); return discardsByWinType.values().stream().flatMap(List::stream).distinct().filter(legalTiles::contains) .sorted(Comparator.comparing(tilesAndPriv::get)).map(tile -> { List<WinType> winTypes = discardsByWinType.entrySet().stream() .filter(entry -> entry.getValue().contains(tile)).map(Map.Entry::getKey) .collect(Collectors.toList()); return new BarBotCpgdChoice(contextView, playerInfo, new PlayerAction(contextView.getMyLocation(), actionType, Set.of(tile)), this, winTypes); }); } }).filter(Objects::nonNull).collect(Collectors.toList()); if (actionTypes.stream().noneMatch(DISCARD::matchBy)) choices.add(new BarBotCpgdChoice(contextView, playerInfo, null, this, contextView.getGameStrategy().getAllWinTypes())); return choices; } private List<Tile> remainTiles; private Map<TileType, Long> remainTilesByType; /** * 返回所有剩余牌(本家看不到的所有牌)。 */ public List<Tile> remainTiles() { if (remainTiles == null) { // 除了本家手牌、所有玩家groups、已经打出的牌 Set<Tile> existTiles = new HashSet<>(); existTiles.addAll(contextView.getMyInfo().getAliveTiles()); contextView.getTableView().getPlayerInfoView().values().forEach(playerInfo -> { playerInfo.getTileGroups().stream() .map(TileGroupPlayerView::getTiles).filter(Objects::nonNull) .forEach(existTiles::addAll); existTiles.addAll(playerInfo.getDiscardedTiles()); }); List<Tile> remainTiles = contextView.getGameStrategy().getAllTiles().stream() .filter(tile -> !existTiles.contains(tile)).collect(Collectors.toList()); remainTilesByType = remainTiles.stream() .collect(Collectors.groupingBy(Tile::type, HashMap::new, Collectors.counting())); /* * 因为remainTileCountByType用此方法保证remainTilesByType的存在, * 所以remainTilesByType在remainTiles之前赋值 */ this.remainTiles = remainTiles; } return remainTiles; } public Map<TileType, Long> remainTileCountByType() { remainTiles(); return remainTilesByType; } public int remainTileCount() { return remainTiles().size(); } private Map<Integer, Double> probCache = Collections.synchronizedMap(new HashMap<>()); /** * 计算addedTiles出现的可能性。<br> * addedTiles出现的可能性=(在剩余牌中选到addedTiles的组合数)/(在剩余牌中选addedTiles个牌的组合数) */ public double getProb(Collection<Tile> addedTiles) { int hash = addedTiles.stream().mapToInt(Tile::hashCode).sum(); Double prob = probCache.get(hash); if (prob == null) { Map<TileType, List<Tile>> addedByType = addedTiles.stream().collect(Collectors.groupingBy(Tile::type)); Map<TileType, Long> remainTiles = remainTileCountByType(); AtomicLong addedComb = new AtomicLong(1); addedByType.forEach((type, added) -> addedComb .getAndAccumulate(combCount(remainTiles.get(type), added.size()), Math::multiplyExact)); prob = (double) addedComb.get() / combCount(remainTileCount(), addedTiles.size()); probCache.put(hash, prob); } return prob; } /** * 中止任务,根据当前已经进行的判断尽快产生结果。 */ public void stop() { stopRequest = true; } }
412
0.887074
1
0.887074
game-dev
MEDIA
0.496293
game-dev
0.990343
1
0.990343