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
AXiX-official/CrossCoreLuascripts
1,115
ios/Buffers/Buffer2902.lua
-- 排压盾 -- 本文件由工具自动生成,请不要直接编辑本文件 --------------------------------------------- -- 技能基类 Buffer2902 = oo.class(BuffBase) function Buffer2902:Init(mgr, id, target, caster) BuffBase.Init(self, mgr, id, target, caster) end -- 伤害前 function Buffer2902:OnBefourHurt(caster, target) -- 8063 if SkillJudger:CasterIsEnemy(self, self.caster, target, true) then else return end -- 8070 if SkillJudger:TargetIsSelf(self, self.caster, target, true) then else return end -- 102300201 self:AddTempAttr(BufferEffect[102300201], self.caster, self.caster, nil, "crit",-0.3) end -- 创建时 function Buffer2902:OnCreate(caster, target) -- 2902 self:AddReduceShield(BufferEffect[2902], self.caster, target or self.owner, nil,0.3,1,0.1) -- 8462 local c62 = SkillApi:SkillLevel(self, self.caster, target or self.owner,4,3228) -- 322801 self:AddAttr(BufferEffect[322801], self.caster, target or self.owner, nil,"speed",c62*5) -- 8462 local c62 = SkillApi:SkillLevel(self, self.caster, target or self.owner,4,3228) -- 322811 self:AddAttr(BufferEffect[322811], self.caster, target or self.owner, nil,"resist",0.05*c62) end
0
0.517035
1
0.517035
game-dev
MEDIA
0.930382
game-dev
0.593779
1
0.593779
ray-cast/Cubizer
4,455
Standard Assets/Utility/SimpleMouseRotator.cs
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; namespace UnityStandardAssets.Utility { public class SimpleMouseRotator : MonoBehaviour { // A mouselook behaviour with constraints which operate relative to // this gameobject's initial rotation. // Only rotates around local X and Y. // Works in local coordinates, so if this object is parented // to another moving gameobject, its local constraints will // operate correctly // (Think: looking out the side window of a car, or a gun turret // on a moving spaceship with a limited angular range) // to have no constraints on an axis, set the rotationRange to 360 or greater. public Vector2 rotationRange = new Vector3(70, 70); public float rotationSpeed = 10; public float dampingTime = 0.2f; public bool autoZeroVerticalOnMobile = true; public bool autoZeroHorizontalOnMobile = false; public bool relative = true; private Vector3 m_TargetAngles; private Vector3 m_FollowAngles; private Vector3 m_FollowVelocity; private Quaternion m_OriginalRotation; private void Start() { m_OriginalRotation = transform.localRotation; } private void Update() { // we make initial calculations from the original local rotation transform.localRotation = m_OriginalRotation; // read input from mouse or mobile controls float inputH; float inputV; if (relative) { inputH = CrossPlatformInputManager.GetAxis("Mouse X"); inputV = CrossPlatformInputManager.GetAxis("Mouse Y"); // wrap values to avoid springing quickly the wrong way from positive to negative if (m_TargetAngles.y > 180) { m_TargetAngles.y -= 360; m_FollowAngles.y -= 360; } if (m_TargetAngles.x > 180) { m_TargetAngles.x -= 360; m_FollowAngles.x -= 360; } if (m_TargetAngles.y < -180) { m_TargetAngles.y += 360; m_FollowAngles.y += 360; } if (m_TargetAngles.x < -180) { m_TargetAngles.x += 360; m_FollowAngles.x += 360; } #if MOBILE_INPUT // on mobile, sometimes we want input mapped directly to tilt value, // so it springs back automatically when the look input is released. if (autoZeroHorizontalOnMobile) { m_TargetAngles.y = Mathf.Lerp (-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f); } else { m_TargetAngles.y += inputH * rotationSpeed; } if (autoZeroVerticalOnMobile) { m_TargetAngles.x = Mathf.Lerp (-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f); } else { m_TargetAngles.x += inputV * rotationSpeed; } #else // with mouse input, we have direct control with no springback required. m_TargetAngles.y += inputH*rotationSpeed; m_TargetAngles.x += inputV*rotationSpeed; #endif // clamp values to allowed range m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y*0.5f, rotationRange.y*0.5f); m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x*0.5f, rotationRange.x*0.5f); } else { inputH = Input.mousePosition.x; inputV = Input.mousePosition.y; // set values to allowed range m_TargetAngles.y = Mathf.Lerp(-rotationRange.y*0.5f, rotationRange.y*0.5f, inputH/Screen.width); m_TargetAngles.x = Mathf.Lerp(-rotationRange.x*0.5f, rotationRange.x*0.5f, inputV/Screen.height); } // smoothly interpolate current values to target angles m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime); // update the actual gameobject's rotation transform.localRotation = m_OriginalRotation*Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0); } } }
0
0.775352
1
0.775352
game-dev
MEDIA
0.91251
game-dev
0.841473
1
0.841473
tvdboom/fortress
45,335
src/game/weapon/components.rs
use crate::constants::{ EnemyQ, EXPLOSION_Z, MAP_SIZE, MAX_FLAMETHROWER_POWER, MAX_SPOTS, SIZE, WEAPONS_PANEL_SIZE, }; use crate::game::assets::WorldAssets; use crate::game::enemy::components::Enemy; use crate::game::map::components::{AnimationComponent, FogOfWar}; use crate::game::map::utils::is_visible; use crate::game::resources::{GameSettings, Player, Resources}; use crate::utils::scale_duration; use bevy::prelude::*; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::f32::consts::PI; use std::time::Duration; #[derive(Component)] pub struct FenceComponent; #[derive(Component)] pub struct WallComponent; #[derive(Component)] pub struct Mine; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub enum WeaponName { AAA, Artillery, Canon, Flamethrower, MachineGun, MissileLauncher, Mortar, Turret, } #[derive(Clone)] pub struct FireAnimation { /// Name of the asset for firing animation pub atlas: &'static str, /// Scaling factor for the image pub scale: Vec3, /// Duration of the animation timer pub duration: f32, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum FireStrategy { /// Don't fire None, /// Fire at the closest enemy Closest, /// Fire at enemy with the highest `max_health` Strongest, /// Fire at the enemy with the most surrounding enemies at /// a distance given by the explosion's `radius` Density, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum AirFireStrategy { None, All, Grounded, Airborne, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum MortarShell { None, Light, Heavy, } #[derive(Clone)] pub struct Upgrade { /// Upgrade description pub description: &'static str, /// Texture corresponding to an asset pub texture: &'static str, /// Upgrade cost pub price: Resources, } #[derive(Component, Clone)] pub struct Weapon { /// Name of the weapon pub name: WeaponName, /// Name of the asset for sprite pub image: &'static str, /// Short description pub description: &'static str, /// Dimensions (size) of the sprite pub dim: Vec2, /// Maximum number that can be bought pub maximum: u32, /// Rotation speed in radians per second pub rotation_speed: f32, /// Price to buy the weapon pub price: Resources, /// Animation to play when firing pub fire_animation: FireAnimation, /// Number of bullets fired per shot pub n_bullets: u32, /// Target entity to point to pub target: Option<Entity>, /// Time between shots (reload time) pub fire_timer: Option<Timer>, /// Strategy to select a target pub fire_strategy: FireStrategy, /// The minimum distance at which the weapon can shoot pub min_distance: f32, /// Bullet fired by the weapon pub bullet: Bullet, /// Upgrades for the weapon pub upgrade1: Upgrade, pub upgrade2: Upgrade, } #[derive(Clone)] pub struct Damage { /// Damage to ground enemies pub ground: f32, /// Damage to flying enemies pub air: f32, /// Armor penetration. Also damages structures if in explosion pub penetration: f32, } impl Default for Damage { fn default() -> Self { Self { ground: 0., air: 0., penetration: 0., } } } impl Damage { /// Calculate the damage inflicted on `enemy` pub fn calculate(&self, enemy: &Enemy) -> f32 { let base = if enemy.flies { self.air } else { self.ground }; (base - (enemy.armor - self.penetration).max(0.)).max(0.) } } #[derive(Clone)] pub struct Explosion { /// Name of the asset for firing animation pub atlas: &'static str, /// Interval between frames (in seconds) pub interval: f32, /// Explosion radius pub radius: f32, /// Damage inflicted by the explosion pub damage: Damage, } impl Default for Explosion { fn default() -> Self { Self { atlas: "explosion1", interval: 0.01, radius: 0., damage: default(), } } } #[derive(Clone)] pub enum Movement { /// Bullets impacts at fist enemy hit Straight, /// Bullet impacts at location Location(Vec3), /// Bullets impacts on `Entity` Homing(Entity), /// Bullets impacts on `Entity` and damages everything it hits PiercingHoming(Entity), } #[derive(Clone)] pub enum Impact { /// Damage is applied to a single enemy SingleTarget(Damage), /// Piercing bullets don't despawn after hitting an enemy Piercing { damage: Damage, hits: HashSet<Entity>, // Keep track of enemies already hit }, /// Explodes after colliding with an enemy Explosion(Explosion), } impl Impact { /// Resolve the impact of the bullet on the enemy /// Return whether the impact was resolved pub fn resolve( &mut self, commands: &mut Commands, bullet_e: Entity, bullet_t: &Transform, enemy: Option<(Entity, &mut Enemy)>, assets: &Local<WorldAssets>, ) -> bool { match self { Impact::SingleTarget(d) => { let (_, enemy) = enemy.unwrap(); if (d.ground > 0. && !enemy.flies) || (d.air > 0. && enemy.flies) { enemy.health -= d.calculate(enemy).min(enemy.health); commands.entity(bullet_e).try_despawn(); return true; } } Impact::Piercing { damage: d, hits } => { let (enemy_e, enemy) = enemy.unwrap(); // The same enemy can only be hit once if !hits.contains(&enemy_e) { if (d.ground > 0. && !enemy.flies) || (d.air > 0. && enemy.flies) { enemy.health -= d.calculate(enemy).min(enemy.health); hits.insert(enemy_e); return true; } } } Impact::Explosion(e) => { // If an enemy is passed, check it can trigger the explosion // E.g., a mine can collide with a flying enemy, and it shouldn't explode if let Some((_, enemy)) = enemy { if (e.damage.ground == 0. && !enemy.flies) || (e.damage.air == 0. && enemy.flies) { return false; } } commands.entity(bullet_e).try_despawn(); let atlas_asset = assets.get_atlas(e.atlas); commands.spawn(( Sprite { image: atlas_asset.image, texture_atlas: Some(atlas_asset.texture), custom_size: Some(Vec2::splat(2. * e.radius)), ..default() }, Transform::from_xyz( bullet_t.translation.x, bullet_t.translation.y, EXPLOSION_Z, ), AnimationComponent { timer: Timer::from_seconds(e.interval, TimerMode::Repeating), last_index: atlas_asset.last_index, explosion: Some(e.clone()), }, )); return true; } } false } } #[derive(Component, Clone)] pub struct Bullet { /// Name of the asset for sprite pub image: &'static str, /// Dimensions (size) of the sprite pub dim: Vec2, /// Cost per bullet pub price: Resources, /// Distance traveled per second pub speed: f32, /// Movement type pub movement: Movement, /// Impact type (what happens on collision) pub impact: Impact, /// Current distance traveled by the bullet pub distance: f32, /// The maximum distance the bullet can travel (despawn after) pub max_distance: f32, } impl Weapon { /// Acquire a target to fire at. If `self.target` is empty, it will /// select a new target excluding the entities in `exclusions`. pub fn acquire_target( &self, transform: &Transform, enemy_q: &Query<EnemyQ, (With<Enemy>, Without<Weapon>)>, fow_q: &Query<&Transform, (With<FogOfWar>, Without<Weapon>)>, exclusions: &HashSet<Entity>, ) -> Option<Entity> { // Return target if it's already acquired, and it still exists and is visible if let Some(enemy_e) = self.target.and_then(|enemy_e| { if let Ok((enemy_e, enemy_t, enemy)) = enemy_q.get(enemy_e) { if is_visible(&fow_q.get_single().unwrap(), enemy_t, enemy) && !exclusions.contains(&enemy_e) { return Some(enemy_e); } } None }) { return Some(enemy_e); } let targets: Vec<(EnemyQ, f32)> = enemy_q .iter() .filter_map(|(enemy_e, enemy_t, enemy)| { // Check if the enemy is behind the fog of war if !is_visible(fow_q.get_single().unwrap(), enemy_t, enemy) { return None; } // Don't shoot flying units when the bullet has only ground damage and vice versa match &self.bullet.impact { Impact::SingleTarget(d) | Impact::Piercing { damage: d, .. } | Impact::Explosion(Explosion { damage: d, .. }) => { if (d.ground == 0. && !enemy.flies) || (d.air == 0. && enemy.flies) { return None; } } } // Check if the enemy is in range let distance = transform.translation.distance(enemy_t.translation); if distance < self.min_distance || distance > self.bullet.max_distance { return None; } // Remove exclusions if exclusions.contains(&enemy_e) { return None; } Some(((enemy_e, enemy_t, enemy), distance)) }) .collect(); match self.fire_strategy { FireStrategy::None => None, FireStrategy::Closest => targets .iter() .min_by(|(_, d1), (_, d2)| d1.partial_cmp(d2).unwrap()) .map(|((enemy_e, _, _), _)| *enemy_e), FireStrategy::Strongest => targets .iter() .max_by(|((_, _, e1), _), ((_, _, e2), _)| { e1.max_health.partial_cmp(&e2.max_health).unwrap() }) .map(|((enemy_e, _, _), _)| *enemy_e), FireStrategy::Density => { if let Impact::Explosion(e) = &self.bullet.impact { targets .iter() .max_by(|((_, t1, _), _), ((_, t2, _), _)| { let density_a = targets .iter() .filter(|((_, t, _), _)| { t1.translation.distance(t.translation) <= e.radius }) .count(); let density_b = targets .iter() .filter(|((_, t, _), _)| { t2.translation.distance(t.translation) <= e.radius }) .count(); density_a.cmp(&density_b) }) .map(|((enemy_e, _, _), _)| *enemy_e) } else { panic!("Invalid impact type for FireStrategy::Density, expected Explosion.") } } } } /// Whether the weapon's timer is finished pub fn can_fire(&mut self, time: &Time, game_settings: &GameSettings) -> bool { if let Some(ref mut timer) = &mut self.fire_timer { timer.tick(scale_duration(time.delta(), game_settings.speed)); if timer.finished() { timer.reset(); // Start reload return true; } } false } /// Whether the weapon points at the given angle pub fn is_aiming(&self, angle: &f32, transform: &Transform) -> bool { // Accept a 0.1 tolerance (in radians) (angle - PI * 0.5 - transform.rotation.to_euler(EulerRot::XYZ).2).abs() < 0.1 } /// Update the weapon's based on the player's settings pub fn update(&mut self, player: &Player) { let upgrades = *player.weapons.upgrades.get(&self.name).unwrap_or(&(0, 0)); let upgrade1 = upgrades.0 as f32; let upgrade2 = upgrades.1 as f32; match self.name { WeaponName::AAA => { // Increase weapon range with upgrade self.bullet.max_distance = (0.6 + 0.1 * upgrade2) * MAP_SIZE.y; // Reset the target to avoid one last shot at the wrong enemy self.target = None; match player.weapons.settings.aaa { AirFireStrategy::None => self.fire_strategy = FireStrategy::None, AirFireStrategy::All => { self.fire_strategy = FireStrategy::Closest; self.bullet.impact = Impact::SingleTarget(Damage { ground: 5. + 5. * upgrade1, air: 5. + 5. * upgrade1, penetration: upgrade1, }) } AirFireStrategy::Airborne => { self.fire_strategy = FireStrategy::Closest; self.bullet.impact = Impact::SingleTarget(Damage { ground: 0., air: 20. + 5. * upgrade1, penetration: upgrade1, }) } _ => unreachable!(), }; } WeaponName::Artillery => { self.bullet.impact = Impact::SingleTarget(Damage { ground: 40. + 10. * upgrade1, air: 40. + 10. * upgrade1, penetration: 10. + upgrade1, }); self.fire_timer = Some(Timer::from_seconds(1. - 0.07 * upgrade2, TimerMode::Once)); self.target = None; self.fire_strategy = player.weapons.settings.artillery.clone(); } WeaponName::Canon => { // Reset the target to avoid one last shot at the wrong enemy self.target = None; match player.weapons.settings.canon { AirFireStrategy::None => self.fire_strategy = FireStrategy::None, AirFireStrategy::Grounded => { self.fire_strategy = FireStrategy::Closest; if let Impact::Explosion(ref mut explosion) = self.bullet.impact { explosion.damage = Damage { ground: 20. + 5. * upgrade1, air: 0., penetration: 0., }; explosion.radius = (0.08 + 0.02 * upgrade2) * MAP_SIZE.y; explosion.interval = 0.01 + 0.005 * upgrade2; } } AirFireStrategy::Airborne => { self.fire_strategy = FireStrategy::Closest; if let Impact::Explosion(ref mut explosion) = self.bullet.impact { explosion.damage = Damage { ground: 0., air: 20. + 5. * upgrade1, penetration: 0., }; explosion.radius = (0.08 + 0.02 * upgrade2) * MAP_SIZE.y; explosion.interval = 0.01 + 0.005 * upgrade2; } } _ => unreachable!(), }; } WeaponName::Flamethrower => match player.weapons.settings.flamethrower { 0 => self.fire_strategy = FireStrategy::None, _ => { let power = player.weapons.settings.flamethrower as f32; self.fire_strategy = FireStrategy::Closest; self.fire_animation.scale.x = 1.5 + power * 0.5; if let Some(timer) = self.fire_timer.as_mut() { timer.set_duration(Duration::from_secs_f32( 0.1 * (MAX_FLAMETHROWER_POWER + 1 - power as u32) as f32, )); } self.bullet.max_distance = 100. * (1.5 + power * 0.5); self.bullet.price.gasoline = power; if let Impact::Piercing { damage, .. } = &mut self.bullet.impact { *damage = Damage { ground: 5. + upgrade1, air: 5. + upgrade1, penetration: 5. + upgrade1 + 2. * upgrade2, } } } }, WeaponName::MachineGun => { match player.weapons.settings.machine_gun { 0 => { self.fire_timer = None; self.fire_strategy = FireStrategy::None; } v => { self.bullet.impact = Impact::SingleTarget(Damage { ground: 5. + 2. * upgrade1, air: 5. + 2. * upgrade1, penetration: 0., }); self.bullet.max_distance = (0.7 + 0.1 * upgrade2) * MAP_SIZE.y; self.fire_strategy = FireStrategy::Closest; if let Some(ref mut timer) = self.fire_timer { timer.set_duration(Duration::from_secs_f32(1. / v as f32)); } else { self.fire_timer = Some(Timer::from_seconds(1. / v as f32, TimerMode::Once)) } } }; } WeaponName::MissileLauncher => { if let Impact::Explosion(Explosion { radius, damage, .. }) = &mut self.bullet.impact { *radius = (0.1 + 0.02 * upgrade2) * MAP_SIZE.y; *damage = Damage { ground: 30. + 5. * upgrade1, air: 30. + 5. * upgrade1, penetration: 5. + upgrade1, } } self.n_bullets = player.weapons.settings.missile_launcher; if self.n_bullets == 0 { self.fire_strategy = FireStrategy::None; } else { self.fire_strategy = FireStrategy::Strongest; } } WeaponName::Mortar => { // Reset the target to recalculate the highest density self.target = None; self.n_bullets = 1 + upgrade2 as u32; match player.weapons.settings.mortar { MortarShell::None => self.fire_strategy = FireStrategy::None, MortarShell::Light => { self.fire_strategy = FireStrategy::Density; self.bullet.price = Resources { bullets: 15., ..default() }; self.bullet.impact = Impact::Explosion(Explosion { radius: 0.05 * MAP_SIZE.y, damage: Damage { ground: 50. + 10. * upgrade1, air: 50. + 10. * upgrade1, penetration: 0., }, ..default() }) } MortarShell::Heavy => { self.fire_strategy = FireStrategy::Density; self.bullet.price = Resources { bullets: 30., ..default() }; self.bullet.impact = Impact::Explosion(Explosion { radius: 0.1 * MAP_SIZE.y, damage: Damage { ground: 75. + 15. * upgrade1, air: 75. + 15. * upgrade1, penetration: 25. + 5. * upgrade1, }, ..default() }) } }; } WeaponName::Turret => { self.fire_timer = Some(Timer::from_seconds(1. - 0.07 * upgrade2, TimerMode::Once)); } } } } #[derive(Resource)] pub struct WeaponManager { pub aaa: Weapon, pub artillery: Weapon, pub canon: Weapon, pub flamethrower: Weapon, pub machine_gun: Weapon, pub mortar: Weapon, pub missile_launcher: Weapon, pub turret: Weapon, pub mine: Bullet, pub bomb: Bullet, pub nuke: Bullet, } impl WeaponManager { pub fn get(&self, name: &WeaponName) -> Weapon { match name { WeaponName::AAA => self.aaa.clone(), WeaponName::Artillery => self.artillery.clone(), WeaponName::Canon => self.canon.clone(), WeaponName::Flamethrower => self.flamethrower.clone(), WeaponName::MachineGun => self.machine_gun.clone(), WeaponName::Mortar => self.mortar.clone(), WeaponName::MissileLauncher => self.missile_launcher.clone(), WeaponName::Turret => self.turret.clone(), } } } impl Default for WeaponManager { fn default() -> Self { Self { aaa: Weapon { name: WeaponName::AAA, image: "weapon/aaa.png", description: "\ Medium range, single-target anti-aircraft artillery. Effective against flying \ units. Has two shooting strategies: all (shoots at all enemies doing low damage) \ and airborne (shoots only at flying enemies doing high damage).", dim: Vec2::new(80., 80.), maximum: MAX_SPOTS, rotation_speed: 5., target: None, price: Resources { materials: 300., ..default() }, fire_animation: FireAnimation { atlas: "single-flash", scale: Vec3::splat(0.5), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(0.5, TimerMode::Once)), fire_strategy: FireStrategy::Closest, min_distance: 0., bullet: Bullet { image: "weapon/shell.png", dim: Vec2::new(20., 7.), price: Resources { bullets: 10., ..default() }, speed: 1.2 * MAP_SIZE.y, movement: Movement::Straight, impact: Impact::SingleTarget(Damage { ground: 5., air: 5., penetration: 0., }), max_distance: 0.7 * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 150., ..default() }, }, upgrade2: Upgrade { description: "Increase the fire range.", texture: "range", price: Resources { technology: 75., ..default() }, }, }, artillery: Weapon { name: WeaponName::Artillery, image: "weapon/artillery.png", description:"\ Long range, single-target, high damage weapon. Although slow to reload, its \ high penetration bullets can kill even the strongest of foes. It has two \ firing strategies: closest (shoots at the closes enemy) and strongest (shoot \ at the enemy with the highest maximum health).", dim: Vec2::new(80., 80.), maximum: MAX_SPOTS, rotation_speed: 5., target: None, price: Resources { materials: 600., ..default() }, fire_animation: FireAnimation { atlas: "cone-flash", scale: Vec3::splat(0.5), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(1., TimerMode::Once)), fire_strategy: FireStrategy::Closest, min_distance: 0., bullet: Bullet { image: "weapon/bullet.png", dim: Vec2::new(30., 10.), price: Resources { bullets: 30., ..default() }, speed: 0.9 * MAP_SIZE.y, movement: Movement::Straight, impact: Impact::SingleTarget(Damage { ground: 45., air: 45., penetration: 40., }), max_distance: 1. * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 400., ..default() }, }, upgrade2: Upgrade { description: "Decrease the reload time.", texture: "reload", price: Resources { technology: 400., ..default() }, }, }, canon: Weapon { name: WeaponName::Canon, image: "weapon/canon.png", description:"\ Medium range and damage weapon that fires explosive shells. Slow to reload. It \ has two firing strategies: grounded (shoots only at ground enemies) and airborne \ (shoots only at flying enemies).", dim: Vec2::new(50., 70.), maximum: MAX_SPOTS, rotation_speed: 6., target: None, price: Resources { materials: 200., ..default() }, fire_animation: FireAnimation { atlas: "cone-flash", scale: Vec3::splat(0.5), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(2., TimerMode::Once)), fire_strategy: FireStrategy::Closest, min_distance: 0., bullet: Bullet { image: "weapon/grenade.png", dim: Vec2::new(25., 10.), price: Resources { bullets: 10., ..default() }, speed: 0.6 * MAP_SIZE.y, movement: Movement::Straight, impact: Impact::Explosion(Explosion { atlas: "explosion2", radius: 0.08 * MAP_SIZE.y, ..default() // Damage set when updating fire strategy }), max_distance: 0.9 * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 100., ..default() }, }, upgrade2: Upgrade { description: "Increase the explosion radius.", texture: "explosion", price: Resources { technology: 150., ..default() }, }, }, flamethrower: Weapon { name: WeaponName::Flamethrower, image: "weapon/flamethrower.png", description:"\ Short range, high damage weapon that shoots a continuous stream of fire. The \ flamethrower can adjust its firing power, increasing its range and damage at \ an increased gasoline consumption. All enemies in the stream take damage.", dim: Vec2::new(60., 60.), maximum: MAX_SPOTS, rotation_speed: 7., target: None, price: Resources { materials: 300., ..default() }, fire_animation: FireAnimation { atlas: "flame", scale: Vec3::new(3., 1., 1.), duration: 0.02, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(0.5, TimerMode::Once)), fire_strategy: FireStrategy::None, min_distance: 0., bullet: Bullet { image: "weapon/invisible-bullet.png", dim: Vec2::new(20., 40.), price: Resources { gasoline: 5., ..default() }, speed: 1.2 * MAP_SIZE.y, movement: Movement::Straight, impact: Impact::Piercing { damage: Damage { ground: 5., air: 5., penetration: 5., }, hits: HashSet::new(), }, max_distance: 0., // Is set by self.update() distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 150., ..default() }, }, upgrade2: Upgrade { description: "Increase the penetration.", texture: "penetration", price: Resources { technology: 100., ..default() }, }, }, machine_gun: Weapon { name: WeaponName::MachineGun, image: "weapon/machine-gun.png", description:"\ Medium range, low damage, single-target fire weapon. The machine gun can \ change its firing frequency.", dim: Vec2::new(70., 70.), maximum: MAX_SPOTS, rotation_speed: 7., target: None, price: Resources { materials: 100., ..default() }, fire_animation: FireAnimation { atlas: "single-flash", scale: Vec3::splat(0.5), duration: 0.1, }, n_bullets: 1, fire_timer: None, fire_strategy: FireStrategy::None, min_distance: 0., bullet: Bullet { image: "weapon/bullet.png", dim: Vec2::new(25., 7.), price: Resources { bullets: 1., ..default() }, speed: 0.8 * MAP_SIZE.y, movement: Movement::Straight, impact: Impact::SingleTarget(Damage { ground: 5., air: 5., penetration: 0., }), max_distance: 0.7 * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 50., ..default() }, }, upgrade2: Upgrade { description: "Increase the fire range.", texture: "range", price: Resources { technology: 30., ..default() }, }, }, missile_launcher: Weapon { name: WeaponName::MissileLauncher, image: "weapon/missile-launcher.png", description:"\ Medium range and damage weapon that fires multiple explosive shells. Very \ effective to deal with large number of enemies. The missile launcher shoots \ homing shells, always targeting the strongest enemies. It can't shoot enemies \ that are too close.", dim: Vec2::new(90., 90.), maximum: 2, rotation_speed: 5., target: None, price: Resources { materials: 1200., ..default() }, fire_animation: FireAnimation { atlas: "wide-flash", scale: Vec3::splat(0.7), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(3., TimerMode::Once)), fire_strategy: FireStrategy::None, min_distance: 0.15 * MAP_SIZE.y, bullet: Bullet { image: "weapon/grenade.png", dim: Vec2::new(20., 6.), price: Resources { bullets: 50., ..default() }, speed: 0.6 * MAP_SIZE.y, movement: Movement::Homing(Entity::from_raw(0)), // Set at spawn impact: Impact::Explosion(Explosion { radius: 0.1 * MAP_SIZE.y, damage: Damage { ground: 30., air: 30., penetration: 5., }, ..default() }), max_distance: 1.8 * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 1000., ..default() }, }, upgrade2: Upgrade { description: "Increase the explosion radius.", texture: "explosion", price: Resources { technology: 1000., ..default() }, }, }, mortar: Weapon { name: WeaponName::Mortar, image: "weapon/mortar.png", description:"\ Long range weapon that fires explosive shells at the highest enemy density \ location. The mortar has two explosive types to choose from: light (medium \ damage and radius) and heavy (high damage and radius, but costs more and does \ damage to structures). It can't shoot enemies that are too close.", dim: Vec2::new(70., 70.), maximum: MAX_SPOTS, rotation_speed: 5., target: None, price: Resources { materials: 400., ..default() }, fire_animation: FireAnimation { atlas: "wide-flash", scale: Vec3::splat(0.5), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(3., TimerMode::Once)), fire_strategy: FireStrategy::None, min_distance: 0.2 * MAP_SIZE.y, bullet: Bullet { image: "weapon/grenade.png", dim: Vec2::new(25., 10.), price: Resources { bullets: 35., ..default() }, speed: 0.6 * MAP_SIZE.y, movement: Movement::Location(Vec3::splat(0.)), // Set at spawn impact: Impact::Explosion(Explosion { radius: 0.15 * MAP_SIZE.y, damage: Damage { ground: 50., air: 50., penetration: 0., }, ..default() }), max_distance: 1.8 * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 200., ..default() }, }, upgrade2: Upgrade { description: "Increase the number of shells fired.", texture: "targets", price: Resources { technology: 300., ..default() }, }, }, turret: Weapon { name: WeaponName::Turret, image: "weapon/turret.png", description:"\ Long range, massive damage weapon that always shoots at the strongest enemy. \ Its bullets damage all enemies it passes through. The turret requires you to \ click on the button on the weapons panel to shoot. The weapon shoots with the \ power indicated in the bar next to the button. Although it can shoot at >20% \ power, its damage increases exponentially with the shooting power. The turret \ has high penetration bullets. Only one turret can be built.", dim: Vec2::new(90., 90.), maximum: 1, rotation_speed: 5., target: None, price: Resources { materials: 1000., ..default() }, fire_animation: FireAnimation { atlas: "triple-flash", scale: Vec3::splat(0.6), duration: 0.1, }, n_bullets: 1, fire_timer: Some(Timer::from_seconds(1., TimerMode::Once)), fire_strategy: FireStrategy::None, min_distance: 0., bullet: Bullet { image: "weapon/triple-bullet.png", dim: Vec2::new(25., 25.), price: Resources { bullets: 200., ..default() }, speed: 0.6 * MAP_SIZE.y, movement: Movement::PiercingHoming(Entity::from_raw(0)), // Set at spawn impact: Impact::Piercing { // Real damage set when firing damage: Damage { ground: 50., air: 50., penetration: 0., }, hits: HashSet::new(), }, max_distance: 3. * MAP_SIZE.y, distance: 0., }, upgrade1: Upgrade { description: "Increase the damage.", texture: "damage", price: Resources { technology: 500., ..default() }, }, upgrade2: Upgrade { description: "Increase the power-up speed.", texture: "reload", price: Resources { technology: 500., ..default() }, }, }, mine: Bullet { image: "weapon/mine.png", dim: Vec2::new(30., 20.), price: Resources { bullets: 25., gasoline: 25., ..default() }, speed: 0., movement: Movement::Straight, impact: Impact::Explosion(Explosion { interval: 0.02, radius: 0.1 * MAP_SIZE.y, damage: Damage { ground: 50., air: 0., penetration: 20., }, ..default() }), max_distance: f32::MAX, distance: 0., }, bomb: Bullet { image: "weapon/bomb.png", dim: Vec2::new(30., 15.), price: Resources { bullets: 250., gasoline: 250., ..default() }, speed: 0.4 * MAP_SIZE.y, movement: Movement::Location(Vec3::splat(0.)), // Set at spawn impact: Impact::Explosion(Explosion { interval: 0.05, radius: 0.35 * MAP_SIZE.y, damage: Damage { ground: 80., air: 80., penetration: 20., }, ..default() }), max_distance: f32::MAX, distance: 0., }, nuke: Bullet { image: "weapon/nuke.png", dim: Vec2::new(25., 10.), price: Resources { bullets: 2500., gasoline: 2500., ..default() }, speed: 0.2 * MAP_SIZE.y, movement: Movement::Location(Vec3::new( -WEAPONS_PANEL_SIZE.x * 0.5, SIZE.y * 0.5 - MAP_SIZE.y * 0.5, EXPLOSION_Z, )), impact: Impact::Explosion(Explosion { interval: 0.05, radius: 1.5 * MAP_SIZE.y, damage: Damage { ground: 100_000., air: 100_000., penetration: 100_000., }, ..default() }), max_distance: f32::MAX, distance: 0., }, } } }
0
0.935756
1
0.935756
game-dev
MEDIA
0.993091
game-dev
0.909128
1
0.909128
TheAnswer/Core3
1,329
MMOCoreORB/src/server/zone/objects/creature/commands/RequestResourceWeightsBatchCommand.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef REQUESTRESOURCEWEIGHTSBATCHCOMMAND_H_ #define REQUESTRESOURCEWEIGHTSBATCHCOMMAND_H_ #include "server/zone/managers/crafting/CraftingManager.h" class RequestResourceWeightsBatchCommand : public QueueCommand { public: RequestResourceWeightsBatchCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) return INVALIDSTATE; if (!checkInvalidLocomotions(creature)) return INVALIDLOCOMOTION; if (!creature->isPlayerCreature()) return GENERALERROR; ManagedReference<CraftingManager* > craftingManager = creature->getZoneServer()->getCraftingManager(); if (craftingManager == nullptr) return GENERALERROR; StringTokenizer tokenizer(arguments.toString()); String value; uint32 schematicID; while(tokenizer.hasMoreTokens()) { tokenizer.getStringToken(value); try { schematicID = Integer::valueOf(value); craftingManager->sendResourceWeightsTo(creature, schematicID); } catch(Exception& e) { warning("Invalid draft slot request: " + value); } } return SUCCESS; } }; #endif //REQUESTRESOURCEWEIGHTSBATCHCOMMAND_H_
0
0.939625
1
0.939625
game-dev
MEDIA
0.9437
game-dev
0.963148
1
0.963148
BoundaryML/baml
9,335
engine/language_client_typescript/src/types/type_builder.rs
use std::{collections::BTreeMap, ops::Deref}; // This file provides the native bindings between our Rust implementation and TypeScript // We use NAPI-RS to expose Rust functionality to JavaScript/TypeScript use baml_runtime::type_builder::{self, WithMeta}; use baml_types::{ir_type::UnionConstructor, BamlValue}; use napi::{ bindgen_prelude::{Array, JavaScriptClassExt}, Env, }; use napi_derive::napi; // Create TypeScript-compatible wrappers for our Rust types // These macros generate the necessary code for TypeScript interop crate::lang_wrapper!(TypeBuilder, type_builder::TypeBuilder); // Thread-safe wrapper for EnumBuilder with name tracking // The sync_thread_safe attribute ensures safe concurrent access from TypeScript crate::lang_wrapper!(EnumBuilder, type_builder::EnumBuilder, sync_thread_safe, name: String); // Thread-safe wrapper for ClassBuilder with name tracking // Enables safe TypeScript interop with class definitions crate::lang_wrapper!(ClassBuilder, type_builder::ClassBuilder, sync_thread_safe, name: String); // Thread-safe wrapper for EnumValueBuilder // Ensures enum value definitions can be safely accessed across threads crate::lang_wrapper!( EnumValueBuilder, type_builder::EnumValueBuilder, sync_thread_safe ); // Thread-safe wrapper for ClassPropertyBuilder // Enables concurrent access to class property definitions crate::lang_wrapper!( ClassPropertyBuilder, type_builder::ClassPropertyBuilder, sync_thread_safe ); // Thread-safe wrapper for FieldType // Core type system representation with thread-safety guarantees crate::lang_wrapper!(FieldType, baml_types::TypeIR, sync_thread_safe); // Implement Default for TypeBuilder to allow easy instantiation // This enables idiomatic Rust usage while maintaining TypeScript compatibility impl Default for TypeBuilder { fn default() -> Self { Self::new() } } // note: you may notice a rust-analyzer warning in vs code when working with this file. // the warning "did not find struct napitypebuilder parsed before expand #[napi] for impl" // is a known false positive that occurs due to how rust-analyzer processes macro state. // // don't worry - the code compiles and works correctly! the warning is yet to be addressed by napi maintainers. // // if you'd like to hide this warning in vs code, you can add this to your settings.json: // "rust-analyzer.diagnostics.disabled": ["macro-error"] // // ref: // https://github.com/napi-rs/napi-rs/issues/1630 #[napi] impl TypeBuilder { #[napi(constructor)] pub fn new() -> Self { let tb = type_builder::TypeBuilder::new(); tb.into() } #[napi] pub fn reset(&self) { self.inner.reset(); } #[napi] pub fn get_enum(&self, name: String) -> EnumBuilder { EnumBuilder { inner: self.inner.upsert_enum(&name), name, } } #[napi] pub fn get_class(&self, name: String) -> ClassBuilder { ClassBuilder { inner: self.inner.upsert_class(&name), name, } } #[napi] pub fn list(&self, inner: &FieldType) -> FieldType { inner.inner.lock().unwrap().clone().as_list().into() } #[napi] pub fn optional(&self, inner: &FieldType) -> FieldType { inner.inner.lock().unwrap().clone().as_optional().into() } #[napi] pub fn string(&self) -> FieldType { baml_types::TypeIR::string().into() } #[napi] pub fn literal_string(&self, value: String) -> FieldType { baml_types::TypeIR::literal_string(value).into() } #[napi] pub fn literal_int(&self, value: i64) -> FieldType { baml_types::TypeIR::literal_int(value).into() } #[napi] pub fn literal_bool(&self, value: bool) -> FieldType { baml_types::TypeIR::literal_bool(value).into() } #[napi] pub fn int(&self) -> FieldType { baml_types::TypeIR::int().into() } #[napi] pub fn float(&self) -> FieldType { baml_types::TypeIR::float().into() } #[napi] pub fn bool(&self) -> FieldType { baml_types::TypeIR::bool().into() } #[napi] pub fn null(&self) -> FieldType { baml_types::TypeIR::null().into() } #[napi] pub fn map(&self, key: &FieldType, value: &FieldType) -> FieldType { baml_types::TypeIR::map( key.inner.lock().unwrap().clone(), value.inner.lock().unwrap().clone(), ) .into() } #[napi] pub fn union(&self, types: Vec<&FieldType>) -> FieldType { baml_types::TypeIR::union( types .iter() .map(|t| t.inner.lock().unwrap().clone()) .collect(), ) .into() } #[napi] pub fn add_baml(&self, baml: String, rt: &crate::BamlRuntime) -> napi::Result<()> { self.inner .add_baml(&baml, rt.inner.internal()) .map_err(crate::errors::from_anyhow_error) } #[napi] pub fn to_string(&self) -> String { self.inner.to_string() } } #[napi] impl FieldType { #[napi] pub fn list(&self) -> FieldType { self.inner.lock().unwrap().clone().as_list().into() } #[napi] pub fn optional(&self) -> FieldType { self.inner.lock().unwrap().clone().as_optional().into() } #[napi] pub fn equals(&self, other: &FieldType) -> bool { self.inner.lock().unwrap().deref() == other.inner.lock().unwrap().deref() } } #[napi] impl EnumBuilder { #[napi] pub fn value(&self, name: String) -> EnumValueBuilder { self.inner.lock().unwrap().upsert_value(&name).into() } #[napi] pub fn alias(&self, alias: Option<String>) -> Self { self.inner.lock().unwrap().with_meta( "alias", alias.map_or(baml_types::BamlValue::Null, BamlValue::String), ); self.inner.clone().into() } #[napi] pub fn field(&self) -> FieldType { baml_types::TypeIR::r#enum(&self.name).into() } } #[napi] impl EnumValueBuilder { #[napi] pub fn alias(&self, alias: Option<String>) -> Self { self.inner.lock().unwrap().with_meta( "alias", alias.map_or(baml_types::BamlValue::Null, BamlValue::String), ); self.inner.clone().into() } #[napi] pub fn skip(&self, skip: Option<bool>) -> Self { self.inner .lock() .unwrap() .with_meta("skip", skip.map_or(BamlValue::Null, BamlValue::Bool)); self.inner.clone().into() } #[napi] pub fn description(&self, description: Option<String>) -> Self { self.inner.lock().unwrap().with_meta( "description", description.map_or(baml_types::BamlValue::Null, BamlValue::String), ); self.inner.clone().into() } } #[napi] impl ClassBuilder { #[napi] pub fn list_properties<'e>(&self, env: &'e Env) -> napi::Result<Array<'e>> { let properties = self .inner .lock() .unwrap() .list_properties_key_value() .into_iter() .map(|(name, prop)| (name, ClassPropertyBuilder::from(prop))); let mut js_array = env.create_array(properties.len() as u32)?; for (i, (name, prop_builder)) in properties.enumerate() { let mut tuple = env.create_array(2)?; tuple.set(0, env.create_string(&name)?)?; tuple.set(1, prop_builder.into_instance(env)?)?; js_array.set(i as u32, tuple)?; } Ok(js_array) } #[napi] pub fn remove_property(&self, name: String) { self.inner.lock().unwrap().remove_property(&name); } #[napi] pub fn reset(&self) { self.inner.lock().unwrap().reset(); } #[napi] pub fn field(&self) -> FieldType { baml_types::TypeIR::class(&self.name).into() } #[napi] pub fn property(&self, name: String) -> ClassPropertyBuilder { self.inner.lock().unwrap().upsert_property(&name).into() } } #[napi] impl ClassPropertyBuilder { #[napi] pub fn set_type(&self, field_type: &FieldType) -> Self { self.inner .lock() .unwrap() .set_type(field_type.inner.lock().unwrap().clone()); self.inner.clone().into() } #[napi] pub fn get_type(&self) -> napi::Result<FieldType> { self.inner .lock() .unwrap() .r#type() .map(FieldType::from) .ok_or_else(|| crate::errors::from_anyhow_error(anyhow::anyhow!( "attempted to read a property that has no defined type, this is likely an internal bug" ))) } #[napi] pub fn alias(&self, alias: Option<String>) -> Self { self.inner.lock().unwrap().with_meta( "alias", alias.map_or(baml_types::BamlValue::Null, BamlValue::String), ); self.inner.clone().into() } #[napi] pub fn description(&self, description: Option<String>) -> Self { self.inner.lock().unwrap().with_meta( "description", description.map_or(baml_types::BamlValue::Null, BamlValue::String), ); self.inner.clone().into() } }
0
0.632397
1
0.632397
game-dev
MEDIA
0.247867
game-dev
0.738421
1
0.738421
FishRPG/FishRPG-public
1,588
RPG-Core/src/main/java/me/acraftingfish/minecraftrpg/common/armor/ArmorSlotInfo.java
package me.acraftingfish.minecraftrpg.common.armor; import com.marcusslover.plus.lib.item.Item; import lombok.AllArgsConstructor; import lombok.Data; import me.acraftingfish.minecraftrpg.common.item.xitem.GameItem; import me.acraftingfish.minecraftrpg.utils.ItemUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Optional; @Data public class ArmorSlotInfo { private @Nullable Item item; private @Nullable GameItem gameItem; private boolean dirty = false; public ArmorSlotInfo(Item item, GameItem gameItem){ this.item = item; this.gameItem = gameItem; } public void set(@Nullable GameItem gameItem){ this.dirty = true; if(gameItem == null){ this.item = null; this.gameItem = null; return; } set(gameItem.item(), gameItem); } public void set(@Nullable Item item){ this.dirty = true; if(item == null || !item.isValid()) { this.item = null; this.gameItem = null; return; } this.item = item; this.gameItem = ItemUtil.getItem(item); } private void set(@Nullable Item item, @Nullable GameItem gameItem){ this.dirty = true; if(item == null || !item.isValid()) { this.item = null; this.gameItem = null; return; } this.item = item; this.gameItem = gameItem; } public void clear() { this.dirty = true; set(null, null); } }
0
0.763358
1
0.763358
game-dev
MEDIA
0.892409
game-dev
0.691365
1
0.691365
SmashPhil/Vehicle-Framework
24,171
Source/Vehicles/Graphics/ITab/ITab_Vehicle_Upgrades.cs
using System.Collections.Generic; using System.Linq; using RimWorld; using SmashTools; using UnityEngine; using Vehicles.Rendering; using Verse; using Verse.Sound; namespace Vehicles; [StaticConstructorOnStartup] public class ITab_Vehicle_Upgrades : ITab { public const float UpgradeNodeDim = 40; //public const float UpgradeNodesX = 20; //public const float UpgradeNodesY = 11; public const float TopPadding = 20; public const float EdgePadding = 5f; public const float SideDisplayedOffset = 40f; public const float BottomDisplayedOffset = 20f; public const float TotalIconSizeScalar = 6000f; private const float ScreenWidth = 880f; private const float ScreenHeight = 520f; private const float InfoScreenWidth = 375; private const float InfoScreenHeight = 150; private const float InfoPanelRowHeight = 20f; private const float InfoPanelMoreDetailButtonSize = 24; private const float InfoPanelArrowPointerSize = 45; private const float OverlayGraphicHeight = (InfoScreenWidth - InfoPanelArrowPointerSize) / 2; public static readonly Vector2 GridSpacing = new(20, 20); public static readonly Vector2 GridOrigin = new(30, 30); internal static readonly int MaxLinesAcross = Mathf.FloorToInt(ScreenWidth / GridSpacing.x) - 2; private static readonly int MaxLinesDown = Mathf.FloorToInt(ScreenHeight / GridSpacing.y) - 3; public static readonly List<string> ReplaceNodes = []; private static readonly Color NotUpgradedColor = new(0, 0, 0, 0.3f); private static readonly Color UpgradingColor = new(1, 0.75f, 0, 1); private static readonly Color DisabledColor = new(0.25f, 0.25f, 0.25f, 1); private static readonly Color DisabledLineColor = new(0.3f, 0.3f, 0.3f, 1); private static readonly Color GridLineColor = new(0.3f, 0.3f, 0.3f, 1); private static readonly Color EffectColorPositive = new(0.1f, 1f, 0.1f); private static readonly Color EffectColorNegative = new(0.8f, 0.4f, 0.4f); private static readonly Color EffectColorNeutral = new(0.5f, 0.5f, 0.5f, 0.75f); private VehiclePawn openedFor; private UpgradeNode selectedNode; private UpgradeNode highlightedNode; private readonly List<UpgradeTextEntry> textEntries = []; private float textEntryHeight; private readonly List<VehicleTurret> renderTurrets = []; private readonly List<string> excludeTurrets = []; private bool showDetails; private UpgradeNode InfoNode => selectedNode ?? highlightedNode; private UpgradeNode SelectedNode { get { return selectedNode; } set { if (selectedNode != value) { ClearTurretRenderers(selectedNode); selectedNode = value; openedFor = Vehicle; if (selectedNode != null) { RecacheTextEntries(); RecacheTurretRenderers(); } } } } public ITab_Vehicle_Upgrades() { size = new Vector2(ScreenWidth, ScreenHeight); labelKey = "VF_TabUpgrades"; } private VehiclePawn Vehicle { get { if (SelPawn is VehiclePawn { CompUpgradeTree: not null } vehicle) { if (vehicle != openedFor) { openedFor = vehicle; SelectedNode = null; } return vehicle; } CloseTab(); return null; } } public override void OnOpen() { base.OnOpen(); SelectedNode = null; highlightedNode = null; } protected override void CloseTab() { base.CloseTab(); openedFor = null; } private void RecacheTextEntries() { textEntries.Clear(); textEntryHeight = 0; /* if (SelectedNode != null && SelectedNode.upgradeExplanation != null) { textEntryHeight = Text.CalcHeight(SelectedNode.upgradeExplanation, InfoScreenWidth - 10); } else { foreach (Upgrade upgrade in InfoNode.upgrades) { foreach (UpgradeTextEntry textEntry in upgrade.UpgradeDescription(Vehicle)) { textEntries.Add(textEntry); } } textEntryHeight = textEntries.Count * Text.LineHeightOf(GameFont.Small); } */ } private void RecacheTurretRenderers() { if (SelectedNode.upgrades.NullOrEmpty()) return; foreach (Upgrade upgrade in InfoNode.upgrades) { if (upgrade is not TurretUpgrade turretUpgrade) continue; if (!turretUpgrade.turrets.NullOrEmpty()) { foreach (VehicleTurret turret in turretUpgrade.turrets) { turret.ResolveGraphics(Vehicle.VehicleDef, forceRegen: true); renderTurrets.Add(turret); } } if (!turretUpgrade.removeTurrets.NullOrEmpty()) { excludeTurrets.AddRange(turretUpgrade.removeTurrets); } } } private void ClearTurretRenderers(UpgradeNode upgradeNode) { if (upgradeNode != null && !upgradeNode.upgrades.NullOrEmpty()) { foreach (Upgrade upgrade in InfoNode.upgrades) { if (upgrade is TurretUpgrade turretUpgrade) { if (!turretUpgrade.turrets.NullOrEmpty()) { foreach (VehicleTurret turret in turretUpgrade.turrets) { turret.OnDestroy(); } } } } } renderTurrets.Clear(); excludeTurrets.Clear(); } private IEnumerable<UpgradeNode> GetDisablerNodes(UpgradeNode upgradeNode) { if (!upgradeNode.disableIfUpgradeNodeEnabled.NullOrEmpty()) { UpgradeNode disableNode = Vehicle.CompUpgradeTree.Props.def.GetNode(upgradeNode.disableIfUpgradeNodeEnabled); if (disableNode != null) { yield return disableNode; } } if (!upgradeNode.disableIfUpgradeNodesEnabled.NullOrEmpty()) { foreach (string key in upgradeNode.disableIfUpgradeNodesEnabled) { UpgradeNode disableNode = Vehicle.CompUpgradeTree.Props.def.GetNode(key); if (disableNode != null) { yield return disableNode; } } } } private Vector2 GridCoordinateToScreenPos(IntVec2 coord) { float x = GridOrigin.x + (GridSpacing.x * coord.x) - (GridSpacing.x / 2); float y = GridOrigin.y + (GridSpacing.y * coord.z) - (GridSpacing.y / 2) + TopPadding; return new Vector2(x, y); } private Vector2 GridCoordinateToScreenPosAdjusted(IntVec2 coord, Vector2 drawSize) { float x = GridOrigin.x + (GridSpacing.x * coord.x) - (GridSpacing.x / 2); float y = GridOrigin.y + (GridSpacing.y * coord.z) - (GridSpacing.y / 2) + TopPadding; float offsetX = drawSize.x / 2; float offsetY = drawSize.y / 2; return new Vector2(x - offsetX, y - offsetY); } protected override void FillTab() { //May occur if sub-window is open while selected entity changes inbetween frames if (Vehicle == null) { return; } Rect rect = new(0f, TopPadding, size.x, size.y - TopPadding); Rect innerRect = rect.ContractedBy(5f); if (DebugSettings.ShowDevGizmos) { string debugGridLabel = "VF_DevMode_DebugDrawUpgradeNodeGrid".Translate(); Vector2 debugGridLabelSize = Text.CalcSize(debugGridLabel); Rect devGridCheckboxRect = new(rect.xMax - 80 - debugGridLabelSize.x, 0, debugGridLabelSize.x + 30, debugGridLabelSize.y); bool showGrid = VehicleMod.settings.debug.debugDrawNodeGrid; Widgets.CheckboxLabeled(devGridCheckboxRect, debugGridLabel, ref showGrid); VehicleMod.settings.debug.debugDrawNodeGrid = showGrid; } highlightedNode = null; //DrawButtons(); DrawGrid(innerRect); Rect labelRect = new(innerRect.x, 5, innerRect.width - 16f, 20f); Widgets.Label(labelRect, Vehicle.Label); if (!VehicleMod.settings.debug.debugDrawNodeGrid) { using var lineColor = new TextBlock(GridLineColor); Widgets.DrawLineHorizontal(innerRect.x, innerRect.y, innerRect.width); Widgets.DrawLineHorizontal(innerRect.x, innerRect.yMax, innerRect.width); Widgets.DrawLineVertical(innerRect.x, innerRect.y, innerRect.height); Widgets.DrawLineVertical(innerRect.xMax, innerRect.y, innerRect.height); } } private void DrawButtons(Rect rect) { if (Vehicle.CompUpgradeTree.NodeUnlocking == SelectedNode) { if (Widgets.ButtonText(rect, "CancelButton".Translate())) { Vehicle.CompUpgradeTree.ClearUpgrade(); SelectedNode = null; } } else if (Vehicle.CompUpgradeTree.NodeUnlocked(SelectedNode) && Vehicle.CompUpgradeTree.LastNodeUnlocked(SelectedNode)) { if (Widgets.ButtonText(rect, "VF_RemoveUpgrade".Translate())) { SoundDefOf.Click.PlayOneShotOnCamera(Vehicle.Map); if (DebugSettings.godMode) { Vehicle.CompUpgradeTree.ResetUnlock(SelectedNode); } else { Vehicle.CompUpgradeTree.RemoveUnlock(SelectedNode); } SelectedNode = null; } } else if (Widgets.ButtonText(rect, "VF_Upgrade".Translate()) && !Vehicle.CompUpgradeTree.NodeUnlocked(SelectedNode)) { if (Vehicle.CompUpgradeTree.Disabled(SelectedNode)) { Messages.Message("VF_DisabledFromOtherNode".Translate(), MessageTypeDefOf.RejectInput, false); } else if (Vehicle.CompUpgradeTree.PrerequisitesMet(SelectedNode)) { SoundDefOf.ExecuteTrade.PlayOneShotOnCamera(Vehicle.Map); if (DebugSettings.godMode) { Vehicle.CompUpgradeTree.FinishUnlock(SelectedNode); SoundDefOf.Building_Complete.PlayOneShot(Vehicle); } else { Vehicle.CompUpgradeTree.StartUnlock(SelectedNode); } SelectedNode = null; } else { Messages.Message("VF_MissingPrerequisiteUpgrade".Translate(), MessageTypeDefOf.RejectInput, false); } } } private static void DrawBackgroundGridTop() { for (int i = 0; i <= MaxLinesAcross; i++) { using TextBlock lineColor = new(GridLineColor); Widgets.DrawLineVertical(GridSpacing.x + GridSpacing.x * i, TopPadding + GridSpacing.y, MaxLinesDown * GridSpacing.y); if (i % 5 == 0) { GUI.color = Color.white; Widgets.Label( new Rect(GridSpacing.x + GridSpacing.x * i - 5f, TopPadding, GridSpacing.x, GridSpacing.y), i.ToString()); } } } private static void DrawBackgroundGridLeft() { for (int i = 0; i <= MaxLinesDown; i++) { using TextBlock lineColor = new(GridLineColor); Widgets.DrawLineHorizontal(GridSpacing.x, TopPadding + GridSpacing.y * (i + 1), MaxLinesAcross * GridSpacing.x); if (i % 5 == 0) { GUI.color = Color.white; Widgets.Label( new Rect(GridSpacing.x - 20f, TopPadding + GridSpacing.y * (i + 1) - GridSpacing.y / 2, GridSpacing.x, GridSpacing.y), i.ToString()); } } } private void DrawNodeSelection() { if (SelectedNode == null || Vehicle.CompUpgradeTree.Upgrading) return; Vector2 selectedRectPos = GridCoordinateToScreenPosAdjusted(SelectedNode.GridCoordinate, SelectedNode.drawSize); Rect selectedRect = new(selectedRectPos, SelectedNode.drawSize); selectedRect = selectedRect.ExpandedBy(2f); GUI.DrawTexture(selectedRect, BaseContent.WhiteTex); } private void DrawPrerequisites() { using TextBlock colorBlock = new(Color.white); foreach (UpgradeNode upgradeNode in Vehicle.CompUpgradeTree.Props.def.nodes) { if (upgradeNode.prerequisiteNodes.NullOrEmpty() || upgradeNode.hidden) continue; foreach (UpgradeNode prerequisite in Vehicle.CompUpgradeTree.Props.def.nodes.FindAll(prereqNode => !prereqNode.hidden && upgradeNode.prerequisiteNodes.Contains(prereqNode.key))) { Vector2 start = GridCoordinateToScreenPos(upgradeNode.GridCoordinate); Vector2 end = GridCoordinateToScreenPos(prerequisite.GridCoordinate); Color color = Vehicle.CompUpgradeTree.NodeUnlocked(upgradeNode) ? Color.white : DisabledLineColor; foreach (UpgradeNode disabledNode in GetDisablerNodes(upgradeNode)) { Rect prerequisiteRect = new(GridCoordinateToScreenPosAdjusted(disabledNode.GridCoordinate, disabledNode.drawSize), prerequisite.drawSize); if (!Vehicle.CompUpgradeTree.Upgrading && Mouse.IsOver(prerequisiteRect)) { color = Color.red; } } Widgets.DrawLine(start, end, color, 2f); } } } private void DrawUpgradeNodes(Rect rect) { Rect detailRect = InfoNode != null ? GetDetailRect(rect) : Rect.zero; foreach (UpgradeNode upgradeNode in Vehicle.CompUpgradeTree.Props.def.nodes) { if (upgradeNode.hidden) continue; using TextBlock colorBlock = new(Color.white); Vector2 upgradeRectPos = GridCoordinateToScreenPosAdjusted(upgradeNode.GridCoordinate, upgradeNode.drawSize); Rect upgradeRect = new(upgradeRectPos, upgradeNode.drawSize); bool colored = false; if (Vehicle.CompUpgradeTree.Disabled(upgradeNode) || !Vehicle.CompUpgradeTree.PrerequisitesMet(upgradeNode)) { colored = true; GUI.color = DisabledColor; } Widgets.DrawTextureFitted(upgradeRect, Command.BGTex, 1); Widgets.DrawTextureFitted(upgradeRect, upgradeNode.UpgradeImage, 1); DrawNodeCondition(upgradeRect, upgradeNode, colored); if (upgradeNode.displayLabel) { float textWidth = Text.CalcSize(upgradeNode.label).x; Rect nodeLabelRect = new(upgradeRect.x - (textWidth - upgradeRect.width) / 2, upgradeRect.y - 20f, 10f * upgradeNode.label.Length, 25f); Widgets.Label(nodeLabelRect, upgradeNode.label); } if (Mouse.IsOver(upgradeRect)) { highlightedNode = upgradeNode; if (Vehicle.CompUpgradeTree.PrerequisitesMet(upgradeNode) && !Vehicle.CompUpgradeTree.NodeUnlocked(upgradeNode)) { GUI.DrawTexture(upgradeRect, TexUI.HighlightTex); } } if (InfoNode != null && !Mouse.IsOver(detailRect) && Widgets.ButtonInvisible(upgradeRect)) { if (SelectedNode != upgradeNode) { SelectedNode = upgradeNode; SoundDefOf.Checkbox_TurnedOn.PlayOneShotOnCamera(); } else { SelectedNode = null; SoundDefOf.Checkbox_TurnedOff.PlayOneShotOnCamera(); } } } if (InfoNode != null) { Widgets.BeginGroup(detailRect); { DrawInfoPanel(detailRect.AtZero()); } Widgets.EndGroup(); } } private void DrawGrid(Rect rect) { if (DebugSettings.ShowDevGizmos && VehicleMod.settings.debug.debugDrawNodeGrid) { DrawBackgroundGridTop(); DrawBackgroundGridLeft(); } DrawNodeSelection(); DrawPrerequisites(); DrawUpgradeNodes(rect); } private Rect GetDetailRect(Rect rect, float padding = 5) { Vector2 upgradeRectPos = GridCoordinateToScreenPosAdjusted(InfoNode.GridCoordinate, InfoNode.drawSize); Rect upgradeRect = new(upgradeRectPos, InfoNode.drawSize); float ingredientsHeight = 0; if (!InfoNode.ingredients.NullOrEmpty()) { ingredientsHeight = InfoNode.ingredients.Count * InfoPanelRowHeight; } float detailWidth = InfoScreenWidth - padding * 2; using TextBlock textFont = new(GameFont.Medium); float labelHeight = Text.CalcHeight(InfoNode.label, detailWidth); Text.Font = GameFont.Small; float descriptionHeight = Text.CalcHeight(InfoNode.description, detailWidth); float totalCalculatedHeight = labelHeight + descriptionHeight + ingredientsHeight + 30 + padding; if (SelectedNode != null) { totalCalculatedHeight += 10; //5 padding from description to line, and line to bottom rect if (SelectedNode.HasGraphics) { totalCalculatedHeight += OverlayGraphicHeight; } if (!textEntries.NullOrEmpty()) { totalCalculatedHeight += textEntryHeight + 5; } } float windowRectX = upgradeRect.x + InfoNode.drawSize.x + padding; if (windowRectX + detailWidth > rect.xMax - padding) { windowRectX = upgradeRect.x - detailWidth - padding; windowRectX = Mathf.Clamp(windowRectX, rect.x + padding, rect.xMax - detailWidth - padding); } float maxInfoScreenHeight = Mathf.Max(InfoScreenHeight, totalCalculatedHeight); float windowRectY = upgradeRect.y + InfoNode.drawSize.y / 2 - maxInfoScreenHeight / 2; windowRectY = Mathf.Clamp(windowRectY, rect.y + padding, rect.yMax - maxInfoScreenHeight - padding); //if (windowRectY + maxInfoScreenHeight >= ScreenHeight) //{ // windowRectY -= maxInfoScreenHeight + padding * 2 + InfoNode.drawSize.y; //} return new Rect(windowRectX, windowRectY, detailWidth, maxInfoScreenHeight); } private void DrawInfoPanel(Rect rect, float padding = 5) { Widgets.DrawMenuSection(rect); Rect innerInfoRect = rect.ContractedBy(padding); using TextBlock textFont = new(GameFont.Medium); float labelHeight = Text.CalcHeight(InfoNode.label, innerInfoRect.width); Rect labelRect = new(innerInfoRect.x, innerInfoRect.y, innerInfoRect.width, labelHeight); Widgets.Label(labelRect, InfoNode.label); Text.Font = GameFont.Small; Rect costListRect = new(innerInfoRect.x, labelRect.yMax, innerInfoRect.width, innerInfoRect.height - labelRect.height); float costY = DrawCostItems(costListRect); Rect tempRect = costListRect; tempRect.height = costY; float descriptionHeight = Text.CalcHeight(InfoNode.description, innerInfoRect.width); Rect descriptionRect = new(innerInfoRect.x, costListRect.y + costY, innerInfoRect.width, descriptionHeight); Widgets.Label(descriptionRect, InfoNode.description); if (SelectedNode != null) { bool hasGraphics = SelectedNode.HasGraphics; bool showUpgradeList = !SelectedNode.upgrades.NullOrEmpty(); if (hasGraphics || showUpgradeList) { Widgets.DrawLineHorizontal(rect.x, descriptionRect.yMax + 5, rect.width, UIElements.MenuSectionBgBorderColor); } Rect textEntryRect = new(innerInfoRect.x, descriptionRect.yMax + 10, innerInfoRect.width, textEntryHeight); if (showUpgradeList) { //DrawUpgradeList(textEntryRect); } if (hasGraphics) { Rect overlayShowcaseRect = new(innerInfoRect.x, textEntryRect.yMax + 5, innerInfoRect.width, (innerInfoRect.width - InfoPanelArrowPointerSize) / 2); DrawVehicleGraphicComparison(overlayShowcaseRect); } Rect buttonRect = new(innerInfoRect.xMax - 125f, innerInfoRect.yMax - 30, 120, 30); DrawButtons(buttonRect); Rect tempButtonRect = buttonRect; tempButtonRect.width = innerInfoRect.width; } } private void DrawVehicleGraphicComparison(Rect rect) { Rect innerInfoRect = rect.ContractedBy(5); Rect vehicleOriginalRect = new(innerInfoRect.x, innerInfoRect.y, innerInfoRect.height, innerInfoRect.height); float arrowSize = InfoPanelArrowPointerSize; Rect arrowPointerRect = new(vehicleOriginalRect.xMax + 5, vehicleOriginalRect.y + vehicleOriginalRect.height / 2 - arrowSize / 2, arrowSize, arrowSize); Rect vehicleNewRect = new(arrowPointerRect.xMax + 5, vehicleOriginalRect.y, vehicleOriginalRect.width, vehicleOriginalRect.height); BlitRequest requestBefore = BlitRequest.For(Vehicle); VehicleGui.DrawVehicleOnGUI(vehicleOriginalRect, requestBefore); BlitRequest requestAfter = new(Vehicle); requestAfter.blitTargets.Add(Vehicle.VehicleDef); List<GraphicOverlay> extraOverlays = Vehicle.CompUpgradeTree.Props.TryGetOverlays(InfoNode); if (!extraOverlays.NullOrEmpty()) requestAfter.blitTargets.AddRange(extraOverlays); if (!Vehicle.DrawTracker.overlayRenderer.AllOverlaysListForReading.NullOrEmpty()) requestAfter.blitTargets.AddRange(Vehicle.DrawTracker.overlayRenderer .AllOverlaysListForReading); if (!renderTurrets.NullOrEmpty()) requestAfter.blitTargets.AddRange(renderTurrets); if (Vehicle.GetCachedComp<CompVehicleTurrets>() is { } compTurrets && !compTurrets.Turrets.NullOrEmpty()) { requestAfter.blitTargets.AddRange(compTurrets.Turrets.Where(turret => excludeTurrets is null || !excludeTurrets.Contains(turret.key))); } VehicleGui.DrawVehicleOnGUI(vehicleNewRect, requestAfter); Widgets.DrawTextureFitted(arrowPointerRect, TexData.TutorArrowRight, 1); } private void DrawSubIconsBar(Rect rect) { Rect subIconsRect = new(rect.xMax - InfoPanelMoreDetailButtonSize, rect.y, rect.width, InfoPanelMoreDetailButtonSize); Color baseColor = !showDetails ? Color.white : Color.green; Color mouseoverColor = !showDetails ? GenUI.MouseoverColor : new Color(0f, 0.5f, 0f); Rect buttonRect = new(subIconsRect.x, subIconsRect.y, InfoPanelMoreDetailButtonSize, InfoPanelMoreDetailButtonSize); if (!InfoNode.upgrades.NullOrEmpty()) { if (Widgets.ButtonImageFitted(buttonRect, TexButton.Info, baseColor, mouseoverColor)) { showDetails = !showDetails; if (showDetails) { SoundDefOf.TabOpen.PlayOneShotOnCamera(); } else { SoundDefOf.TabClose.PlayOneShotOnCamera(); } } buttonRect.x -= buttonRect.width; } } protected override void UpdateSize() { base.UpdateSize(); if (!Mathf.Approximately(size.x, ScreenWidth) || !Mathf.Approximately(size.y, ScreenHeight)) { size = new Vector2(ScreenWidth, ScreenHeight); } } private float DrawCostItems(Rect rect) { Rect costRect = rect; float currentY = 0; foreach (ThingDefCountClass thingDefCountClass in InfoNode.ingredients) { using TextBlock colorBlock = new(Color.white); Rect iconRect = new(costRect.x, costRect.y + currentY, InfoPanelRowHeight, InfoPanelRowHeight); GUI.DrawTexture(iconRect, thingDefCountClass.thingDef.uiIcon); string label = thingDefCountClass.thingDef.LabelCap; if (Vehicle.Map.resourceCounter.GetCount(thingDefCountClass.thingDef) < thingDefCountClass.count) { GUI.color = Color.red; } Rect itemCountRect = new(iconRect.x + 26, iconRect.y, 50, InfoPanelRowHeight); Widgets.Label(itemCountRect, $"{thingDefCountClass.count}"); Rect itemLabelRect = new(iconRect.x + 60, itemCountRect.y, costRect.width - itemCountRect.width - 25, InfoPanelRowHeight); Widgets.Label(itemLabelRect, label); currentY += InfoPanelRowHeight; } return currentY; } private void DrawUpgradeList(Rect rect) { if (InfoNode.upgradeExplanation != null) { Widgets.Label(rect, InfoNode.upgradeExplanation); } else if (!InfoNode.upgrades.NullOrEmpty()) { using TextBlock textBlock = new(GameFont.Small, TextAnchor.MiddleLeft); // Lists upgrade details if none is included foreach (Upgrade upgrade in InfoNode.upgrades) { foreach (UpgradeTextEntry textEntry in upgrade.UpgradeDescription(Vehicle)) { using TextBlock colorBlock = new(Color.white); float labelWidth = rect.width * 0.75f; float labelHeight = Text.CalcHeight(textEntry.label, labelWidth); float valueWidth = rect.width - labelWidth; float valueHeight = Text.CalcHeight(textEntry.description, valueWidth); float entryHeight = Mathf.Max(labelHeight, valueHeight); Rect leftRect = new(rect.x, rect.y, labelWidth, entryHeight); Widgets.Label(leftRect, textEntry.label); GUI.color = textEntry.effectType switch { UpgradeEffectType.Positive => EffectColorPositive, UpgradeEffectType.Negative => EffectColorNegative, UpgradeEffectType.Neutral => EffectColorNeutral, _ => Color.white, }; Rect rightRect = new(leftRect.xMax, rect.y, valueWidth, entryHeight); Widgets.Label(rightRect, textEntry.description); rect.y += entryHeight; } } } } private void DrawNodeCondition(Rect rect, UpgradeNode node, bool colored) { if (DisabledAndMouseOver()) { DrawBorder(rect, Color.red); } else if (Vehicle.CompUpgradeTree.NodeUnlocking == node) { DrawBorder(rect, UpgradingColor); } else if (Vehicle.CompUpgradeTree.NodeUnlocked(node)) { DrawBorder(rect, Color.white); } else if (!colored) { Widgets.DrawBoxSolid(rect, NotUpgradedColor); } else { DrawBorder(rect, NotUpgradedColor); } return; bool DisabledAndMouseOver() { foreach (UpgradeNode disabledNode in GetDisablerNodes(node)) { Rect prerequisiteRect = new( GridCoordinateToScreenPosAdjusted(disabledNode.GridCoordinate, disabledNode.drawSize), disabledNode.drawSize); if (!Vehicle.CompUpgradeTree.Upgrading && Mouse.IsOver(prerequisiteRect)) { return true; } } return false; } } private static void DrawBorder(Rect rect, Color color) { Vector2 topLeft = new(rect.x, rect.y); Vector2 topRight = new(rect.xMax, rect.y); Vector2 bottomLeft = new(rect.x, rect.yMax); Vector2 bottomRight = new(rect.xMax, rect.yMax); Vector2 leftTop = new(rect.x, rect.y + 2); Vector2 leftBottom = new(rect.x, rect.yMax + 2); Vector2 rightTop = new(rect.xMax, rect.y + 2); Vector2 rightBottom = new(rect.xMax, rect.yMax + 2); Widgets.DrawLine(topLeft, topRight, color, 1); Widgets.DrawLine(bottomLeft, bottomRight, color, 1); Widgets.DrawLine(leftTop, leftBottom, color, 1); Widgets.DrawLine(rightTop, rightBottom, color, 1); } }
0
0.937552
1
0.937552
game-dev
MEDIA
0.761983
game-dev
0.97614
1
0.97614
ImLegiitXD/Blossom
3,639
src/main/java/net/minecraft/realms/RealmsSliderButton.java
package net.minecraft.realms; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.MathHelper; public class RealmsSliderButton extends RealmsButton { public float value; public boolean sliding; private final float minValue; private final float maxValue; private int steps; public RealmsSliderButton(int p_i1056_1_, int p_i1056_2_, int p_i1056_3_, int p_i1056_4_, int p_i1056_5_, int p_i1056_6_) { this(p_i1056_1_, p_i1056_2_, p_i1056_3_, p_i1056_4_, p_i1056_6_, 0, 1.0F, (float)p_i1056_5_); } public RealmsSliderButton(int p_i1057_1_, int p_i1057_2_, int p_i1057_3_, int p_i1057_4_, int p_i1057_5_, int p_i1057_6_, float p_i1057_7_, float p_i1057_8_) { super(p_i1057_1_, p_i1057_2_, p_i1057_3_, p_i1057_4_, 20, ""); this.value = 1.0F; this.minValue = p_i1057_7_; this.maxValue = p_i1057_8_; this.value = this.toPct((float)p_i1057_6_); this.getProxy().displayString = this.getMessage(); } public String getMessage() { return ""; } public float toPct(float p_toPct_1_) { return MathHelper.clamp_float((this.clamp(p_toPct_1_) - this.minValue) / (this.maxValue - this.minValue), 0.0F, 1.0F); } public float toValue(float p_toValue_1_) { return this.clamp(this.minValue + (this.maxValue - this.minValue) * MathHelper.clamp_float(p_toValue_1_, 0.0F, 1.0F)); } public float clamp(float p_clamp_1_) { p_clamp_1_ = this.clampSteps(p_clamp_1_); return MathHelper.clamp_float(p_clamp_1_, this.minValue, this.maxValue); } protected float clampSteps(float p_clampSteps_1_) { if (this.steps > 0) { p_clampSteps_1_ = (float)(this.steps * Math.round(p_clampSteps_1_ / (float)this.steps)); } return p_clampSteps_1_; } public int getYImage(boolean p_getYImage_1_) { return 0; } public void renderBg(int p_renderBg_1_, int p_renderBg_2_) { if (this.getProxy().visible) { if (this.sliding) { this.value = (float)(p_renderBg_1_ - (this.getProxy().xPosition + 4)) / (float)(this.getProxy().getButtonWidth() - 8); this.value = MathHelper.clamp_float(this.value, 0.0F, 1.0F); float f = this.toValue(this.value); this.clicked(f); this.value = this.toPct(f); this.getProxy().displayString = this.getMessage(); } Minecraft.getMinecraft().getTextureManager().bindTexture(WIDGETS_LOCATION); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.blit(this.getProxy().xPosition + (int)(this.value * (float)(this.getProxy().getButtonWidth() - 8)), this.getProxy().yPosition, 0, 66, 4, 20); this.blit(this.getProxy().xPosition + (int)(this.value * (float)(this.getProxy().getButtonWidth() - 8)) + 4, this.getProxy().yPosition, 196, 66, 4, 20); } } public void clicked(int p_clicked_1_, int p_clicked_2_) { this.value = (float)(p_clicked_1_ - (this.getProxy().xPosition + 4)) / (float)(this.getProxy().getButtonWidth() - 8); this.value = MathHelper.clamp_float(this.value, 0.0F, 1.0F); this.clicked(this.toValue(this.value)); this.getProxy().displayString = this.getMessage(); this.sliding = true; } public void clicked(float p_clicked_1_) { } public void released(int p_released_1_, int p_released_2_) { this.sliding = false; } }
0
0.804288
1
0.804288
game-dev
MEDIA
0.340462
game-dev
0.873602
1
0.873602
PolarisSS13/Polaris
3,832
code/modules/events/carp_migration.dm
/datum/event/carp_migration startWhen = 0 // Start immediately announceWhen = 45 // Adjusted by setup endWhen = 75 // Adjusted by setup var/carp_cap = 10 var/list/spawned_carp = list() /datum/event/carp_migration/setup() announceWhen = rand(30, 60) // 1 to 2 minutes endWhen += severity * 25 carp_cap = 2 + 3 ** severity // No more than this many at once regardless of waves. (5, 11, 29) /datum/event/carp_migration/start() affecting_z -= global.using_map.sealed_levels // Space levels only please! ..() /datum/event/carp_migration/announce() var/announcement = "" if(severity == EVENT_LEVEL_MAJOR) announcement = "Massive migration of unknown biological entities has been detected near [location_name()], please stand-by." else announcement = "Unknown biological [spawned_carp.len == 1 ? "entity has" : "entities have"] been detected near [location_name()], please stand-by." command_announcement.Announce(announcement, "Lifesign Alert") /datum/event/carp_migration/tick() if(activeFor % 5 != 0) return // Only process every 10 seconds. if(count_spawned_carps() < carp_cap) spawn_fish(rand(1, severity * 2) - 1, severity, severity * 2) /datum/event/carp_migration/proc/spawn_fish(var/num_groups, var/group_size_min, var/group_size_max, var/dir) if(isnull(dir)) dir = (victim && prob(80)) ? victim.fore_dir : pick(GLOB.cardinal) // Check if any landmarks exist! var/list/spawn_locations = list() for(var/obj/effect/landmark/C in landmarks_list) if(C.name == "carpspawn" && (C.z in affecting_z)) spawn_locations.Add(C.loc) if(spawn_locations.len) // Okay we've got landmarks, lets use those! shuffle_inplace(spawn_locations) num_groups = min(num_groups, spawn_locations.len) for (var/i = 1, i <= num_groups, i++) var/group_size = rand(group_size_min, group_size_max) for (var/j = 0, j < group_size, j++) spawn_one_carp(spawn_locations[i]) return // Okay we did *not* have any landmarks, so lets do our best! var/i = 1 while (i <= num_groups) var/Z = pick(affecting_z) var/group_size = rand(group_size_min, group_size_max) var/turf/map_center = locate(round(world.maxx/2), round(world.maxy/2), Z) var/turf/group_center = pick_random_edge_turf(dir, Z, TRANSITIONEDGE + 2) var/list/turfs = getcircle(group_center, 2) for (var/j = 0, j < group_size, j++) var/mob/living/simple_mob/animal/M = spawn_one_carp(turfs[(i % turfs.len) + 1]) // Ray trace towards middle of the map to find where they can stop just outside of structure/ship. var/turf/target for(var/turf/T in getline(get_turf(M), map_center)) if(!T.is_space()) break; target = T if(target) M.ai_holder?.give_destination(target) // Ask carp to swim towards the middle of the map i++ // Spawn a single carp at given location. /datum/event/carp_migration/proc/spawn_one_carp(var/loc) var/mob/living/simple_mob/animal/M = new /mob/living/simple_mob/animal/space/carp/event(loc) GLOB.destroyed_event.register(M, src, .proc/on_carp_destruction) spawned_carp.Add(M) return M // Counts living carp spawned by this event. /datum/event/carp_migration/proc/count_spawned_carps() . = 0 for(var/I in spawned_carp) var/mob/living/simple_mob/animal/M = I if(!QDELETED(M) && M.stat != DEAD) . += 1 // If carp is bomphed, remove it from the list. /datum/event/carp_migration/proc/on_carp_destruction(var/mob/M) spawned_carp -= M GLOB.destroyed_event.unregister(M, src, .proc/on_carp_destruction) /datum/event/carp_migration/end() . = ..() // Clean up carp that died in space for some reason. spawn(0) for(var/mob/living/simple_mob/SM in spawned_carp) if(SM.stat == DEAD) var/turf/T = get_turf(SM) if(istype(T, /turf/space)) if(prob(75)) qdel(SM) CHECK_TICK // Overmap version /datum/event/carp_migration/overmap/announce() return
0
0.685582
1
0.685582
game-dev
MEDIA
0.911103
game-dev
0.937779
1
0.937779
RainwayApp/spitfire
5,259
include/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h
/* * Copyright (C) 2011, Google Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_NAVIGATOR_GAMEPAD_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_NAVIGATOR_GAMEPAD_H_ #include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/navigator.h" #include "third_party/blink/renderer/core/frame/platform_event_controller.h" #include "third_party/blink/renderer/modules/gamepad/gamepad.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace device { class Gamepad; } namespace blink { class Document; class GamepadDispatcher; class GamepadHapticActuator; class GamepadList; class Navigator; class MODULES_EXPORT NavigatorGamepad final : public GarbageCollected<NavigatorGamepad>, public Supplement<Navigator>, public DOMWindowClient, public PlatformEventController, public LocalDOMWindow::EventListenerObserver, public Gamepad::Client { USING_GARBAGE_COLLECTED_MIXIN(NavigatorGamepad); public: static const char kSupplementName[]; static NavigatorGamepad* From(Document&); static NavigatorGamepad& From(Navigator&); explicit NavigatorGamepad(Navigator&); ~NavigatorGamepad() override; static GamepadList* getGamepads(Navigator&); GamepadList* Gamepads(); void Trace(Visitor*) override; private: void SampleGamepads(); void DidRemoveGamepadEventListeners(); bool StartUpdatingIfAttached(); void SampleAndCompareGamepadState(); void DispatchGamepadEvent(const AtomicString&, Gamepad*); // PageVisibilityObserver void PageVisibilityChanged() override; // PlatformEventController void RegisterWithDispatcher() override; void UnregisterWithDispatcher() override; bool HasLastData() override; void DidUpdateData() override; // LocalDOMWindow::EventListenerObserver void DidAddEventListener(LocalDOMWindow*, const AtomicString&) override; void DidRemoveEventListener(LocalDOMWindow*, const AtomicString&) override; void DidRemoveAllEventListeners(LocalDOMWindow*) override; // Gamepad::Client GamepadHapticActuator* GetVibrationActuatorForGamepad( const Gamepad&) override; // A reference to the buffer containing the last-received gamepad state. May // be nullptr if no data has been received yet. Do not overwrite this buffer // as it may have already been returned to the page. Instead, write to // |gamepads_back_| and swap buffers. Member<GamepadList> gamepads_; // True if the buffer referenced by |gamepads_| has been exposed to the page. // When the buffer is not exposed, prefer to reuse it. bool is_gamepads_exposed_ = false; // A reference to the buffer for receiving new gamepad state. May be // overwritten. Member<GamepadList> gamepads_back_; HeapVector<Member<GamepadHapticActuator>> vibration_actuators_; // The timestamp for the navigationStart attribute. Gamepad timestamps are // reported relative to this value. base::TimeTicks navigation_start_; // The timestamp when gamepads were made available to the page. If no data has // been received from the hardware, the gamepad timestamp should be equal to // this value. base::TimeTicks gamepads_start_; // True if there is at least one listener for gamepad connection or // disconnection events. bool has_connection_event_listener_ = false; // True while processing gamepad events. bool processing_events_ = false; Member<GamepadDispatcher> gamepad_dispatcher_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_NAVIGATOR_GAMEPAD_H_
0
0.952472
1
0.952472
game-dev
MEDIA
0.810135
game-dev
0.680754
1
0.680754
Raytwo/Cobalt
11,023
crates/cobalt/src/audio/gamesound.rs
use unity::prelude::*; use engage::{combat::Character, gamedata::unit::Unit, gamesound::GameSound}; use crate::audio::{get_event_or_fallback, get_switchname_fallback, ORIGINAL_SUFFIX, PREVIOUS_LAST_PICK_VOICE, UNSAFE_CHARACTER_PTR}; pub struct GameSoundStatic { default_bank_name_array: &'static mut Il2CppArray<&'static mut Il2CppString>, } #[skyline::hook(offset = 0x2287c60)] pub fn load_default_sound_banks(method_info: OptionalMethod) { let static_fields = GameSound::class().get_static_fields_mut::<GameSoundStatic>(); let mut banks = static_fields.default_bank_name_array.to_vec(); let manager = mods::manager::Manager::get(); if let Ok(dir) = manager.get_directory("Data/StreamingAssets/Audio/GeneratedSoundBanks/Switch") { if let Ok(filepaths) = manager.get_files_in_directory_and_subdir(dir) { for path in filepaths.iter().filter(|path| path.extension() == Some("bnk")) { let filename = Il2CppString::new_static(path.file_stem().unwrap()); if !banks.contains(&filename) { println!("Added '{}' to the list", path); banks.insert(0, filename); } } } } static_fields.default_bank_name_array = Il2CppArray::from_slice(banks.as_mut_slice()).unwrap(); // static_fields.default_bank_name_array.iter().for_each(|bank| { // println!("Bank name: {}", bank.to_string()); // }); call_original!(method_info); } #[skyline::hook(offset = 0x2292270)] pub fn gamesound_personvoice( gameobject: &(), person_switch_name: &Il2CppString, engage_switch_name: Option<&Il2CppString>, event_name: &Il2CppString, character: &Character, method_info: OptionalMethod, ) { let event_string = event_name.to_string(); // println!( // "[PersonVoice]: Event name: {}, switch name: {}", // event_string, // person_switch_name // ); let character_ptr: *const Character = character as *const Character; unsafe { UNSAFE_CHARACTER_PTR = character_ptr; } if event_string.ends_with(ORIGINAL_SUFFIX) { // What does it mean to be an "original"? // "original" is an escape hatch for modded events that want to play a version that was defined in the "layer" above it. // // Let's say the event_string is `V_Critical_Original`. // // In the context of "Simple Event Replacement" (what's currently in the public release), it means that // 1. The person switch name is `PlayerF` // 2. The first time around, we found and played the modded event, `V_Critical_PlayerF`. // 3. However, the modded event's WEM file had a marker `CobaltEvent:V_Critical_Original`. Which // means that we should play the original event, `V_Critical`, instead. // So this time on entering the function, we will skip looking for the modded event and play the original event instead. // There is no need to mess with the person switch name in this case. // // In the context of "Costume Voice", SeasideDragon!PlayerF // // 1. The person switch name that was used last time was `SeasideDragon`. // 2. The first time around, we found and played the modded event, `V_Critical_SeasideDragon`. // 3. However, the modded event's WEM file had a marker `CobaltEvent:V_Critical_Original`. Which // means that we should play `V_Critical` again, but for the fallback person switch name of `PlayerF`. let stripped_name = event_string.trim_end_matches(ORIGINAL_SUFFIX); call_original!( gameobject, person_switch_name, engage_switch_name, stripped_name.into(), character, method_info ); return; } let parsed_event = get_event_or_fallback(Il2CppString::new(format!("{}_{}", event_string, person_switch_name))); let parsed_switchname = get_switchname_fallback(person_switch_name); if GameSound::is_event_loaded(parsed_event) { println!("[PersonVoice True]: Event name: {}, switch name: {}", parsed_event, parsed_switchname); call_original!(gameobject, parsed_switchname, engage_switch_name, parsed_event, character, method_info); } else { println!("[PersonVoice False]: Event name: {}, switch name: {}", event_string, parsed_switchname); call_original!(gameobject, parsed_switchname, engage_switch_name, event_name, character, method_info); } } #[skyline::hook(offset = 0x2292F90)] pub fn gamesound_ringcleaningvoice(person_switch_name: &Il2CppString, event_name: &Il2CppString, character: &Character, method_info: OptionalMethod) { let event_string = event_name.to_string(); let person_string = person_switch_name.to_string(); match event_string.contains("V_Ring") { true => { let modded_event = Il2CppString::new(format!("{}_{}", event_string, person_string)); println!("[GameSound] {} => {}_{}", event_string, event_string, person_string); match GameSound::is_event_loaded(modded_event) { true => call_original!(person_switch_name, modded_event, character, method_info), false => call_original!(person_switch_name, event_name, character, method_info), } }, false => call_original!(person_switch_name, event_name, character, method_info), } } // App.GameSound$$LoadSystemVoice 710228e850 App_GameSound_ResultLoad_o * App.GameSound$$LoadSystemVoice(System_String_o * personSwitchName, MethodInfo * method) 544 #[unity::hook("App", "GameSound", "LoadSystemVoice")] pub fn gamesound_loadsystemvoice(person_switch_name: &Il2CppString, method_info: OptionalMethod) -> &() { // match ParsedVoiceName::parse(person_switch_name) { // ParsedVoiceName::ModdedVoiceName(mod_voice) => { // println!( // "Loading fallback system voice for {}, which is {}", // person_switch_name, mod_voice.fallback_voice_name // ); // call_original!(mod_voice.fallback_voice_name, method_info) // }, // ParsedVoiceName::OriginalVoiceName(original_voice) => { // println!("Loading original system voice for {}", original_voice.voice_name); // call_original!(original_voice.voice_name, method_info) // }, // } let parsed_switchname = get_switchname_fallback(person_switch_name); call_original!(parsed_switchname, method_info) } // App.GameSound$$UnloadSystemVoice 710228ea70 void App.GameSound$$UnloadSystemVoice(System_String_o * personSwitchName, MethodInfo * method) 408 #[unity::hook("App", "GameSound", "UnloadSystemVoice")] pub fn gamesound_unloadsystemvoice(person_switch_name: &Il2CppString, method_info: OptionalMethod) -> &() { // match ParsedVoiceName::parse(person_switch_name) { // ParsedVoiceName::ModdedVoiceName(mod_voice) => { // println!( // "Unloading fallback system voice for {}, which is {}", // person_switch_name, mod_voice.fallback_voice_name // ); // call_original!(mod_voice.fallback_voice_name, method_info) // }, // ParsedVoiceName::OriginalVoiceName(original_voice) => { // println!("Unloading original system voice for {}", original_voice.voice_name); // call_original!(original_voice.voice_name, method_info) // }, // } let parsed_switchname = get_switchname_fallback(person_switch_name); call_original!(parsed_switchname, method_info) } #[skyline::hook(offset = 0x24F8DE0)] pub fn gamesound_setenumparam_gameobject( _this: &(), value_name: Option<&Il2CppString>, value: Option<&Il2CppString>, _game_object: &(), method_info: OptionalMethod, ) -> bool { let value_name_string = match value_name { Some(value_name_str) => value_name_str.to_string(), None => "None".to_string(), }; let value_string = match value { Some(value_str) => value_str.to_string(), None => "None".to_string(), }; // Try to not spam the console match value_name_string.as_str() { "Person" => { println!("[GameSound] value_name: {}", value_name_string); println!("[GameSound] value: {}", value_string); }, _ => return call_original!(_this, value_name, value, _game_object, method_info), } // For current purposes, we don't need to do anything past this point if there's nothing to change. if value_string == "None" { return call_original!(_this, value_name, value, _game_object, method_info); } // Check category match value_name_string.as_str() { "Person" => { // Filter for '!' fallback let parsed_value = get_switchname_fallback(value.unwrap()); if parsed_value == value.unwrap() { return call_original!(_this, value_name, value, _game_object, method_info); } println!("[GameSound] Parsed value: {}", parsed_value); return call_original!(_this, value_name, Some(parsed_value), _game_object, method_info); }, _ => call_original!(_this, value_name, value, _game_object, method_info), } } // App.GameSound$$UnitPickVoice 7102292360 void App.GameSound$$UnitPickVoice(App_Unit_o * unit, MethodInfo * method) 1012 #[unity::hook("App", "GameSound", "UnitPickVoice")] pub fn gamesound_unitpickvoice(unit: &Unit, method_info: OptionalMethod) { // This looks pretty insane, and it is. // // Each unit has a set of voice clips that they can play when you select them. // They vary based on the unit's current health status (High, Medium, Low). // // The game keeps track of which type of voice clip was last played for a unit. // For example, if the unit is at High health, and you select them, they will say a line from the High pool. // However, if you select them again, they won't say any High line again, and instead, remain silent. // // Then later, if they take damage, and you select them, they will say a Medium or Low line. // // You won't hear a V_Pick line again until their health status changes. // // The last_pick_voice field is used to keep track of the last voice clip type that was played. // // We need to save the last pick voice, and potentially later restore it when playing an original V_Pick event. // // If we don't, then the game thinks that the unit has already played the voice clip, and won't play it again. // // The actual restoration is done in the soundplay_posteventcallback hook unsafe { PREVIOUS_LAST_PICK_VOICE = unit.last_pick_voice } call_original!(unit, method_info); } // #[unity::from_offset("App", "GameSound", "IsEventLoaded")] // pub fn gamesound_iseventloaded(event_name: &Il2CppString, method_info: OptionalMethod) -> bool;
0
0.947374
1
0.947374
game-dev
MEDIA
0.831195
game-dev
0.961768
1
0.961768
NanceDevDiaries/Tutorials
2,294
IntroToGameSettings/Source/LyraGame/Settings/LyraGameSettingRegistry_Gameplay.cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "LyraGameSettingRegistry.h" #include "GameSettingCollection.h" #include "EditCondition/WhenPlayingAsPrimaryPlayer.h" #include "EditCondition/WhenPlatformHasTrait.h" #include "CustomSettings/LyraSettingValueDiscrete_Language.h" #include "LyraSettingsLocal.h" #include "GameSettingValueDiscreteDynamic.h" #include "Player/LyraLocalPlayer.h" #include "Replays/LyraReplaySubsystem.h" #define LOCTEXT_NAMESPACE "Lyra" UGameSettingCollection* ULyraGameSettingRegistry::InitializeGameplaySettings(ULyraLocalPlayer* InLocalPlayer) { UGameSettingCollection* Screen = NewObject<UGameSettingCollection>(); Screen->SetDevName(TEXT("GameplayCollection")); Screen->SetDisplayName(LOCTEXT("GameplayCollection_Name", "Gameplay")); Screen->Initialize(InLocalPlayer); // ... More code // @Game-Change start Accessibility settings { UGameSettingCollection* AccessibilitySubsection = NewObject<UGameSettingCollection>(); AccessibilitySubsection->SetDevName(TEXT("GameplayAccessibilityCollection")); AccessibilitySubsection->SetDisplayName(LOCTEXT("GameplayAccessibilityCollection_Name", "Accessibility")); Screen->AddSetting(AccessibilitySubsection); //---------------------------------------------------------------------------------- { UGameSettingValueDiscreteDynamic_Bool* Setting = NewObject<UGameSettingValueDiscreteDynamic_Bool>(); Setting->SetDevName(TEXT("GameplayArachnophobiaMode")); Setting->SetDisplayName(LOCTEXT("GameplayArachnophobiaModeSetting_Name", "Arachnophobia mode")); Setting->SetDescriptionRichText(LOCTEXT("GameplayArachnophobiaModeSetting_Description", "Make the scary spiders look like cute capybaras.")); Setting->SetDynamicGetter(GET_LOCAL_SETTINGS_FUNCTION_PATH(ShouldUseArachnophobiaMode)); Setting->SetDynamicSetter(GET_LOCAL_SETTINGS_FUNCTION_PATH(SetShouldUseArachnophobiaMode)); Setting->SetDefaultValue(GetDefault<ULyraSettingsLocal>()->ShouldUseArachnophobiaMode()); Setting->AddEditCondition(FWhenPlayingAsPrimaryPlayer::Get()); AccessibilitySubsection->AddSetting(Setting); } //---------------------------------------------------------------------------------- } // @Game-Change end Accessibility settings return Screen; } #undef LOCTEXT_NAMESPACE
0
0.87204
1
0.87204
game-dev
MEDIA
0.88633
game-dev
0.608341
1
0.608341
Mortalknight/GW2_UI
22,465
Classic/Objectives/objectives.lua
local _, GW = ... local TRACKER_TYPE_COLOR = GW.TRACKER_TYPE_COLOR local lastAQW = GetTime() local tomTomWaypoint = nil local function AddTomTomWaypoint(questId, objective) if TomTom and TomTom.AddWaypoint and Questie and Questie.started then local QuestieQuest = QuestieLoader:ImportModule("QuestieDB").GetQuest(questId) local spawn, zone, name = QuestieLoader:ImportModule("DistanceUtils").GetNearestSpawnForQuest(QuestieQuest) if (not spawn) and objective ~= nil then spawn, zone, name = QuestieLoader:ImportModule("DistanceUtils").GetNearestSpawn(objective) end if spawn then if tomTomWaypoint and TomTom.RemoveWaypoint then -- remove old waypoint TomTom:RemoveWaypoint(tomTomWaypoint) end local uiMapId = QuestieLoader:ImportModule("ZoneDB"):GetUiMapIdByAreaId(zone) tomTomWaypoint = TomTom:AddWaypoint(uiMapId, spawn[1] / 100, spawn[2] / 100, {title = name, crazy = true}) end end end local function LinkQuestIntoChat(title, questId) if not ChatFrame1EditBox:IsVisible() then if Questie and Questie.started then ChatFrame_OpenChat("[" .. title .. " (" .. questId .. ")]") else ChatFrame_OpenChat(gsub(title, " *(.*)", "%1")) end else if Questie and Questie.started then ChatEdit_InsertLink("[" .. title .. " (" .. questId .. ")]") else ChatEdit_InsertLink(gsub(title, " *(.*)", "%1")) end end end local function UntrackQuest(questLogIndex) local questID = GetQuestIDFromLogIndex(questLogIndex) for index, value in ipairs(QUEST_WATCH_LIST) do if value.id == questID then tremove(QUEST_WATCH_LIST, index) end end if GetCVar("autoQuestWatch") == "0" then GW2UI_QUEST_WATCH_DB.TrackedQuests[questID] = nil else GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questID] = true end RemoveQuestWatch(questLogIndex) QuestWatch_Update() QuestLog_Update() end local function AddQuestInfos(questId, id) local title, level, group, _, _, isComplete, _, _, startEvent = GetQuestLogTitle(id) local sourceItemId = nil local isFailed = false if Questie and Questie.started then local questieQuest = QuestieLoader:ImportModule("QuestieDB").GetQuest(questId) if questieQuest and questieQuest.sourceItemId then sourceItemId = questieQuest.sourceItemId end end if isComplete == nil then isComplete = false elseif isComplete == 1 then isComplete = true else isComplete = false isFailed = true end return { questId = questId, questWatchedId = id or 0, questLogIndex = id, questLevel = level, questGroup = group, title = title, isComplete = isComplete, startEvent = startEvent, numObjectives = GetNumQuestLeaderBoards(id), requiredMoney = GetQuestLogRequiredMoney(questId), isAutoComplete = false, sourceItemId = sourceItemId, isFailed = isFailed } end local function IsQuestFrequency(questId) -- if questie is loaded check for daily quest if Questie and Questie.started then return QuestieLoader:ImportModule("QuestieDB").IsDailyQuest(questId) end return false end local function UpdateBlockInternal(self, parent, quest) self.height = 25 self.numObjectives = 0 self.turnin:Hide() if quest.requiredMoney then parent.watchMoneyReasons = parent.watchMoneyReasons + 1 else parent.watchMoneyReasons = parent.watchMoneyReasons - 1 end self.title = quest.title local text = "" if quest.questGroup == "Elite" then text = "[" .. quest.questLevel .. "|TInterface/AddOns/GW2_UI/textures/icons/quest-group-icon:12:12:0:0|t] " elseif quest.questGroup == "Dungeon" then text = "[" .. quest.questLevel .. "|TInterface/AddOns/GW2_UI/textures/icons/quest-dungeon-icon:12:12:0:0|t] " elseif quest.questGroup then text = "[" .. quest.questLevel .. "+] " else text = "[" .. quest.questLevel .. "] " end self.questID = quest.questId self.questLogIndex = quest.questLogIndex self.sourceItemId = quest.sourceItemId self.title = quest.title self.Header:SetText(text .. quest.title) GW.CombatQueue_Queue(nil, self.UpdateObjectiveActionButton, {self}) if Questie and Questie.started and GW.settings.QUESTTRACKER_SHOW_XP and GW.mylevel < GetMaxPlayerLevel() then local xpReward = QuestieLoader:ImportModule("QuestXP"):GetQuestLogRewardXP(quest.questId, false) if xpReward then self.Header:SetText(text .. quest.title .. " |cFF888888(" .. GW.CommaValue(xpReward) .. XP .. ")|r") end end if quest.numObjectives == 0 and GetMoney() >= quest.requiredMoney and not quest.startEvent then quest.isComplete = true end self.isComplete = quest.isComplete if not quest.isComplete then self:UpdateBlockObjectives(quest.numObjectives) end if quest.requiredMoney and quest.requiredMoney > GetMoney() and not quest.isComplete then self:AddObjective(GetMoneyString(GetMoney()) .. " / " .. GetMoneyString(quest.requiredMoney), self.numObjectives + 1, {isQuest = true, finished = quest.isComplete, objectiveType = nil}) end if quest.isComplete then if quest.isAutoComplete then self:AddObjective(QUEST_WATCH_CLICK_TO_COMPLETE, self.numObjectives + 1, {isQuest = true, finished = false, objectiveType = nil}) else local completionText = GetQuestLogCompletionText(quest.questLogIndex) if completionText then self:AddObjective(completionText, self.numObjectives + 1, {isQuest = true, finished = false, objectiveType = nil}) else self:AddObjective(QUEST_WATCH_QUEST_READY, self.numObjectives + 1, {isQuest = true, finished = false, objectiveType = nil}) end end elseif quest.isFailed then self:AddObjective(FAILED, self.numObjectives + 1, {isQuest = true, finished = false, objectiveType = nil}) end self.height = self.height + 5 self:SetHeight(self.height) end GwQuestLogBlockMixin = {} function GwQuestLogBlockMixin:UpdateBlockObjectives(numObjectives) local addedObjectives = 1 local infos = C_QuestLog.GetQuestObjectives(self.questID) for objectiveIndex = 1, numObjectives do local text = infos[objectiveIndex].text local objectiveType = infos[objectiveIndex].type local finished = infos[objectiveIndex].finished if not finished or not text then self:AddObjective(text, addedObjectives, {isQuest = true, finished = finished, objectiveType = objectiveType}) addedObjectives = addedObjectives + 1 end end end function GwQuestLogBlockMixin:UpdateBlock(parent, quest) if quest.questId then UpdateBlockInternal(self, parent, quest, quest.questId, quest.questLogIndex) end end GwQuestLogMixin = {} function GwQuestLogMixin:OnEvent(event, ...) local arg1 = ... local numWatchedQuests = GetNumQuestWatches() if (event == "QUEST_LOG_UPDATE" or event == "UPDATE_FACTION" or (event == "UNIT_QUEST_LOG_CHANGED" and arg1 == "player")) then self:UpdateLayout() elseif event == "PLAYER_MONEY" and self.watchMoneyReasons > numWatchedQuests then self:UpdateLayout() else self:UpdateLayout() end if self.watchMoneyReasons > numWatchedQuests then self.watchMoneyReasons = self.watchMoneyReasons - numWatchedQuests end GwQuestTracker:LayoutChanged() end function GwQuestLogMixin:UpdateLayout() if self.isUpdating then return end self.isUpdating = true local counterQuest = 0 local savedContainerHeight = self.collapsed and 20 or 1 local shouldShowHeader = not self.collapsed local frameName = self:GetName() if self.collapsed then self.header:Show() else self.header:Hide() end -- collect quests here local sorted = {} GW.sorted = sorted local numQuests = GetNumQuestLogEntries() for i = 1, numQuests do local questId = select(8, GetQuestLogTitle(i)) if questId and questId > 0 then local questInfo = AddQuestInfos(questId, i) table.insert(sorted, questInfo) end end --sort based on setting if GW.settings.QUESTTRACKER_SORTING == "LEVEL" then -- Sort by level table.sort(sorted, function(a, b) return a and b and a.questLevel < b.questLevel end) elseif GW.settings.QUESTTRACKER_SORTING == "ZONE" then -- Sort by Zone if Questie and Questie.started and QuestieLoader then local QuestieTrackerUtils = QuestieLoader:ImportModule("TrackerUtils") local QuestieDB = QuestieLoader:ImportModule("QuestieDB") if QuestieTrackerUtils and QuestieDB then table.sort(sorted, function(a, b) local qA = QuestieDB.GetQuest(a.questId) local qB = QuestieDB.GetQuest(b.questId) local qAZone, qBZone if qA and qA.zoneOrSort > 0 then qAZone = QuestieTrackerUtils:GetZoneNameByID(qA.zoneOrSort) elseif qA and qA.zoneOrSort < 0 then qAZone = QuestieTrackerUtils:GetCategoryNameByID(qA.zoneOrSort) else qAZone = tostring(qA and qA.zoneOrSort or "") end if qB and qB.zoneOrSort > 0 then qBZone = QuestieTrackerUtils:GetZoneNameByID(qB.zoneOrSort) elseif qB and qB.zoneOrSort < 0 then qBZone = QuestieTrackerUtils:GetCategoryNameByID(qB.zoneOrSort) else qBZone = tostring(qB and qB.zoneOrSort or "") end -- Sort by Zone then by Level to mimic QuestLog sorting if qAZone == qBZone then return qA.level < qB.level else if qAZone ~= nil and qBZone ~= nil then return qAZone < qBZone else return qAZone and qBZone end end end) end end end wipe(self.trackedQuests) for _, quest in pairs(sorted) do if ((GetCVar("autoQuestWatch") == "1" and not GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[quest.questId]) or (GetCVar("autoQuestWatch") == "0" and GW2UI_QUEST_WATCH_DB.TrackedQuests[quest.questId])) then if shouldShowHeader then self.header:Show() counterQuest = counterQuest + 1 if counterQuest == 1 then savedContainerHeight = 20 end local isFrequency = IsQuestFrequency(quest.questId) local colorKey = isFrequency and "DAILY" or "QUEST" local block = self:GetBlock(counterQuest, colorKey, true) block.isFrequency = isFrequency block:UpdateBlock(self, quest) block:Show() savedContainerHeight = savedContainerHeight + block.height block.fromContainerTopHeight = savedContainerHeight GW.CombatQueue_Queue("update_tracker_" .. frameName .. block.index, block.UpdateObjectiveActionButtonPosition, {block}) tinsert(self.trackedQuests, quest) else counterQuest = counterQuest + 1 local block = self.blocks and self.blocks[counterQuest] if block then block.questID = nil block.questLogIndex = 0 block.sourceItemId = nil block:Hide() GW.CombatQueue_Queue("update_tracker_" .. counterQuest, block.UpdateObjectiveActionButton, {block}) end end end end self.oldHeight = GW.RoundInt(self:GetHeight()) self:SetHeight(counterQuest > 0 and savedContainerHeight or 1) self.numQuests = counterQuest -- hide other quests for i = counterQuest + 1, #self.blocks do local block = self.blocks[i] block.questID = nil block.questLogIndex = 0 block.sourceItemId = nil block:Hide() GW.CombatQueue_Queue("update_tracker_itembutton_remove" .. i, block.UpdateObjectiveActionButton, {block}) end local headerCounterText = " (" .. counterQuest .. ")" self.header.title:SetText(TRACKER_HEADER_QUESTS .. headerCounterText) GwQuestTracker:LayoutChanged() self.isUpdating = false end function GwQuestLogMixin:BlockOnClick(button) if button == "RightButton" then MenuUtil.CreateContextMenu(self, function(ownerRegion, rootDescription) rootDescription:CreateTitle(self.title) if Questie and Questie.started then local QuestieQuest = QuestieLoader:ImportModule("QuestieDB").GetQuest(self.questID) or {} if QuestieQuest:IsComplete() == 0 then local submenuObjectives = rootDescription:CreateButton(OBJECTIVES_TRACKER_LABEL) for _, objective in pairs(QuestieQuest.Objectives) do local submenuObjectives = submenuObjectives:CreateButton(objective.Description) if TomTom and TomTom.AddWaypoint then submenuObjectives:CreateButton(GW.L["Set TomTom Target"], function() AddTomTomWaypoint(self.questID, objective) end) end submenuObjectives:CreateButton(GW.L["Show on Map"], function() QuestieLoader:ImportModule("TrackerUtils"):ShowObjectiveOnMap(objective) end) end if next(QuestieQuest.SpecialObjectives) then for _, objective in pairs(QuestieQuest.SpecialObjectives) do local submenuObjectives = submenuObjectives:CreateButton(objective.Description) if TomTom and TomTom.AddWaypoint then submenuObjectives:CreateButton(GW.L["Set TomTom Target"], function() AddTomTomWaypoint(self.questID, objective) end) end submenuObjectives:CreateButton(GW.L["Show on Map"], function() QuestieLoader:ImportModule("TrackerUtils"):ShowObjectiveOnMap(objective) end) end end end end rootDescription:CreateButton(COMMUNITIES_INVITE_MANAGER_LINK_TO_CHAT, function() LinkQuestIntoChat(self.title, self.questID) end) rootDescription:CreateButton("Wowhead URL", function() StaticPopup_Show("QUESTIE_WOWHEAD_URL", self.questID, self.title) end) rootDescription:CreateButton(OBJECTIVES_VIEW_IN_QUESTLOG, function() QuestLogFrame:Show() QuestLog_SetSelection(self.questLogIndex) QuestLog_Update() end) if TomTom and TomTom.AddWaypoint and Questie and Questie.started then rootDescription:CreateButton(GW.L["Set TomTom Target"], function() AddTomTomWaypoint(self.questID, nil) end) end if Questie and Questie.started and self.isComplete then rootDescription:CreateButton(GW.L["Show on Map"], function() local QuestieQuest = QuestieLoader:ImportModule("QuestieDB").GetQuest(self.questID) QuestieLoader:ImportModule("TrackerUtils"):ShowFinisherOnMap(QuestieQuest) end) end rootDescription:CreateButton(UNTRACK_QUEST, function() UntrackQuest(self.questLogIndex) end) end) return end if IsShiftKeyDown() and ChatEdit_GetActiveWindow() then if button == "LeftButton" then LinkQuestIntoChat(self.title, self.questID) end return elseif IsControlKeyDown() then if button == "LeftButton" then AddTomTomWaypoint(self.questID, nil) else UntrackQuest(self.questLogIndex) end return end if button ~= "RightButton" then PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON) if QuestLogFrame:IsShown() and QuestLogFrame.selectedButtonID == self.questLogIndex then QuestLogFrame:Hide() else QuestLogFrame:Show() QuestLog_SetSelection(self.questLogIndex) QuestLog_Update() end end end GwObjectivesQuestContainerMixin = CreateFromMixins(GwQuestLogMixin) function GwObjectivesQuestContainerMixin:_RemoveQuestWatch(index, isGW2) if not isGW2 then local questId = select(8, GetQuestLogTitle(index)) if questId == 0 then questId = index end if questId then if "0" == GetCVar("autoQuestWatch") then GW2UI_QUEST_WATCH_DB.TrackedQuests[questId] = nil else GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questId] = true end self:OnEvent() end end end function GwObjectivesQuestContainerMixin:_AQW_Insert(index) if index == 0 then return end local now = GetTime() if index and index == self._last_aqw and (now - lastAQW) < 0.1 then -- this fixes double calling due to AQW+AQW_Insert (QuestGuru fix) return end lastAQW = now self._last_aqw = index RemoveQuestWatch(index, true) -- prevent hitting 5 quest watch limit local questId = select(8, GetQuestLogTitle(index)) if questId == 0 then questId = index end if questId > 0 then if "0" == GetCVar("autoQuestWatch") then if GW2UI_QUEST_WATCH_DB.TrackedQuests[questId] then GW2UI_QUEST_WATCH_DB.TrackedQuests[questId] = nil else GW2UI_QUEST_WATCH_DB.TrackedQuests[questId] = true end else if GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questId] then GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questId] = nil elseif IsShiftKeyDown() and (QuestLogFrame:IsShown() or (QuestLogExFrame and QuestLogExFrame:IsShown())) then--hack GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questId] = true end end self:OnEvent() end end function GwObjectivesQuestContainerMixin:InitModule() self.blockMixInTemplate = GwQuestLogBlockMixin GW2UI_QUEST_WATCH_DB = GW2UI_QUEST_WATCH_DB or {} GW2UI_QUEST_WATCH_DB.TrackedQuests = GW2UI_QUEST_WATCH_DB.TrackedQuests or {} GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests = GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests or {} self:SetScript("OnEvent", self.OnEvent) self:RegisterEvent("QUEST_LOG_UPDATE") self:RegisterEvent("QUEST_WATCH_UPDATE") self:RegisterEvent("UPDATE_FACTION") self:RegisterEvent("UNIT_QUEST_LOG_CHANGED") self:RegisterEvent("PLAYER_LEVEL_UP") self:RegisterEvent("PLAYER_MONEY") self:RegisterEvent("PLAYER_ENTERING_WORLD") self.watchMoneyReasons = 0 self.trackedQuests = {} self.header = CreateFrame("Button", nil, self, "GwQuestTrackerHeader") self.header.title:GwSetFontTemplate(DAMAGE_TEXT_FONT, GW.TextSizeType.HEADER) self.header.title:SetShadowOffset(1, -1) self.collapsed = false self.header:SetScript("OnMouseDown", function() self:CollapseHeader() end) -- this way, otherwiese we have a wrong self at the function self.header.title:SetTextColor(TRACKER_TYPE_COLOR.QUEST.r, TRACKER_TYPE_COLOR.QUEST.g, TRACKER_TYPE_COLOR.QUEST.b) self.header.icon:SetTexCoord(0, 0.5, 0.25, 0.5) self.header.title:SetText(TRACKER_HEADER_QUESTS) --hook functions hooksecurefunc("AutoQuestWatch_Insert", function(questIndex) self:_AQW_Insert(questIndex) end) hooksecurefunc("AddQuestWatch", function(questIndex) self:_AQW_Insert(questIndex) end) hooksecurefunc("RemoveQuestWatch", function(questIndex) self:_RemoveQuestWatch(questIndex) end) IsQuestWatched = function(index) local _, _, _, isHeader, _, _, _, questId = GetQuestLogTitle(index) if isHeader then return false end if questId == 0 then questId = index end if "0" == GetCVar("autoQuestWatch") then return GW2UI_QUEST_WATCH_DB.TrackedQuests[questId or -1] else return questId and (not GW2UI_QUEST_WATCH_DB.AutoUntrackedQuests[questId]) end end GetNumQuestWatches = function() return 0 end local baseQLTB_OnClick = QuestLogTitleButton_OnClick QuestLogTitleButton_OnClick = function(btn, button) -- I wanted to use hooksecurefunc but this needs to be a pre-hook to work properly unfortunately if (not btn) or btn.isHeader or not IsShiftKeyDown() then baseQLTB_OnClick(btn, button) return end local questLogLineIndex = self:GetID() if ( IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow() ) then local questId = GetQuestIDFromLogIndex(questLogLineIndex) ChatEdit_InsertLink("["..gsub(btn:GetText(), " *(.*)", "%1").." ("..questId..")]") else if GetNumQuestLeaderBoards(questLogLineIndex) == 0 and not IsQuestWatched(questLogLineIndex) then -- only call if we actually want to fix this quest (normal quests already call AQW_insert) self:_AQW_Insert(questLogLineIndex) QuestWatch_Update() QuestLog_SetSelection(questLogLineIndex) QuestLog_Update() else baseQLTB_OnClick(btn, button) end end end if not self._IsQuestWatched then self._IsQuestWatched = IsQuestWatched self._GetNumQuestWatches = GetNumQuestWatches end self:OnEvent("LOAD") end
0
0.856482
1
0.856482
game-dev
MEDIA
0.926375
game-dev
0.942551
1
0.942551
spring/spring
51,910
rts/Lua/LuaHandleSynced.cpp
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #include "LuaHandleSynced.h" #include "LuaInclude.h" #include "LuaUtils.h" #include "LuaArchive.h" #include "LuaCallInCheck.h" #include "LuaConfig.h" #include "LuaConstGL.h" #include "LuaConstCMD.h" #include "LuaConstCMDTYPE.h" #include "LuaConstCOB.h" #include "LuaConstEngine.h" #include "LuaConstGame.h" #include "LuaConstPlatform.h" #include "LuaInterCall.h" #include "LuaRender.h" #include "LuaSyncedCtrl.h" #include "LuaSyncedRead.h" #include "LuaSyncedTable.h" #include "LuaUICommand.h" #include "LuaUnsyncedCtrl.h" #include "LuaUnsyncedRead.h" #include "LuaFeatureDefs.h" #include "LuaUnitDefs.h" #include "LuaWeaponDefs.h" #include "LuaScream.h" #include "LuaMaterial.h" #include "LuaOpenGL.h" #include "LuaVFS.h" #include "LuaZip.h" #include "Game/Game.h" #include "Game/WordCompletion.h" #include "Sim/Misc/GlobalSynced.h" #include "Sim/Misc/TeamHandler.h" #include "Sim/Features/FeatureDef.h" #include "Sim/Features/FeatureDefHandler.h" #include "Sim/Units/BuildInfo.h" #include "Sim/Units/UnitDef.h" #include "Sim/Units/UnitDefHandler.h" #include "Sim/Units/Scripts/CobInstance.h" #include "Sim/Units/Scripts/LuaUnitScript.h" #include "Sim/Weapons/Weapon.h" #include "Sim/Weapons/WeaponDefHandler.h" #include "System/EventHandler.h" #include "System/creg/SerializeLuaState.h" #include "System/FileSystem/FileHandler.h" #include "System/Log/ILog.h" #include "System/SpringMath.h" LuaRulesParams::Params CSplitLuaHandle::gameParams; /******************************************************************************/ /******************************************************************************/ // ## ## ## ## ###### ## ## ## ## ###### ######## ######## // ## ## ### ## ## ## ## ## ### ## ## ## ## ## ## // ## ## #### ## ## #### #### ## ## ## ## ## // ## ## ## ## ## ###### ## ## ## ## ## ###### ## ## // ## ## ## #### ## ## ## #### ## ## ## ## // ## ## ## ### ## ## ## ## ### ## ## ## ## ## // ####### ## ## ###### ## ## ## ###### ######## ######## CUnsyncedLuaHandle::CUnsyncedLuaHandle(CSplitLuaHandle* _base, const std::string& _name, int _order) : CLuaHandle(_name, _order, false, false) , base(*_base) { D.allowChanges = false; } CUnsyncedLuaHandle::~CUnsyncedLuaHandle() = default; bool CUnsyncedLuaHandle::Init(const std::string& code, const std::string& file) { if (!IsValid()) return false; // load the standard libraries LUA_OPEN_LIB(L, luaopen_base); LUA_OPEN_LIB(L, luaopen_math); LUA_OPEN_LIB(L, luaopen_table); LUA_OPEN_LIB(L, luaopen_string); //LUA_OPEN_LIB(L, luaopen_io); //LUA_OPEN_LIB(L, luaopen_os); //LUA_OPEN_LIB(L, luaopen_package); //LUA_OPEN_LIB(L, luaopen_debug); // delete some dangerous functions lua_pushnil(L); lua_setglobal(L, "dofile"); lua_pushnil(L); lua_setglobal(L, "loadfile"); lua_pushnil(L); lua_setglobal(L, "loadlib"); lua_pushnil(L); lua_setglobal(L, "loadstring"); // replaced lua_pushnil(L); lua_setglobal(L, "require"); lua_pushvalue(L, LUA_GLOBALSINDEX); AddBasicCalls(L); // remove Script.Kill() lua_getglobal(L, "Script"); LuaPushNamedNil(L, "Kill"); lua_pop(L, 1); LuaPushNamedCFunc(L, "loadstring", CSplitLuaHandle::LoadStringData); LuaPushNamedCFunc(L, "CallAsTeam", CSplitLuaHandle::CallAsTeam); LuaPushNamedNumber(L, "COBSCALE", COBSCALE); // load our libraries { #define KILL { KillLua(); return false; } if (!LuaSyncedTable::PushEntries(L)) KILL if (!AddEntriesToTable(L, "VFS", LuaVFS::PushUnsynced )) KILL if (!AddEntriesToTable(L, "VFS", LuaZipFileReader::PushUnsynced )) KILL if (!AddEntriesToTable(L, "VFS", LuaZipFileWriter::PushUnsynced )) KILL if (!AddEntriesToTable(L, "VFS", LuaArchive::PushEntries )) KILL if (!AddEntriesToTable(L, "UnitDefs", LuaUnitDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "WeaponDefs", LuaWeaponDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "Script", LuaInterCall::PushEntriesUnsynced)) KILL if (!AddEntriesToTable(L, "Script", LuaScream::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaSyncedRead::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaUnsyncedCtrl::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaUnsyncedRead::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaUICommand::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaRender::PushEntries )) KILL if (!AddEntriesToTable(L, "gl", LuaOpenGL::PushEntries )) KILL if (!AddEntriesToTable(L, "GL", LuaConstGL::PushEntries )) KILL if (!AddEntriesToTable(L, "Engine", LuaConstEngine::PushEntries )) KILL if (!AddEntriesToTable(L, "Platform", LuaConstPlatform::PushEntries )) KILL if (!AddEntriesToTable(L, "Game", LuaConstGame::PushEntries )) KILL if (!AddEntriesToTable(L, "CMD", LuaConstCMD::PushEntries )) KILL if (!AddEntriesToTable(L, "CMDTYPE", LuaConstCMDTYPE::PushEntries )) KILL if (!AddEntriesToTable(L, "LOG", LuaUtils::PushLogEntries )) KILL #undef KILL } lua_settop(L, 0); // add code from the sub-class if (!base.AddUnsyncedCode(L)) { KillLua(); return false; } lua_settop(L, 0); if (!LoadCode(L, code, file)) { KillLua(); return false; } lua_settop(L, 0); eventHandler.AddClient(this); return true; } // // Call-Ins // void CUnsyncedLuaHandle::RecvFromSynced(lua_State* srcState, int args) { if (!IsValid()) return; LUA_CALL_IN_CHECK(L); luaL_checkstack(L, 2 + args, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return; // the call is not defined LuaUtils::CopyData(L, srcState, args); // call the routine RunCallIn(L, cmdStr, args, 0); } bool CUnsyncedLuaHandle::DrawUnit(const CUnit* unit) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 4, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; const bool oldDrawState = LuaOpenGL::IsDrawingEnabled(L); LuaOpenGL::SetDrawingEnabled(L, true); lua_pushnumber(L, unit->id); lua_pushnumber(L, game->GetDrawMode()); const bool success = RunCallIn(L, cmdStr, 2, 1); LuaOpenGL::SetDrawingEnabled(L, oldDrawState); if (!success) return false; const bool draw = luaL_optboolean(L, -1, false); lua_pop(L, 1); return draw; } bool CUnsyncedLuaHandle::DrawFeature(const CFeature* feature) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 4, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; const bool oldDrawState = LuaOpenGL::IsDrawingEnabled(L); LuaOpenGL::SetDrawingEnabled(L, true); lua_pushnumber(L, feature->id); lua_pushnumber(L, game->GetDrawMode()); const bool success = RunCallIn(L, cmdStr, 2, 1); LuaOpenGL::SetDrawingEnabled(L, oldDrawState); if (!success) return false; const bool draw = luaL_optboolean(L, -1, false); lua_pop(L, 1); return draw; } bool CUnsyncedLuaHandle::DrawShield(const CUnit* unit, const CWeapon* weapon) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 5, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; const bool oldDrawState = LuaOpenGL::IsDrawingEnabled(L); LuaOpenGL::SetDrawingEnabled(L, true); lua_pushnumber(L, unit->id); lua_pushnumber(L, weapon->weaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, game->GetDrawMode()); const bool success = RunCallIn(L, cmdStr, 3, 1); LuaOpenGL::SetDrawingEnabled(L, oldDrawState); if (!success) return false; const bool draw = luaL_optboolean(L, -1, false); lua_pop(L, 1); return draw; } bool CUnsyncedLuaHandle::DrawProjectile(const CProjectile* projectile) { assert(projectile->weapon || projectile->piece); LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 5, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; const bool oldDrawState = LuaOpenGL::IsDrawingEnabled(L); LuaOpenGL::SetDrawingEnabled(L, true); lua_pushnumber(L, projectile->id); lua_pushnumber(L, game->GetDrawMode()); const bool success = RunCallIn(L, cmdStr, 2, 1); LuaOpenGL::SetDrawingEnabled(L, oldDrawState); if (!success) return false; const bool draw = luaL_optboolean(L, -1, false); lua_pop(L, 1); return draw; } bool CUnsyncedLuaHandle::DrawMaterial(const LuaMaterial* material) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 4, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; const bool oldDrawState = LuaOpenGL::IsDrawingEnabled(L); LuaOpenGL::SetDrawingEnabled(L, true); lua_pushnumber(L, material->uuid); // lua_pushnumber(L, material->type); lua_pushnumber(L, game->GetDrawMode()); const bool success = RunCallIn(L, cmdStr, 2, 1); LuaOpenGL::SetDrawingEnabled(L, oldDrawState); if (!success) return false; const bool draw = luaL_optboolean(L, -1, false); lua_pop(L, 1); return draw; } // // Call-Outs // /******************************************************************************/ /******************************************************************************/ // ###### ## ## ## ## ###### ######## ######## // ## ## ## ## ### ## ## ## ## ## ## // ## #### #### ## ## ## ## ## // ###### ## ## ## ## ## ###### ## ## // ## ## ## #### ## ## ## ## // ## ## ## ## ### ## ## ## ## ## // ###### ## ## ## ###### ######## ######## CSyncedLuaHandle::CSyncedLuaHandle(CSplitLuaHandle* _base, const std::string& _name, int _order) : CLuaHandle(_name, _order, false, true) , base(*_base) , origNextRef(-1) { D.allowChanges = true; } CSyncedLuaHandle::~CSyncedLuaHandle() { // kill all unitscripts running in this handle CLuaUnitScript::HandleFreed(this); } bool CSyncedLuaHandle::Init(const std::string& code, const std::string& file) { if (!IsValid()) return false; watchUnitDefs.resize(unitDefHandler->NumUnitDefs() + 1, false); watchFeatureDefs.resize(featureDefHandler->NumFeatureDefs() + 1, false); watchExplosionDefs.resize(weaponDefHandler->NumWeaponDefs(), false); watchProjectileDefs.resize(weaponDefHandler->NumWeaponDefs() + 1, false); // last bit controls piece-projectiles watchAllowTargetDefs.resize(weaponDefHandler->NumWeaponDefs(), false); // load the standard libraries SPRING_LUA_OPEN_LIB(L, luaopen_base); SPRING_LUA_OPEN_LIB(L, luaopen_math); SPRING_LUA_OPEN_LIB(L, luaopen_table); SPRING_LUA_OPEN_LIB(L, luaopen_string); //SPRING_LUA_OPEN_LIB(L, luaopen_io); //SPRING_LUA_OPEN_LIB(L, luaopen_os); //SPRING_LUA_OPEN_LIB(L, luaopen_package); //SPRING_LUA_OPEN_LIB(L, luaopen_debug); lua_getglobal(L, "next"); origNextRef = luaL_ref(L, LUA_REGISTRYINDEX); // delete/replace some dangerous functions lua_pushnil(L); lua_setglobal(L, "dofile"); lua_pushnil(L); lua_setglobal(L, "loadfile"); lua_pushnil(L); lua_setglobal(L, "loadlib"); lua_pushnil(L); lua_setglobal(L, "require"); lua_pushnil(L); lua_setglobal(L, "rawequal"); //FIXME not unsafe anymore since split? lua_pushnil(L); lua_setglobal(L, "rawget"); //FIXME not unsafe anymore since split? lua_pushnil(L); lua_setglobal(L, "rawset"); //FIXME not unsafe anymore since split? // lua_pushnil(L); lua_setglobal(L, "getfenv"); // lua_pushnil(L); lua_setglobal(L, "setfenv"); lua_pushnil(L); lua_setglobal(L, "newproxy"); // sync unsafe cause of __gc lua_pushnil(L); lua_setglobal(L, "gcinfo"); lua_pushnil(L); lua_setglobal(L, "collectgarbage"); lua_pushvalue(L, LUA_GLOBALSINDEX); LuaPushNamedCFunc(L, "loadstring", CSplitLuaHandle::LoadStringData); LuaPushNamedCFunc(L, "pairs", SyncedPairs); LuaPushNamedCFunc(L, "next", SyncedNext); lua_pop(L, 1); lua_pushvalue(L, LUA_GLOBALSINDEX); AddBasicCalls(L); // into Global // adjust the math.random() and math.randomseed() calls lua_getglobal(L, "math"); LuaPushNamedCFunc(L, "random", SyncedRandom); LuaPushNamedCFunc(L, "randomseed", SyncedRandomSeed); lua_pop(L, 1); // pop the global math table lua_getglobal(L, "Script"); LuaPushNamedCFunc(L, "AddActionFallback", AddSyncedActionFallback); LuaPushNamedCFunc(L, "RemoveActionFallback", RemoveSyncedActionFallback); LuaPushNamedCFunc(L, "GetWatchUnit", GetWatchUnitDef); LuaPushNamedCFunc(L, "SetWatchUnit", SetWatchUnitDef); LuaPushNamedCFunc(L, "GetWatchFeature", GetWatchFeatureDef); LuaPushNamedCFunc(L, "SetWatchFeature", SetWatchFeatureDef); LuaPushNamedCFunc(L, "GetWatchExplosion", GetWatchExplosionDef); LuaPushNamedCFunc(L, "SetWatchExplosion", SetWatchExplosionDef); LuaPushNamedCFunc(L, "GetWatchProjectile", GetWatchProjectileDef); LuaPushNamedCFunc(L, "SetWatchProjectile", SetWatchProjectileDef); LuaPushNamedCFunc(L, "GetWatchAllowTarget", GetWatchAllowTargetDef); LuaPushNamedCFunc(L, "SetWatchAllowTarget", SetWatchAllowTargetDef); LuaPushNamedCFunc(L, "GetWatchWeapon", GetWatchWeaponDef); LuaPushNamedCFunc(L, "SetWatchWeapon", SetWatchWeaponDef); lua_pop(L, 1); // add the custom file loader LuaPushNamedCFunc(L, "SendToUnsynced", SendToUnsynced); LuaPushNamedCFunc(L, "CallAsTeam", CSplitLuaHandle::CallAsTeam); LuaPushNamedNumber(L, "COBSCALE", COBSCALE); // load our libraries (LuaSyncedCtrl overrides some LuaUnsyncedCtrl entries) { #define KILL { KillLua(); return false; } if (!AddEntriesToTable(L, "VFS", LuaVFS::PushSynced )) KILL if (!AddEntriesToTable(L, "VFS", LuaZipFileReader::PushSynced )) KILL if (!AddEntriesToTable(L, "VFS", LuaZipFileWriter::PushSynced )) KILL if (!AddEntriesToTable(L, "UnitDefs", LuaUnitDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "WeaponDefs", LuaWeaponDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries )) KILL if (!AddEntriesToTable(L, "Script", LuaInterCall::PushEntriesSynced)) KILL if (!AddEntriesToTable(L, "Spring", LuaUnsyncedCtrl::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaSyncedCtrl::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaSyncedRead::PushEntries )) KILL if (!AddEntriesToTable(L, "Spring", LuaUICommand::PushEntries )) KILL if (!AddEntriesToTable(L, "Engine", LuaConstEngine::PushEntries )) KILL if (!AddEntriesToTable(L, "Game", LuaConstGame::PushEntries )) KILL if (!AddEntriesToTable(L, "CMD", LuaConstCMD::PushEntries )) KILL if (!AddEntriesToTable(L, "CMDTYPE", LuaConstCMDTYPE::PushEntries )) KILL if (!AddEntriesToTable(L, "COB", LuaConstCOB::PushEntries )) KILL if (!AddEntriesToTable(L, "SFX", LuaConstSFX::PushEntries )) KILL if (!AddEntriesToTable(L, "LOG", LuaUtils::PushLogEntries )) KILL #undef KILL } // add code from the sub-class if (!base.AddSyncedCode(L)) { KillLua(); return false; } lua_settop(L, 0); creg::AutoRegisterCFunctions(GetName(), L); if (!LoadCode(L, code, file)) { KillLua(); return false; } lua_settop(L, 0); eventHandler.AddClient(this); return true; } // // Call-Ins // bool CSyncedLuaHandle::SyncedActionFallback(const std::string& msg, int playerID) { string cmd = msg; const std::string::size_type pos = cmd.find_first_of(" \t"); if (pos != string::npos) cmd.resize(pos); if (textCommands.find(cmd) == textCommands.end()) return false; // strip the leading '/' return GotChatMsg(msg.substr(1), playerID); } bool CSyncedLuaHandle::CommandFallback(const CUnit* unit, const Command& cmd) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 9, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined LuaUtils::PushUnitAndCommand(L, unit, cmd); // call the function if (!RunCallIn(L, cmdStr, 7, 1)) return true; const bool remove = luaL_optboolean(L, -1, true); lua_pop(L, 1); return remove; // return 'true' to remove the command } bool CSyncedLuaHandle::AllowCommand(const CUnit* unit, const Command& cmd, int playerNum, bool fromSynced, bool fromLua) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 7 + 3, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined const int argc = LuaUtils::PushUnitAndCommand(L, unit, cmd); lua_pushnumber(L, playerNum); lua_pushboolean(L, fromSynced); lua_pushboolean(L, fromLua); // call the function if (!RunCallIn(L, cmdStr, argc + 3, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitCreation( const UnitDef* unitDef, const CUnit* builder, const BuildInfo* buildInfo ) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 9, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, unitDef->id); lua_pushnumber(L, builder->id); lua_pushnumber(L, builder->team); if (buildInfo != nullptr) { lua_pushnumber(L, buildInfo->pos.x); lua_pushnumber(L, buildInfo->pos.y); lua_pushnumber(L, buildInfo->pos.z); lua_pushnumber(L, buildInfo->buildFacing); } // call the function if (!RunCallIn(L, cmdStr, (buildInfo != nullptr)? 7 : 3, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitTransfer(const CUnit* unit, int newTeam, bool capture) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 7, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, unit->team); lua_pushnumber(L, newTeam); lua_pushboolean(L, capture); // call the function if (!RunCallIn(L, cmdStr, 5, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitBuildStep(const CUnit* builder, const CUnit* unit, float part) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 7, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, builder->id); lua_pushnumber(L, builder->team); lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, part); // call the function if (!RunCallIn(L, cmdStr, 5, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitTransport(const CUnit* transporter, const CUnit* transportee) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 6, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; lua_pushnumber(L, transporter->id); lua_pushnumber(L, transporter->unitDef->id); lua_pushnumber(L, transporter->team); lua_pushnumber(L, transportee->id); lua_pushnumber(L, transportee->unitDef->id); lua_pushnumber(L, transportee->team); if (!RunCallIn(L, cmdStr, 6, 1)) return true; const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitTransportLoad( const CUnit* transporter, const CUnit* transportee, const float3& loadPos, bool allowed ) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 9, __func__); static const LuaHashString cmdStr(__func__); // use engine default if callin does not exist if (!cmdStr.GetGlobalFunc(L)) return allowed; lua_pushnumber(L, transporter->id); lua_pushnumber(L, transporter->unitDef->id); lua_pushnumber(L, transporter->team); lua_pushnumber(L, transportee->id); lua_pushnumber(L, transportee->unitDef->id); lua_pushnumber(L, transportee->team); lua_pushnumber(L, loadPos.x); lua_pushnumber(L, loadPos.y); lua_pushnumber(L, loadPos.z); if (!RunCallIn(L, cmdStr, 9, 1)) return true; // ditto if it does but returns nothing const bool allow = luaL_optboolean(L, -1, allowed); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitTransportUnload( const CUnit* transporter, const CUnit* transportee, const float3& unloadPos, bool allowed ) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 9, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return allowed; lua_pushnumber(L, transporter->id); lua_pushnumber(L, transporter->unitDef->id); lua_pushnumber(L, transporter->team); lua_pushnumber(L, transportee->id); lua_pushnumber(L, transportee->unitDef->id); lua_pushnumber(L, transportee->team); lua_pushnumber(L, unloadPos.x); lua_pushnumber(L, unloadPos.y); lua_pushnumber(L, unloadPos.z); if (!RunCallIn(L, cmdStr, 9, 1)) return true; const bool allow = luaL_optboolean(L, -1, allowed); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitCloak(const CUnit* unit, const CUnit* enemy) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 2, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; lua_pushnumber(L, unit->id); if (enemy != nullptr) lua_pushnumber(L, enemy->id); else lua_pushnil(L); if (!RunCallIn(L, cmdStr, 2, 1)) return true; const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitDecloak(const CUnit* unit, const CSolidObject* object, const CWeapon* weapon) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 3, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; lua_pushnumber(L, unit->id); if (object != nullptr) lua_pushnumber(L, object->id); else lua_pushnil(L); if (weapon != nullptr) lua_pushnumber(L, weapon->weaponNum); else lua_pushnil(L); if (!RunCallIn(L, cmdStr, 3, 1)) return true; assert(lua_isboolean(L, -1)); const bool allow = lua_toboolean(L, -1); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowUnitKamikaze(const CUnit* unit, const CUnit* target, bool allowed) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 2, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return allowed; lua_pushnumber(L, unit->id); lua_pushnumber(L, target->id); if (!RunCallIn(L, cmdStr, 2, 1)) return true; const bool allow = luaL_optboolean(L, -1, allowed); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowFeatureCreation(const FeatureDef* featureDef, int teamID, const float3& pos) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 7, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, featureDef->id); lua_pushnumber(L, teamID); lua_pushnumber(L, pos.x); lua_pushnumber(L, pos.y); lua_pushnumber(L, pos.z); // call the function if (!RunCallIn(L, cmdStr, 5, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowFeatureBuildStep(const CUnit* builder, const CFeature* feature, float part) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 7, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, builder->id); lua_pushnumber(L, builder->team); lua_pushnumber(L, feature->id); lua_pushnumber(L, feature->def->id); lua_pushnumber(L, part); // call the function if (!RunCallIn(L, cmdStr, 5, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowResourceLevel(int teamID, const std::string& type, float level) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 5, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, teamID); lua_pushsstring(L, type); lua_pushnumber(L, level); // call the function if (!RunCallIn(L, cmdStr, 3, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowResourceTransfer(int oldTeam, int newTeam, const char* type, float amount) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 6, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, oldTeam); lua_pushnumber(L, newTeam); lua_pushstring(L, type); lua_pushnumber(L, amount); // call the function if (!RunCallIn(L, cmdStr, 4, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowDirectUnitControl(int playerID, const CUnit* unit) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 6, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, unit->team); lua_pushnumber(L, playerID); // call the function if (!RunCallIn(L, cmdStr, 4, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowBuilderHoldFire(const CUnit* unit, int action) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 3 + 1, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, action); // call the function if (!RunCallIn(L, cmdStr, 3, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::AllowStartPosition(int playerID, int teamID, unsigned char readyState, const float3& clampedPos, const float3& rawPickPos) { LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 13, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return true; // the call is not defined // push the start position and playerID lua_pushnumber(L, playerID); lua_pushnumber(L, teamID); lua_pushnumber(L, readyState); lua_pushnumber(L, clampedPos.x); lua_pushnumber(L, clampedPos.y); lua_pushnumber(L, clampedPos.z); lua_pushnumber(L, rawPickPos.x); lua_pushnumber(L, rawPickPos.y); lua_pushnumber(L, rawPickPos.z); // call the function if (!RunCallIn(L, cmdStr, 9, 1)) return true; // get the results const bool allow = luaL_optboolean(L, -1, true); lua_pop(L, 1); return allow; } bool CSyncedLuaHandle::MoveCtrlNotify(const CUnit* unit, int data) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 6, __func__); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; // the call is not defined // push the unit info lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, unit->team); lua_pushnumber(L, data); // call the function if (!RunCallIn(L, cmdStr, 4, 1)) return false; // get the results const bool disable = luaL_optboolean(L, -1, false); lua_pop(L, 1); return disable; } bool CSyncedLuaHandle::TerraformComplete(const CUnit* unit, const CUnit* build) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 8, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; // the call is not defined // push the unit info lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, unit->team); // push the construction info lua_pushnumber(L, build->id); lua_pushnumber(L, build->unitDef->id); lua_pushnumber(L, build->team); // call the function if (!RunCallInTraceback(L, cmdStr, 6, 1, dbgTrace.GetErrFuncIdx(), false)) return false; // get the results const bool stop = luaL_optboolean(L, -1, false); lua_pop(L, 1); return stop; } /** * called after every damage modification (even HitByWeaponId) * but before the damage is applied * * expects two numbers returned by lua code: * 1st is stored under *newDamage if newDamage != NULL * 2nd is stored under *impulseMult if impulseMult != NULL */ bool CSyncedLuaHandle::UnitPreDamaged( const CUnit* unit, const CUnit* attacker, float damage, int weaponDefID, int projectileID, bool paralyzer, float* newDamage, float* impulseMult ) { LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 2 + 2 + 10, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; int inArgCount = 5; int outArgCount = 2; lua_pushnumber(L, unit->id); lua_pushnumber(L, unit->unitDef->id); lua_pushnumber(L, unit->team); lua_pushnumber(L, damage); lua_pushboolean(L, paralyzer); //FIXME pass impulse too? if (GetHandleFullRead(L)) { lua_pushnumber(L, weaponDefID); inArgCount += 1; lua_pushnumber(L, projectileID); inArgCount += 1; if (attacker != nullptr) { lua_pushnumber(L, attacker->id); lua_pushnumber(L, attacker->unitDef->id); lua_pushnumber(L, attacker->team); inArgCount += 3; } } // call the routine // NOTE: // RunCallInTraceback removes the error-handler by default // this has to be disabled when using ScopedDebugTraceBack // or it would mess up the stack if (!RunCallInTraceback(L, cmdStr, inArgCount, outArgCount, dbgTrace.GetErrFuncIdx(), false)) return false; assert(newDamage != nullptr); assert(impulseMult != nullptr); if (lua_isnumber(L, -2)) { *newDamage = lua_tonumber(L, -2); } else if (!lua_isnumber(L, -2) || lua_isnil(L, -2)) { // first value is obligatory, so may not be nil LOG_L(L_WARNING, "%s(): 1st return-value should be a number (newDamage)", cmdStr.GetString()); } if (lua_isnumber(L, -1)) { *impulseMult = lua_tonumber(L, -1); } else if (!lua_isnumber(L, -1) && !lua_isnil(L, -1)) { // second value is optional, so nils are OK LOG_L(L_WARNING, "%s(): 2nd return-value should be a number (impulseMult)", cmdStr.GetString()); } lua_pop(L, outArgCount); // returns true to disable engine dmg handling return (*newDamage == 0.0f && *impulseMult == 0.0f); } bool CSyncedLuaHandle::FeaturePreDamaged( const CFeature* feature, const CUnit* attacker, float damage, int weaponDefID, int projectileID, float* newDamage, float* impulseMult ) { assert(newDamage != nullptr); assert(impulseMult != nullptr); LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 2 + 9 + 2, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; int inArgCount = 4; int outArgCount = 2; lua_pushnumber(L, feature->id); lua_pushnumber(L, feature->def->id); lua_pushnumber(L, feature->team); lua_pushnumber(L, damage); if (GetHandleFullRead(L)) { lua_pushnumber(L, weaponDefID); inArgCount += 1; lua_pushnumber(L, projectileID); inArgCount += 1; if (attacker != nullptr) { lua_pushnumber(L, attacker->id); lua_pushnumber(L, attacker->unitDef->id); lua_pushnumber(L, attacker->team); inArgCount += 3; } } // call the routine if (!RunCallInTraceback(L, cmdStr, inArgCount, outArgCount, dbgTrace.GetErrFuncIdx(), false)) return false; if (lua_isnumber(L, -2)) { *newDamage = lua_tonumber(L, -2); } else if (!lua_isnumber(L, -2) || lua_isnil(L, -2)) { // first value is obligatory, so may not be nil LOG_L(L_WARNING, "%s(): 1st value returned should be a number (newDamage)", cmdStr.GetString()); } if (lua_isnumber(L, -1)) { *impulseMult = lua_tonumber(L, -1); } else if (!lua_isnumber(L, -1) && !lua_isnil(L, -1)) { // second value is optional, so nils are OK LOG_L(L_WARNING, "%s(): 2nd value returned should be a number (impulseMult)", cmdStr.GetString()); } lua_pop(L, outArgCount); // returns true to disable engine dmg handling return (*newDamage == 0.0f && *impulseMult == 0.0f); } bool CSyncedLuaHandle::ShieldPreDamaged( const CProjectile* projectile, const CWeapon* shieldEmitter, const CUnit* shieldCarrier, bool bounceProjectile, const CWeapon* beamEmitter, const CUnit* beamCarrier, const float3& startPos, const float3& hitPos ) { assert((projectile != nullptr) || ((beamEmitter != nullptr) && (beamCarrier != nullptr))); LUA_CALL_IN_CHECK(L, false); luaL_checkstack(L, 2 + 7 + 1, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return false; // push the call-in arguments if (projectile != nullptr) { // Regular projectiles lua_pushnumber(L, projectile->id); lua_pushnumber(L, projectile->GetOwnerID()); lua_pushnumber(L, shieldEmitter->weaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, shieldCarrier->id); lua_pushboolean(L, bounceProjectile); lua_pushnil(L); lua_pushnil(L); } else { // Beam projectiles lua_pushnumber(L, -1); lua_pushnumber(L, -1); lua_pushnumber(L, shieldEmitter->weaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, shieldCarrier->id); lua_pushboolean(L, bounceProjectile); lua_pushnumber(L, beamEmitter->weaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, beamCarrier->id); } lua_pushnumber(L, startPos.x); lua_pushnumber(L, startPos.y); lua_pushnumber(L, startPos.z); lua_pushnumber(L, hitPos.x); lua_pushnumber(L, hitPos.y); lua_pushnumber(L, hitPos.z); // call the routine if (!RunCallInTraceback(L, cmdStr, 13, 1, dbgTrace.GetErrFuncIdx(), false)) return false; // pop the return-value; must be true or false const bool ret = luaL_optboolean(L, -1, false); lua_pop(L, 1); return ret; } int CSyncedLuaHandle::AllowWeaponTargetCheck(unsigned int attackerID, unsigned int attackerWeaponNum, unsigned int attackerWeaponDefID) { int ret = -1; if (!watchAllowTargetDefs[attackerWeaponDefID]) return ret; LUA_CALL_IN_CHECK(L, -1); luaL_checkstack(L, 2 + 3 + 1, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return ret; lua_pushnumber(L, attackerID); lua_pushnumber(L, attackerWeaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, attackerWeaponDefID); if (!RunCallInTraceback(L, cmdStr, 3, 1, dbgTrace.GetErrFuncIdx(), false)) return ret; ret = lua_toint(L, -1); lua_pop(L, 1); return ret; } bool CSyncedLuaHandle::AllowWeaponTarget( unsigned int attackerID, unsigned int targetID, unsigned int attackerWeaponNum, unsigned int attackerWeaponDefID, float* targetPriority ) { bool ret = true; if (!watchAllowTargetDefs[attackerWeaponDefID]) return ret; LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 5 + 2, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return ret; // casts are only here to preserve -1's passed from *CAI as floats const int siTargetID = static_cast<int>(targetID); const int siAttackerWN = static_cast<int>(attackerWeaponNum); lua_pushnumber(L, attackerID); lua_pushnumber(L, siTargetID); lua_pushnumber(L, siAttackerWN + LUA_WEAPON_BASE_INDEX * (siAttackerWN >= 0)); lua_pushnumber(L, attackerWeaponDefID); if (targetPriority != nullptr) { // Weapon::AutoTarget lua_pushnumber(L, *targetPriority); } else { // {Air,Mobile}CAI::AutoGenerateTarget lua_pushnil(L); } if (!RunCallInTraceback(L, cmdStr, 5, 2, dbgTrace.GetErrFuncIdx(), false)) return ret; if (targetPriority != nullptr) *targetPriority = luaL_optnumber(L, -1, *targetPriority); ret = luaL_optboolean(L, -2, false); lua_pop(L, 2); return ret; } bool CSyncedLuaHandle::AllowWeaponInterceptTarget( const CUnit* interceptorUnit, const CWeapon* interceptorWeapon, const CProjectile* interceptorTarget ) { bool ret = true; if (!watchAllowTargetDefs[interceptorWeapon->weaponDef->id]) return ret; LUA_CALL_IN_CHECK(L, true); luaL_checkstack(L, 2 + 3 + 1, __func__); const LuaUtils::ScopedDebugTraceBack dbgTrace(L); static const LuaHashString cmdStr(__func__); if (!cmdStr.GetGlobalFunc(L)) return ret; lua_pushnumber(L, interceptorUnit->id); lua_pushnumber(L, interceptorWeapon->weaponNum + LUA_WEAPON_BASE_INDEX); lua_pushnumber(L, interceptorTarget->id); if (!RunCallInTraceback(L, cmdStr, 3, 1, dbgTrace.GetErrFuncIdx(), false)) return ret; ret = luaL_optboolean(L, -1, false); lua_pop(L, 1); return ret; } // // Call-Outs // int CSyncedLuaHandle::SyncedRandom(lua_State* L) { #if 0 spring_lua_synced_rand(L); return 1; #endif switch (lua_gettop(L)) { case 0: { lua_pushnumber(L, gsRNG.NextFloat()); return 1; } break; case 1: { if (lua_isnumber(L, 1)) { const int u = lua_toint(L, 1); if (u < 1) luaL_error(L, "error: too small upper limit (%d) given to math.random(), should be >= 1 {synced}", u); lua_pushnumber(L, 1 + gsRNG.NextInt(u)); return 1; } } break; case 2: { if (lua_isnumber(L, 1) && lua_isnumber(L, 2)) { const int lower = lua_toint(L, 1); const int upper = lua_toint(L, 2); if (lower > upper) luaL_error(L, "Empty interval in math.random() {synced}"); const float diff = (upper - lower); const float r = gsRNG.NextFloat(); // [0,1], not [0,1) ? lua_pushnumber(L, Clamp(lower + int(r * (diff + 1)), lower, upper)); return 1; } } break; default: { } break; } luaL_error(L, "Incorrect arguments to math.random() {synced}"); return 0; } int CSyncedLuaHandle::SyncedRandomSeed(lua_State* L) { gsRNG.SetSeed(luaL_checkint(L, -1), false); return 0; } int CSyncedLuaHandle::SyncedNext(lua_State* L) { constexpr int whiteList[] = { LUA_TSTRING, LUA_TNUMBER, LUA_TBOOLEAN, LUA_TNIL, LUA_TTHREAD //FIXME LUA_TTHREAD is normally _not_ synced safe but LUS handler needs it atm (and uses it in a safe way) }; const CSyncedLuaHandle* slh = GetSyncedHandle(L); assert(slh->origNextRef > 0); const int oldTop = lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, slh->origNextRef); lua_pushvalue(L, 1); if (oldTop >= 2) { lua_pushvalue(L, 2); } else { lua_pushnil(L); } lua_call(L, 2, LUA_MULTRET); const int retCount = lua_gettop(L) - oldTop; assert(retCount == 1 || retCount == 2); if (retCount >= 2) { const int keyType = lua_type(L, -2); const auto it = std::find(std::begin(whiteList), std::end(whiteList), keyType); if (it == std::end(whiteList)) { if (LuaUtils::PushDebugTraceback(L) > 0) { lua_pushfstring(L, "Iterating a table with keys of type \"%s\" in synced context!", lua_typename(L, keyType)); lua_call(L, 1, 1); const auto* errMsg = lua_tostring(L, -1); LOG_L(L_WARNING, "%s", errMsg); } lua_pop(L, 1); // either nil or the errMsg } } return retCount; } int CSyncedLuaHandle::SyncedPairs(lua_State* L) { /* copied from lbaselib.cpp */ luaL_checktype(L, 1, LUA_TTABLE); lua_pushcfunction(L, SyncedNext); /* return generator, */ lua_pushvalue(L, 1); /* state, */ lua_pushnil(L); /* and initial value */ return 3; } int CSyncedLuaHandle::SendToUnsynced(lua_State* L) { const int args = lua_gettop(L); if (args <= 0) { luaL_error(L, "Incorrect arguments to SendToUnsynced()"); } static const int supportedTypes = (1 << LUA_TNIL) | (1 << LUA_TBOOLEAN) | (1 << LUA_TNUMBER) | (1 << LUA_TSTRING) ; for (int i = 1; i <= args; i++) { const int t = (1 << lua_type(L, i)); if (!(t & supportedTypes)) { luaL_error(L, "Incorrect data type for SendToUnsynced(), arg %d", i); } } CUnsyncedLuaHandle* ulh = CSplitLuaHandle::GetUnsyncedHandle(L); ulh->RecvFromSynced(L, args); return 0; } int CSyncedLuaHandle::AddSyncedActionFallback(lua_State* L) { std::string cmdRaw = "/" + std::string(luaL_checkstring(L, 1)); std::string cmd = cmdRaw; const std::string::size_type pos = cmdRaw.find_first_of(" \t"); if (pos != string::npos) cmd.resize(pos); if (cmd.empty()) { lua_pushboolean(L, false); return 1; } auto lhs = GetSyncedHandle(L); lhs->textCommands[cmd] = luaL_checkstring(L, 2); wordCompletion.AddWord(cmdRaw, true, false, false); lua_pushboolean(L, true); return 1; } int CSyncedLuaHandle::RemoveSyncedActionFallback(lua_State* L) { //TODO move to LuaHandle std::string cmdRaw = "/" + std::string(luaL_checkstring(L, 1)); std::string cmd = cmdRaw; const std::string::size_type pos = cmdRaw.find_first_of(" \t"); if (pos != string::npos) cmd.resize(pos); if (cmd.empty()) { lua_pushboolean(L, false); return 1; } auto lhs = GetSyncedHandle(L); auto& cmds = lhs->textCommands; const auto it = cmds.find(cmd); if (it != cmds.end()) { cmds.erase(it); wordCompletion.RemoveWord(cmdRaw); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } #define GetWatchDef(DefType) \ int CSyncedLuaHandle::GetWatch ## DefType ## Def(lua_State* L) { \ const CSyncedLuaHandle* lhs = GetSyncedHandle(L); \ const auto& vec = lhs->watch ## DefType ## Defs; \ \ const uint32_t defIdx = luaL_checkint(L, 1); \ \ if ((defIdx == -1u) && (&vec == &lhs->watchProjectileDefs)) { \ lua_pushboolean(L, vec[vec.size() - 1]); \ return 1; \ } \ \ if (defIdx >= vec.size()) \ return 0; \ \ lua_pushboolean(L, vec[defIdx]); \ return 1; \ } #define SetWatchDef(DefType) \ int CSyncedLuaHandle::SetWatch ## DefType ## Def(lua_State* L) { \ CSyncedLuaHandle* lhs = GetSyncedHandle(L); \ auto& vec = lhs->watch ## DefType ## Defs; \ \ const uint32_t defIdx = luaL_checkint(L, 1); \ \ if ((defIdx == -1u) && (&vec == &lhs->watchProjectileDefs)) { \ vec[vec.size() - 1] = luaL_checkboolean(L, 2); \ return 0; \ } \ \ if (defIdx >= vec.size()) \ return 0; \ \ vec[defIdx] = luaL_checkboolean(L, 2); \ return 0; \ } int CSyncedLuaHandle::GetWatchWeaponDef(lua_State* L) { bool watched = false; // trickery to keep Script.GetWatchWeapon backward-compatible { GetWatchExplosionDef(L); watched |= luaL_checkboolean(L, -1); lua_pop(L, 1); } { GetWatchProjectileDef(L); watched |= luaL_checkboolean(L, -1); lua_pop(L, 1); } { GetWatchAllowTargetDef(L); watched |= luaL_checkboolean(L, -1); lua_pop(L, 1); } lua_pushboolean(L, watched); return 1; } GetWatchDef(Unit) GetWatchDef(Feature) GetWatchDef(Explosion) GetWatchDef(Projectile) GetWatchDef(AllowTarget) SetWatchDef(Unit) SetWatchDef(Feature) SetWatchDef(Explosion) SetWatchDef(Projectile) SetWatchDef(AllowTarget) #undef GetWatchDef #undef SetWatchDef /******************************************************************************/ /******************************************************************************/ // ###### ## ## ### ######## ######## ######## // ## ## ## ## ## ## ## ## ## ## ## // ## ## ## ## ## ## ## ## ## ## // ###### ######### ## ## ######## ###### ## ## // ## ## ## ######### ## ## ## ## ## // ## ## ## ## ## ## ## ## ## ## ## // ###### ## ## ## ## ## ## ######## ######## CSplitLuaHandle::CSplitLuaHandle(const std::string& _name, int _order) : syncedLuaHandle(this, _name, _order) , unsyncedLuaHandle(this, _name, _order + 1) { } CSplitLuaHandle::~CSplitLuaHandle() { // must be called before their dtors!!! syncedLuaHandle.KillLua(); unsyncedLuaHandle.KillLua(); } bool CSplitLuaHandle::InitSynced() { if (!IsValid()) { KillLua(); return false; } const std::string syncedCode = LoadFile(GetSyncedFileName(), GetInitFileModes()); if (syncedCode.empty()) { KillLua(); return false; } const bool haveSynced = syncedLuaHandle.Init(syncedCode, GetUnsyncedFileName()); if (!IsValid() || !haveSynced) { KillLua(); return false; } syncedLuaHandle.CheckStack(); return true; } bool CSplitLuaHandle::InitUnsynced() { if (!IsValid()) { KillLua(); return false; } const std::string unsyncedCode = LoadFile(GetUnsyncedFileName(), GetInitFileModes()); if (unsyncedCode.empty()) { KillLua(); return false; } const bool haveUnsynced = unsyncedLuaHandle.Init(unsyncedCode, GetUnsyncedFileName()); if (!IsValid() || !haveUnsynced) { KillLua(); return false; } unsyncedLuaHandle.CheckStack(); return true; } bool CSplitLuaHandle::Init(bool onlySynced) { SetFullCtrl(true); SetFullRead(true); SetCtrlTeam(CEventClient::AllAccessTeam); SetReadTeam(CEventClient::AllAccessTeam); SetReadAllyTeam(CEventClient::AllAccessTeam); SetSelectTeam(GetInitSelectTeam()); return InitSynced() && (onlySynced || InitUnsynced()); } bool CSplitLuaHandle::FreeUnsynced() { if (!unsyncedLuaHandle.IsValid()) return false; unsyncedLuaHandle.KillLua(); unsyncedLuaHandle.~CUnsyncedLuaHandle(); return true; } bool CSplitLuaHandle::LoadUnsynced() { ::new (&unsyncedLuaHandle) CUnsyncedLuaHandle(this, syncedLuaHandle.GetName(), syncedLuaHandle.GetOrder() + 1); if (!unsyncedLuaHandle.IsValid()) { unsyncedLuaHandle.KillLua(); return false; } return InitUnsynced(); } bool CSplitLuaHandle::SwapSyncedHandle(lua_State* L, lua_State* L_GC) { LUA_CLOSE(&syncedLuaHandle.L); syncedLuaHandle.SetLuaStates(L, L_GC); return IsValid(); } string CSplitLuaHandle::LoadFile(const std::string& filename, const std::string& modes) const { string vfsModes(modes); if (CSyncedLuaHandle::devMode) vfsModes = SPRING_VFS_RAW + vfsModes; CFileHandler f(filename, vfsModes); string code; if (!f.LoadStringData(code)) code.clear(); return code; } // // Call-Outs // int CSplitLuaHandle::LoadStringData(lua_State* L) { size_t len; const char *str = luaL_checklstring(L, 1, &len); const char *chunkname = luaL_optstring(L, 2, str); if (luaL_loadbuffer(L, str, len, chunkname) != 0) { lua_pushnil(L); lua_insert(L, -2); return 2; // nil, then the error message } // set the chunk's fenv to the current fenv if (lua_istable(L, 3)) { lua_pushvalue(L, 3); } else { LuaUtils::PushCurrentFuncEnv(L, __func__); } if (lua_setfenv(L, -2) == 0) luaL_error(L, "[%s] error with setfenv", __func__); return 1; } int CSplitLuaHandle::CallAsTeam(lua_State* L) { const int args = lua_gettop(L); if ((args < 2) || !lua_isfunction(L, 2)) luaL_error(L, "[%s] incorrect arguments", __func__); // save the current access const bool prevFullCtrl = CLuaHandle::GetHandleFullCtrl(L); const bool prevFullRead = CLuaHandle::GetHandleFullRead(L); const int prevCtrlTeam = CLuaHandle::GetHandleCtrlTeam(L); const int prevReadTeam = CLuaHandle::GetHandleReadTeam(L); const int prevReadAllyTeam = CLuaHandle::GetHandleReadAllyTeam(L); const int prevSelectTeam = CLuaHandle::GetHandleSelectTeam(L); // parse the new access if (lua_isnumber(L, 1)) { const int teamID = lua_toint(L, 1); if ((teamID < CEventClient::MinSpecialTeam) || (teamID >= teamHandler.ActiveTeams())) luaL_error(L, "[%s] bad teamID %d", __func__, teamID); // ctrl CLuaHandle::SetHandleCtrlTeam(L, teamID); CLuaHandle::SetHandleFullCtrl(L, teamID == CEventClient::AllAccessTeam); // read CLuaHandle::SetHandleReadTeam(L, teamID); CLuaHandle::SetHandleReadAllyTeam(L, (teamID < 0) ? teamID : teamHandler.AllyTeam(teamID)); CLuaHandle::SetHandleFullRead(L, teamID == CEventClient::AllAccessTeam); // select CLuaHandle::SetHandleSelectTeam(L, teamID); } else if (lua_istable(L, 1)) { const int table = 1; for (lua_pushnil(L); lua_next(L, table) != 0; lua_pop(L, 1)) { if (!lua_israwstring(L, -2) || !lua_isnumber(L, -1)) continue; const int teamID = lua_toint(L, -1); if ((teamID < CEventClient::MinSpecialTeam) || (teamID >= teamHandler.ActiveTeams())) luaL_error(L, "[%s] bad teamID %d", __func__, teamID); switch (hashString(lua_tostring(L, -2))) { case hashString("ctrl"): { CLuaHandle::SetHandleCtrlTeam(L, teamID); CLuaHandle::SetHandleFullCtrl(L, teamID == CEventClient::AllAccessTeam); } break; case hashString("read"): { CLuaHandle::SetHandleReadTeam(L, teamID); CLuaHandle::SetHandleReadAllyTeam(L, (teamID < 0) ? teamID : teamHandler.AllyTeam(teamID)); CLuaHandle::SetHandleFullRead(L, teamID == CEventClient::AllAccessTeam); } break; case hashString("select"): { CLuaHandle::SetHandleSelectTeam(L, teamID); } break; } } } else { luaL_error(L, "Incorrect arguments to CallAsTeam()"); } // call the function const int funcArgs = lua_gettop(L) - 2; // protected call so that the permissions are always reverted const int error = lua_pcall(L, funcArgs, LUA_MULTRET, 0); // revert the permissions CLuaHandle::SetHandleFullCtrl(L, prevFullCtrl); CLuaHandle::SetHandleFullRead(L, prevFullRead); CLuaHandle::SetHandleCtrlTeam(L, prevCtrlTeam); CLuaHandle::SetHandleReadTeam(L, prevReadTeam); CLuaHandle::SetHandleReadAllyTeam(L, prevReadAllyTeam); CLuaHandle::SetHandleSelectTeam(L, prevSelectTeam); if (error != 0) { LOG_L(L_ERROR, "[%s] error %i (%s)", __func__, error, lua_tostring(L, -1)); lua_error(L); } return lua_gettop(L) - 1; // the teamID/table is still on the stack } /******************************************************************************/ /******************************************************************************/
0
0.79038
1
0.79038
game-dev
MEDIA
0.950641
game-dev
0.614478
1
0.614478
Dimbreath/ArknightsData
1,406
ko-KR/gamedata/[uc]lua/hotfixes/storyreviewreshotfixer.lua
---@class StoryReviewResHotfixer:HotfixBase local eutil = CS.Torappu.Lua.Util local assetUtil = CS.Torappu.UI.UIAssetLoader local class2inject = CS.Torappu.UI.StoryReview.StoryReviewActivityItemView local StoryReviewResHotfixer = Class("StoryReviewResHotfixer",HotfixBase) local RES_PATH = "Arts/UI/StoryReview/Hubs/Common/replicate_point_hub.prefab" local function StoryReviewResReplace(self) print("in function") local hub = assetUtil.LoadPrefab(RES_PATH) local behavior = hub:GetComponent("SpriteHub") local ret, spriteRes = behavior:TryGetSprite("replicate_point") if spriteRes ~= nil then local img_ary = self._replicateMarkContainer:GetComponentsInChildren(typeof(CS.UnityEngine.UI.Image)) if img_ary.Length == 2 then local img = img_ary[1] if img ~= nil then img.sprite = spriteRes end end end end function StoryReviewResHotfixer:OnInit() self:Fix_ex(class2inject, "ApplyData", function(self, chapterModel) self:ApplyData(chapterModel) local ok, error = xpcall(StoryReviewResReplace, debug.traceback,self) if not ok then eutil.LogError("[StoryReviewResHotfixer] fix error" .. error) end end) end function StoryReviewResHotfixer:OnDispose() xlua.hotfix(class2inject, "ApplyData", nil) end return StoryReviewResHotfixer
0
0.920712
1
0.920712
game-dev
MEDIA
0.838635
game-dev
0.888711
1
0.888711
PotRooms/StarResonanceData
11,481
lua/ui/view/camera_menu_container_action_view.lua
local UI = Z.UI local super = require("ui.ui_subview_base") local Camera_menu_container_actionView = class("Camera_menu_container_actionView", super) local camerasys_data = Z.DataMgr.Get("camerasys_data") function Camera_menu_container_actionView:ctor(parent) self.uiBinder = nil super.ctor(self, "camera_menu_container_action_sub", "photograph/camera_menu_container_action_sub", UI.ECacheLv.None) self.selectedTog_ = nil self.pressEffectItem = nil self.expressionClickTag_ = false self.parent_ = parent self.expressionVm_ = Z.VMMgr.GetVM("expression") self.commonVm_ = Z.VMMgr.GetVM("common") self.expressionData_ = Z.DataMgr.Get("expression_data") self.multActionData_ = Z.DataMgr.Get("multaction_data") self.multActionVm_ = Z.VMMgr.GetVM("multaction") self.viewData = nil self.itemData_ = {} end function Camera_menu_container_actionView:OnActive() self.uiBinder.Trans:SetOffsetMax(0, 0) self.uiBinder.Trans:SetOffsetMin(0, 0) self:BindLuaAttrWatchers() self:BindEvents() self:initUi() end function Camera_menu_container_actionView:initUi() self.uiBinder.Ref:SetVisible(self.uiBinder.btn_reset, self.viewData.OpenSourceType == E.ExpressionOpenSourceType.Camera) self:AddClick(self.uiBinder.btn_reset, function() self:btnReset() end) end function Camera_menu_container_actionView:btnReset(isNotResetEmote) self.expressionData_:SetCurPlayingId(-1) local logicExpressionType = self.expressionData_:GetLogicExpressionType() if logicExpressionType == E.ExpressionType.Action then Z.EventMgr:Dispatch(Z.ConstValue.Camera.ActionReset, self.viewData) elseif not isNotResetEmote then if self.viewData.ZModel then Z.ZAnimActionPlayMgr:ResetEmote(self.viewData.ZModel) else Z.ZAnimActionPlayMgr:ResetEmote() end end self:cancelSelect(false) end function Camera_menu_container_actionView:initEmoteData() local displayExpressionType = self.expressionData_:GetDisplayExpressionType() local isShowUnlockItem = self.viewData.OpenSourceType == E.ExpressionOpenSourceType.Expression local itemList = self.expressionVm_.GetExpressionShowDataByType(displayExpressionType, isShowUnlockItem) self.uiBinder.layout_center.AllowSwitchOff = true local togData = self.expressionData_:GetTabTableData() if not togData or not next(togData) then return end self.uiBinder.lab_name.text = togData[displayExpressionType + 1].name return itemList end function Camera_menu_container_actionView:UpdateListItem() local itemList itemList = self:initEmoteData() if not itemList then return end self:removeUnit() Z.CoroUtil.create_coro_xpcall(function() self:createItem(itemList) end)() end function Camera_menu_container_actionView:removeUnit() self:ClearAllUnits() end function Camera_menu_container_actionView:cancelSelect(isShow) if not isShow and self.selectedTog_ then self.selectedTog_ = nil end end function Camera_menu_container_actionView:createItem(activeDates) if activeDates and next(activeDates) then local itemPath = self.uiBinder.prefabCache:GetString("settingActionItemPath") for k, v in pairs(activeDates) do self:loadShowPieceUnit(k, v, itemPath) end end self.uiBinder.layout_active:ForceRebuildLayoutImmediate() end function Camera_menu_container_actionView:loadShowPieceUnit(index, emoteData, itemPath) if self.viewData == E.ExpressionOpenSourceType.Camera and emoteData.activeType ~= E.ExpressionState.Active then return end local name = string.format("active%s", index) local item = self:AsyncLoadUiUnit(itemPath, name, self.uiBinder.node_active) self:setItemData(item, emoteData, name) end function Camera_menu_container_actionView:setItemData(item, data, name) item.Ref:SetVisible(item.img_lock, false) item.Ref:SetVisible(item.img_btn_emoji_bg, true) item.Ref:SetVisible(item.img_select, false) local actionId = data.tableData.Id if data.tableData.Type == E.ExpressionType.Action then if data.UnlockItem and data.UnlockItem ~= 0 then Z.RedPointMgr.LoadRedDotItem(E.RedType.ExpressionMain .. E.ItemType.ActionExpression .. data.tableData.EmoteType .. data.UnlockItem, self, item.Trans) end Z.GuideMgr:SetSteerIdByComp(item.camera_setting_action_item, E.DynamicSteerType.ExpressionId, actionId) end self:setTogPress(item, data, actionId) local itemBgPath = self.uiBinder.prefabCache:GetString("itemBgPath") local isActive = "_off" if data.activeType ~= E.ExpressionState.Active then isActive = "_off" item.Ref:SetVisible(item.img_lock, true) item.Ref:SetVisible(item.img_btn_emoji_bg, false) self:changeItemAlpha(item, 0.2) else self:changeItemAlpha(item, 1) end item.img_emoji:SetImage(data.tableData.Icon) if data.tableData.Type == E.ExpressionType.Action then local cornerMark = data.tableData.CornerMark for i = 1, 3 do item.Ref:SetVisible(item["img_emoji_corner_" .. i], i == cornerMark) end else for i = 1, 3 do item.Ref:SetVisible(item["img_emoji_corner_" .. i], false) end end item.img_btn_emoji_bg:SetImage(string.format("%s%s", itemBgPath, isActive)) end function Camera_menu_container_actionView:changeItemAlpha(item, alphaValue) if not item or not alphaValue then return end item.img_emoji:SetColor(Color.New(item.img_emoji.color.r, item.img_emoji.color.g, item.img_emoji.color.b, alphaValue)) end function Camera_menu_container_actionView:setTogPress(item, data, actionId) self:AddClick(item.btn_select, function() if Z.EntityMgr.PlayerEnt then local stateId = Z.EntityMgr.PlayerEnt:GetLuaLocalAttrState() local canPlayAction = self.expressionVm_.CanPlayActionCheck(stateId) local canUse = Z.StatusSwitchMgr:CheckSwitchEnable(Z.EStatusSwitch.ActorStateAction) if not canPlayAction or not canUse then Z.TipsVM.ShowTips(1000028) return end end self.selectedTog_ = item if data.activeType == E.ExpressionState.Active then self:play(data.tableData) self.expressionVm_.OpenTipsActionNamePopup(item.Trans, data.tableData.Name) else self.expressionVm_.InitExpressionItemData(data, item.Trans, actionId) end end) item.btn_select.OnLongPressEvent:RemoveAllListeners() if data.activeType == E.ExpressionState.Active and data.tableData.Type == E.ExpressionType.Action then self:EventAddAsyncListener(item.btn_select.OnLongPressEvent, function() local tipsState = E.ExpressionCommonTipsState.Add local isAdd = true if self.expressionVm_.CheckIsHadCommonData(data.tableData.Type, actionId) then isAdd = false tipsState = E.ExpressionCommonTipsState.Remove end self.expressionData_:SetCommonTipsInfo(tipsState, data.tableData.Type, actionId, isAdd) Z.EventMgr:Dispatch(Z.ConstValue.Expression.ShowExpressionTipList, item.Trans) end, nil, nil) end end function Camera_menu_container_actionView:play(emoteCfg) local expressionData = Z.DataMgr.Get("expression_data") local sourceType = self.viewData.OpenSourceType local cfgId = emoteCfg.Id expressionData:SetCurPlayingId(cfgId) if sourceType == E.ExpressionOpenSourceType.Camera then if emoteCfg.Type == E.ExpressionType.Action then Z.EventMgr:Dispatch(Z.ConstValue.Camera.DecorateLayerDown) end local isShowSlider = false if emoteCfg.Type ~= E.ExpressionType.Emote then isShowSlider = true end self.expressionVm_.ExpressionSinglePlay(self.viewData) Z.EventMgr:Dispatch(Z.ConstValue.Camera.ExpressionPlaySlider, isShowSlider) self.parent_.uiBinder.Ref:SetVisible(self.parent_.uiBinder.node_action_slider_container, isShowSlider) elseif sourceType == E.ExpressionOpenSourceType.Expression then if emoteCfg.Type == E.ExpressionType.Action then self.expressionClickTag_ = true self.expressionVm_.PlayAction(cfgId, true, true) Z.EventMgr:Dispatch(Z.ConstValue.Expression.ClickAction, cfgId) elseif emoteCfg.Type == E.ExpressionType.Emote then local emoteId = self.expressionVm_.FacialIdConversion(cfgId) if not emoteId then return end self.expressionVm_.PlayEmote(cfgId, emoteId, true, true) Z.EventMgr:Dispatch(Z.ConstValue.Expression.ClickEmotion, cfgId) else self.multActionVm_.PlayMultAction(emoteCfg.Emote[2], self.cancelSource) end end end function Camera_menu_container_actionView:OnDeActive() self.selectedTog_ = nil if self.playerPosWatcher ~= nil then self.playerPosWatcher:Dispose() self.playerPosWatcher = nil end if self.playerStateWatcher ~= nil then self.playerStateWatcher:Dispose() self.playerStateWatcher = nil end Z.ContainerMgr.CharSerialize.showPieceData.Watcher:UnregWatcher(self.unlockTypeListChange) self.unlockTypeListChange = nil self.playerPosWatcher = nil self:btnReset(true) self.expressionVm_.CloseTitleContentItemsBtn() end function Camera_menu_container_actionView:RestSelectedTog() self.selectedTog_ = nil end function Camera_menu_container_actionView:BindEvents() Z.EventMgr:Add(Z.ConstValue.Camera.SetActionSliderHide, self.setActionSliderVisible, self) end function Camera_menu_container_actionView:setActionSliderVisible(isShow) if not self.parent_ or self.viewData ~= E.ExpressionOpenSourceType.Camera then return end if not self.selectedTog_ or self.expressionData_:GetLogicExpressionType() ~= E.ExpressionType.Action or not self.uiBinder.Ref.UIComp.IsVisible then return end self.parent_.uiBinder.Ref:SetVisible(self.parent_.uiBinder.node_action_slider_container, isShow) end function Camera_menu_container_actionView:BindLuaAttrWatchers() if Z.EntityMgr.PlayerEnt ~= nil then self.playerPosWatcher = Z.DIServiceMgr.PlayerAttrComponentWatcherService:OnAttrVirtualPosChanged(function() self:updatePosEvent() end) self.playerStateWatcher = Z.DIServiceMgr.PlayerAttrStateComponentWatcherService:OnLocalAttrStateChanged(function() self:onPlayerStateChange() end) end function self.unlockTypeListChange(container, dirty) if dirty.unlockTypeList and self.expressionData_:GetLogicExpressionType() == E.ExpressionType.Action then self:UpdateListItem() end end Z.ContainerMgr.CharSerialize.showPieceData.Watcher:RegWatcher(self.unlockTypeListChange) end function Camera_menu_container_actionView:updatePosEvent() if self.selectedTog_ then self.selectedTog_ = nil end self.expressionClickTag_ = false if self.selectedTog_ then self:btnReset(true) end end function Camera_menu_container_actionView:onPlayerStateChange() if Z.EntityMgr.PlayerEnt == nil then logError("PlayerEnt is nil") return end local stateId = Z.EntityMgr.PlayerEnt:GetLuaAttrState() if stateId ~= Z.PbEnum("EActorState", "ActorStateDefault") and stateId ~= Z.PbEnum("EActorState", "ActorStateAction") then if not self.expressionClickTag_ and self.selectedTog_ then self.selectedTog_ = nil end self.expressionClickTag_ = false end end function Camera_menu_container_actionView:OnRefresh() self.togs_ = {} self:UpdateListItem() if self.expressionData_:GetLogicExpressionType() == E.ExpressionType.Action and not camerasys_data.IsDecorateAddViewSliderShow and self.expressionData_:GetCurPlayingEmotTableRow() ~= nil then self.parent_.uiBinder.Ref:SetVisible(self.parent_.uiBinder.node_action_slider_container, true) end end return Camera_menu_container_actionView
0
0.967395
1
0.967395
game-dev
MEDIA
0.375294
game-dev
0.982251
1
0.982251
SkriptLang/Skript
2,350
src/main/java/ch/njol/skript/events/EvtEntityTransform.java
package ch.njol.skript.events; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityTransformEvent; import org.bukkit.event.entity.EntityTransformEvent.TransformReason; import org.jetbrains.annotations.Nullable; import ch.njol.skript.Skript; import ch.njol.skript.entity.EntityData; import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; public class EvtEntityTransform extends SkriptEvent { static { Skript.registerEvent("Entity Transform", EvtEntityTransform.class, EntityTransformEvent.class, "(entit(y|ies)|%*-entitydatas%) transform[ing] [due to %-transformreasons%]") .description("Called when an entity is about to be replaced by another entity.", "Examples when it's called include; when a zombie gets cured and a villager spawns, " + "an entity drowns in water like a zombie that turns to a drown, " + "an entity that gets frozen in powder snow, " + "a mooshroom that when sheared, spawns a new cow.") .examples("on a zombie transforming due to curing:", "on mooshroom transforming:", "on zombie, skeleton or slime transform:") .keywords("entity transform") .since("2.8.0"); } @Nullable private Literal<TransformReason> reasons; @Nullable private Literal<EntityData<?>> datas; @Override @SuppressWarnings("unchecked") public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult) { datas = (Literal<EntityData<?>>) args[0]; reasons = (Literal<TransformReason>) args[1]; return true; } @Override public boolean check(Event event) { if (!(event instanceof EntityTransformEvent)) return false; EntityTransformEvent transformEvent = (EntityTransformEvent) event; if (reasons != null && !reasons.check(event, reason -> transformEvent.getTransformReason().equals(reason))) return false; if (datas != null && !datas.check(event, data -> data.isInstance(transformEvent.getEntity()))) return false; return true; } @Override public String toString(@Nullable Event event, boolean debug) { if (datas == null) return "entities transforming" + (reasons == null ? "" : " due to " + reasons.toString(event, debug)); return datas.toString(event, debug) + " transforming" + (reasons == null ? "" : " due to " + reasons.toString(event, debug)); } }
0
0.910697
1
0.910697
game-dev
MEDIA
0.502248
game-dev
0.686341
1
0.686341
JellyLabScripts/FarmHelper
39,213
src/main/java/com/jelly/farmhelperv2/pathfinder/FlyPathFinderExecutor.java
package com.jelly.farmhelperv2.pathfinder; import cc.polyfrost.oneconfig.utils.Multithreading; import com.google.common.collect.EvictingQueue; import com.jelly.farmhelperv2.config.FarmHelperConfig; import com.jelly.farmhelperv2.event.ReceivePacketEvent; import com.jelly.farmhelperv2.feature.impl.LagDetector; import com.jelly.farmhelperv2.handler.RotationHandler; import com.jelly.farmhelperv2.mixin.client.EntityPlayerAccessor; import com.jelly.farmhelperv2.mixin.pathfinder.PathfinderAccessor; import com.jelly.farmhelperv2.util.*; import com.jelly.farmhelperv2.util.helper.*; import lombok.Getter; import lombok.Setter; import net.minecraft.block.Block; import net.minecraft.block.BlockCactus; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockSoulSand; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.network.play.server.S08PacketPlayerPosLook; import net.minecraft.pathfinding.PathEntity; import net.minecraft.pathfinding.PathFinder; import net.minecraft.pathfinding.PathPoint; import net.minecraft.potion.Potion; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.awt.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class FlyPathFinderExecutor { private static FlyPathFinderExecutor instance; public static FlyPathFinderExecutor getInstance() { if (instance == null) { instance = new FlyPathFinderExecutor(); } return instance; } private final Minecraft mc = Minecraft.getMinecraft(); private Thread pathfinderTask; private Thread timeoutTask; @Getter private State state = State.NONE; private int tick = 0; private final CopyOnWriteArrayList<Vec3> path = new CopyOnWriteArrayList<>(); private Vec3 target; private Entity targetEntity; private boolean follow; private boolean smooth; @Setter private boolean sprinting = false; @Setter @Getter private boolean useAOTV = false; @Getter private long lastTpTime = 0; private final FlyNodeProcessor flyNodeProcessor = new FlyNodeProcessor(); private final PathFinder pathFinder = new PathFinder(flyNodeProcessor); @Getter private float neededYaw = Integer.MIN_VALUE; private final int MAX_DISTANCE = 1500; private int ticksAtLastPos = 0; private Vec3 lastPosCheck = new Vec3(0, 0, 0); private float yModifier = 0; private final Clock stuckBreak = new Clock(); private final Clock stuckCheckDelay = new Clock(); @Getter @Setter private boolean dontRotate = false; private final EvictingQueue<Position> lastPositions = EvictingQueue.create(100); private Position lastPosition; @Setter private float stoppingPositionThreshold = 0.75f; public void findPath(Vec3 pos, boolean follow, boolean smooth) { if (mc.thePlayer.getDistance(pos.xCoord, pos.yCoord, pos.zCoord) < 1) { stop(); LogUtils.sendSuccess("Already at destination"); return; } lastPosition = new Position(mc.thePlayer.getPosition(), new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch)); lastPositions.add(lastPosition); state = State.CALCULATING; this.follow = follow; this.target = pos; this.smooth = smooth; try { pathfinderTask = new Thread(() -> { long startTime = System.currentTimeMillis(); float maxDistance = (float) Math.min(mc.thePlayer.getPositionVector().distanceTo(pos) + 5, MAX_DISTANCE); LogUtils.sendDebug("Distance to target: " + maxDistance); LogUtils.sendDebug("Pathfinding to " + pos); PathEntity route = ((PathfinderAccessor) pathFinder).createPath(mc.theWorld, mc.thePlayer, pos.xCoord, pos.yCoord, pos.zCoord, maxDistance); if (route == null) { LogUtils.sendError("Failed to find path to " + pos); state = State.FAILED; double distance = mc.thePlayer.getPositionVector().distanceTo(this.target); if (distance > MAX_DISTANCE) { LogUtils.sendError("Distance to target is too far. Distance: " + distance + ", Max distance: " + MAX_DISTANCE); stop(); } return; } if (!isRunning()) { stop(); return; } LogUtils.sendDebug("Pathfinding took " + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); List<Vec3> finalRoute = new ArrayList<>(); for (int i = 0; i < route.getCurrentPathLength(); i++) { PathPoint pathPoint = route.getPathPointFromIndex(i); finalRoute.add(new Vec3(pathPoint.xCoord, pathPoint.yCoord, pathPoint.zCoord)); } if (smooth) { finalRoute = smoothPath(finalRoute); } if (!this.isDecelerating()) { this.path.clear(); this.path.addAll(finalRoute.stream().map(vec3 -> vec3.addVector(0.5f, 0.15, 0.5)).collect(Collectors.toCollection(CopyOnWriteArrayList::new))); state = State.PATHING; } LogUtils.sendDebug("Path smoothing took " + (System.currentTimeMillis() - startTime) + "ms"); if (timeoutTask != null) { timeoutTask.stop(); } }); pathfinderTask.start(); timeoutTask = new Thread(() -> { try { Thread.sleep(10_000); if (isCalculating()) { LogUtils.sendError("Pathfinding took too long"); RotationHandler.getInstance().reset(); state = State.FAILED; if (pathfinderTask != null) { pathfinderTask.stop(); } } } catch (InterruptedException e) { LogUtils.sendDebug("Pathfinding finished before timeout"); } }); timeoutTask.start(); } catch (Exception e) { LogUtils.sendError("Pathfinding took too long"); if (!this.follow) stop(); } } public void findPath(Entity target, boolean follow, boolean smooth) { this.targetEntity = target; this.yModifier = 0; findPath(new Vec3(target.posX, target.posY, target.posZ), follow, smooth); } public void findPath(Entity target, boolean follow, boolean smooth, float yModifier, boolean dontRotate) { this.targetEntity = target; this.yModifier = yModifier; this.dontRotate = dontRotate; if (Math.abs(target.motionX) > 0.15 || Math.abs(target.motionZ) > 0.15) { Vec3 targetNextPos = new Vec3(target.posX + target.motionX, target.posY + target.motionY, target.posZ + target.motionZ); findPath(targetNextPos.addVector(0, this.yModifier, 0), follow, smooth); } else { Vec3 targetPos = new Vec3(target.posX, target.posY, target.posZ); Rotation rotation = RotationHandler.getInstance().getRotation(targetPos, mc.thePlayer.getPositionVector()); Vec3 direction = AngleUtils.getVectorForRotation(0, rotation.getYaw()); targetPos = targetPos.addVector(direction.xCoord * 1.2, 0.5, direction.zCoord * 1.2); findPath(targetPos.addVector(0, this.yModifier, 0), follow, smooth); } } public boolean isRotationInCache(float yaw, float pitch) { return lastPositions.stream().anyMatch(position -> position.pos.distanceSq(mc.thePlayer.getPosition()) <= 1 && Math.abs(position.rotation.getYaw() - yaw) < 1 && Math.abs(position.rotation.getPitch() - pitch) < 1); } public boolean isPositionInCache(BlockPos pos) { return lastPositions.stream().anyMatch(position -> position.pos.equals(pos)); } private List<Vec3> smoothPath(List<Vec3> path) { if (path.size() < 2) { return path; } List<Vec3> smoothed = new ArrayList<>(); smoothed.add(path.get(0)); int lowerIndex = 0; while (lowerIndex < path.size() - 2) { Vec3 start = path.get(lowerIndex); Vec3 lastValid = path.get(lowerIndex + 1); for (int upperIndex = lowerIndex + 2; upperIndex < path.size(); upperIndex++) { Vec3 end = path.get(upperIndex); if (traversable(start.addVector(0, 0.1, 0), end.addVector(0, 0.1, 0)) && traversable(start.addVector(0, 0.9, 0), end.addVector(0, 0.9, 0)) && traversable(start.addVector(0, 1.1, 0), end.addVector(0, 1.1, 0)) && traversable(start.addVector(0, 1.9, 0), end.addVector(0, 1.9, 0))) { lastValid = end; } } smoothed.add(lastValid); lowerIndex = path.indexOf(lastValid); } return smoothed; } private static final Vec3[] BLOCK_SIDE_MULTIPLIERS = new Vec3[]{ new Vec3(0.05, 0, 0.05), new Vec3(0.05, 0, 0.95), new Vec3(0.95, 0, 0.05), new Vec3(0.95, 0, 0.95) }; private boolean traversable(Vec3 from, Vec3 to) { for (Vec3 offset : BLOCK_SIDE_MULTIPLIERS) { Vec3 fromVec = new Vec3(from.xCoord + offset.xCoord, from.yCoord + offset.yCoord, from.zCoord + offset.zCoord); Vec3 toVec = new Vec3(to.xCoord + offset.xCoord, to.yCoord + offset.yCoord, to.zCoord + offset.zCoord); MovingObjectPosition trace = mc.theWorld.rayTraceBlocks(fromVec, toVec, false, true, false); if (trace != null) { return false; } } return true; } public boolean isPathing() { return state == State.PATHING; } public boolean isCalculating() { return state == State.CALCULATING; } public boolean isDecelerating() { return state == State.DECELERATING || state == State.WAITING_FOR_DECELERATION; } public boolean isRunning() { return isPathing() || isCalculating() || isDecelerating() || stuckBreak.isScheduled(); } public boolean isPathingOrDecelerating() { return isPathing() || isDecelerating() || stuckBreak.isScheduled(); } public void stop() { RotationHandler.getInstance().reset(); path.clear(); target = null; tped = true; aotvDelay.reset(); targetEntity = null; yModifier = 0; lastTpTime = 0; state = State.NONE; KeyBindUtils.stopMovement(true); loweringRaisingDelay.reset(); neededYaw = Integer.MIN_VALUE; if (pathfinderTask != null) { pathfinderTask.interrupt(); pathfinderTask = null; } if (timeoutTask != null) { timeoutTask.interrupt(); timeoutTask = null; } ticksAtLastPos = 0; lastPosCheck = new Vec3(0, 0, 0); stuckBreak.reset(); stuckCheckDelay.reset(); dontRotate = false; stoppingPositionThreshold = 0.75f; } @SubscribeEvent public void onWorldChange(WorldEvent.Unload event) { if (isRunning()) { stop(); } } @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END) return; if (path.isEmpty()) return; if (target == null) return; tick = (tick + 1) % 12; if (tick != 0) return; if (isCalculating()) return; if (isDecelerating()) return; if (!this.follow) return; if (this.targetEntity != null) { findPath(this.targetEntity, true, this.smooth, this.yModifier, this.dontRotate); } else { findPath(this.target, true, this.smooth); } } private final Clock loweringRaisingDelay = new Clock(); private final Clock aotvDelay = new Clock(); private boolean tped = true; @SubscribeEvent public void onTickNeededYaw(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END) return; if (state == State.NONE) return; if (state == State.FAILED) { neededYaw = Integer.MIN_VALUE; return; } if (mc.currentScreen != null) { KeyBindUtils.stopMovement(); neededYaw = Integer.MIN_VALUE; return; } ArrayList<Vec3> copyPath = new ArrayList<>(path); if (copyPath.isEmpty()) { KeyBindUtils.stopMovement(true); return; } if (state == State.DECELERATING) { if (Math.abs(mc.thePlayer.motionX) <= 0.05 && Math.abs(mc.thePlayer.motionZ) <= 0.05 && mc.thePlayer.motionY == (mc.thePlayer.onGround ? -0.0784000015258789 : 0)) { stop(); } return; } if (stuckBreak.isScheduled() && !stuckBreak.passed()) return; Vec3 current = mc.thePlayer.getPositionVector(); BlockPos currentPos = mc.thePlayer.getPosition(); lastPosition = new Position(currentPos, new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch)); lastPositions.add(lastPosition); if (checkForStuck(current)) { LogUtils.sendDebug("Stuck"); stuckBreak.schedule(800); float rotationToEscape; for (rotationToEscape = 0; rotationToEscape < 360; rotationToEscape += 20) { Vec3 escape = current.addVector(Math.cos(Math.toRadians(rotationToEscape)), 0, Math.sin(Math.toRadians(rotationToEscape))); if (traversable(current.addVector(0, 0.1, 0), escape.addVector(0, 0.1, 0)) && traversable(current.addVector(0, 0.9, 0), escape.addVector(0, 0.9, 0)) && traversable(current.addVector(0, 1.1, 0), escape.addVector(0, 1.1, 0)) && traversable(current.addVector(0, 1.9, 0), escape.addVector(0, 1.9, 0))) { break; } } neededYaw = rotationToEscape; if (FarmHelperConfig.flyPathfinderOringoCompatible) { List<KeyBinding> keyBindings = new ArrayList<>(KeyBindUtils.getNeededKeyPresses(neededYaw)); keyBindings.add(mc.gameSettings.keyBindUseItem.isKeyDown() ? mc.gameSettings.keyBindUseItem : null); keyBindings.add(mc.gameSettings.keyBindAttack.isKeyDown() ? mc.gameSettings.keyBindAttack : null); Vec3 above = current.addVector(0, mc.thePlayer.height + 0.5f, 0); Vec3 below = current.addVector(0, -0.5f, 0); MovingObjectPosition traceAbove = mc.theWorld.rayTraceBlocks(current, above, false, true, false); MovingObjectPosition traceBelow = mc.theWorld.rayTraceBlocks(current, below, false, true, false); if (traceBelow == null || traceBelow.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK) { keyBindings.add(mc.gameSettings.keyBindSneak); } else if (traceAbove == null || traceAbove.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK) { keyBindings.add(mc.gameSettings.keyBindJump); } KeyBindUtils.holdThese(keyBindings.toArray(new KeyBinding[0])); } else { KeyBindUtils.holdThese(mc.gameSettings.keyBindForward, mc.gameSettings.keyBindUseItem.isKeyDown() ? mc.gameSettings.keyBindUseItem : null, mc.gameSettings.keyBindAttack.isKeyDown() ? mc.gameSettings.keyBindAttack : null); } Multithreading.schedule(() -> KeyBindUtils.stopMovement(true), 500, TimeUnit.MILLISECONDS); return; } Vec3 lastElem = copyPath.get(copyPath.size() - 1); if (targetEntity != null) { if (targetEntity instanceof EntityArmorStand) { Entity properEntity = PlayerUtils.getEntityCuttingOtherEntity(targetEntity, e -> !(e instanceof EntityArmorStand)); if (properEntity != null) { targetEntity = properEntity; } } float entityVelocity = (float) Math.sqrt(targetEntity.motionX * targetEntity.motionX + targetEntity.motionZ * targetEntity.motionZ); Vec3 targetPos = targetEntity.getPositionVector().addVector(0, this.yModifier, 0); if (entityVelocity > 0.1) { targetPos = targetPos.addVector(targetEntity.motionX * 1.3, targetEntity.motionY, targetEntity.motionZ * 1.3); } float distance = (float) mc.thePlayer.getPositionVector().distanceTo(targetPos); float distancePath = (float) mc.thePlayer.getPositionVector().distanceTo(lastElem); if (willArriveAtDestinationAfterStopping(lastElem) && entityVelocity < 0.15) { state = State.DECELERATING; KeyBindUtils.stopMovement(true); // stop(); return; } if ((distance < 1 && entityVelocity > 0.15) || (distancePath < 0.5 && entityVelocity < 0.15)) { stop(); return; } } else if (willArriveAtDestinationAfterStopping(lastElem) || mc.thePlayer.getDistance(lastElem.xCoord, lastElem.yCoord, lastElem.zCoord) < 0.3) { state = State.DECELERATING; KeyBindUtils.stopMovement(true); // stop(); return; } if (!mc.thePlayer.capabilities.allowFlying) { Vec3 lastWithoutY = new Vec3(lastElem.xCoord, current.yCoord, lastElem.zCoord); if (current.distanceTo(lastWithoutY) < 1) { stop(); LogUtils.sendSuccess("Arrived at destination"); return; } } Vec3 next = getNext(copyPath); if (!RotationHandler.getInstance().isRotating() && mc.thePlayer.getDistance(next.xCoord, next.yCoord, next.zCoord) > 2) { Target target; if (this.targetEntity != null) target = new Target(this.targetEntity).additionalY(this.yModifier); else if (this.neededYaw != Integer.MIN_VALUE) { Vec3 directionHeading = AngleUtils.getVectorForRotation(4, this.neededYaw); Vec3 directionHeadingPlayer = mc.thePlayer.getPositionEyes(1).addVector(directionHeading.xCoord * 5, directionHeading.yCoord * 5, directionHeading.zCoord * 5); target = new Target(directionHeadingPlayer); } else { target = new Target(this.target).additionalY(this.yModifier); } if (!this.dontRotate && target.getTarget().isPresent() && !path.isEmpty()) { Vec3 lastElement = path.get(Math.max(0, path.size() - 1)); Rotation rot = RotationHandler.getInstance().getRotation(target.getTarget().get()); if (mc.thePlayer.getPositionVector().distanceTo(lastElement) > 2 && target.getTarget().isPresent() && RotationHandler.getInstance().shouldRotate(rot, 3)) { float distanceTo = RotationHandler.getInstance().distanceTo(rot); RotationHandler.getInstance().easeTo(new RotationConfiguration( rot, (long) (FarmHelperConfig.getRandomFlyPathExecutionerRotationTime() * (Math.max(1, distanceTo / 90))), null )); } } if (FarmHelperConfig.useAoteVInPestsDestroyer && tped && useAOTV && aotvDelay.passed() && mc.thePlayer.getDistance(next.xCoord, mc.thePlayer.getPositionVector().yCoord, next.zCoord) > 12 && !RotationHandler.getInstance().isRotating() && isFrontClean()) { int aotv = InventoryUtils.getSlotIdOfItemInHotbar("Aspect of the Void", "Aspect of the End"); if (aotv != mc.thePlayer.inventory.currentItem) { mc.thePlayer.inventory.currentItem = aotv; aotvDelay.schedule(150); } else { KeyBindUtils.rightClick(); tped = false; lastTpTime = System.currentTimeMillis(); } } } Rotation rotation = RotationHandler.getInstance().getRotation(current, next); List<KeyBinding> keyBindings = new ArrayList<>(); List<KeyBinding> neededKeys = KeyBindUtils.getNeededKeyPresses(rotation.getYaw()); neededYaw = rotation.getYaw(); keyBindings.add(mc.gameSettings.keyBindUseItem.isKeyDown() ? mc.gameSettings.keyBindUseItem : null); keyBindings.add(mc.gameSettings.keyBindAttack.isKeyDown() ? mc.gameSettings.keyBindAttack : null); if (FarmHelperConfig.flyPathfinderOringoCompatible) { keyBindings.addAll(neededKeys); } else { keyBindings.add(mc.gameSettings.keyBindForward); } double distanceX = next.xCoord - mc.thePlayer.posX; double distanceY = next.yCoord - mc.thePlayer.posY; double distanceZ = next.zCoord - mc.thePlayer.posZ; float yaw = neededYaw * (float) Math.PI / 180.0f; double relativeDistanceX = distanceX * Math.cos(yaw) + distanceZ * Math.sin(yaw); double relativeDistanceZ = -distanceX * Math.sin(yaw) + distanceZ * Math.cos(yaw); VerticalDirection verticalDirection = shouldChangeHeight(relativeDistanceX, relativeDistanceZ); if (mc.thePlayer.capabilities.allowFlying) { // flying + walking if (fly(next, current)) return; if (verticalDirection.equals(VerticalDirection.HIGHER)) { keyBindings.add(mc.gameSettings.keyBindJump); loweringRaisingDelay.schedule(750); } else if (verticalDirection.equals(VerticalDirection.LOWER)) { keyBindings.add(mc.gameSettings.keyBindSneak); loweringRaisingDelay.schedule(750); } else if (loweringRaisingDelay.passed() && (getBlockUnder() instanceof BlockCactus || distanceY > 0.5) && (((EntityPlayerAccessor) mc.thePlayer).getFlyToggleTimer() == 0 || mc.gameSettings.keyBindJump.isKeyDown())) { keyBindings.add(mc.gameSettings.keyBindJump); } else if (loweringRaisingDelay.passed() && distanceY < -0.5) { Block blockUnder = getBlockUnder(); if (!mc.thePlayer.onGround && mc.thePlayer.capabilities.isFlying && !(blockUnder instanceof BlockCactus) && !(blockUnder instanceof BlockSoulSand)) { keyBindings.add(mc.gameSettings.keyBindSneak); } } } else { // only walking if (shouldJump(next, current)) { mc.thePlayer.jump(); } } if (sprinting) { keyBindings.add(mc.gameSettings.keyBindSprint); } if (neededYaw != Integer.MIN_VALUE) KeyBindUtils.holdThese(keyBindings.toArray(new KeyBinding[0])); else KeyBindUtils.stopMovement(true); } @SubscribeEvent(priority = EventPriority.LOWEST) public void onTeleportPacket(ReceivePacketEvent event) { if (!isRunning()) return; if (event.packet instanceof S08PacketPlayerPosLook) { System.out.println("Tped"); lastTpTime = System.currentTimeMillis() - 50; Multithreading.schedule(() -> { if (isRunning()) { aotvDelay.schedule(100 + Math.random() * 60); tped = true; } }, 50, TimeUnit.MILLISECONDS); } } public boolean hasJustTped() { return lastTpTime + LagDetector.getInstance().getLaggingTime() + 500 > System.currentTimeMillis(); } private boolean isFrontClean() { Vec3 direction = mc.thePlayer.getLookVec(); Vec3 tpPosition = mc.thePlayer.getPositionEyes(1).addVector(direction.xCoord * 10, direction.yCoord * 10, direction.zCoord * 10); MovingObjectPosition mop = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector(), tpPosition, false, true, false); return mop == null || mop.typeOfHit != MovingObjectPosition.MovingObjectType.BLOCK; } public boolean isTping() { return !tped; } private boolean willArriveAtDestinationAfterStopping(Vec3 targetPos) { return predictStoppingPosition().distanceTo(targetPos) < stoppingPositionThreshold; } private Vec3 predictStoppingPosition() { PlayerSimulation playerSimulation = new PlayerSimulation(mc.theWorld); playerSimulation.copy(mc.thePlayer); playerSimulation.isFlying = true; playerSimulation.rotationYaw = neededYaw != Integer.MIN_VALUE && !FarmHelperConfig.flyPathfinderOringoCompatible ? neededYaw : mc.thePlayer.rotationYaw; for (int i = 0; i < 30; i++) { playerSimulation.onLivingUpdate(); if (Math.abs(playerSimulation.motionX) < 0.01D && Math.abs(playerSimulation.motionZ) < 0.01D) { break; } } return new Vec3(playerSimulation.posX, playerSimulation.posY, playerSimulation.posZ); } private Block getBlockUnder() { Vec3 current = mc.thePlayer.getPositionVector(); Vec3 direction = current.addVector(0, 0.5, 0); MovingObjectPosition trace = mc.theWorld.rayTraceBlocks(current, direction, false, true, false); if (trace != null) { return mc.theWorld.getBlockState(trace.getBlockPos()).getBlock(); } return null; } public VerticalDirection shouldChangeHeight(double relativeDistanceX, double relativeDistanceZ) { if (Math.abs(relativeDistanceX) < 0.75 && Math.abs(relativeDistanceZ) < 0.75) { System.out.println("No need to avoid blocks"); return VerticalDirection.NONE; } BlocksInFront blocksInFront = getCollidingBlocks(); if (isBlockInFront(blocksInFront.leftUp) || isBlockInFront(blocksInFront.centerUp) || isBlockInFront(blocksInFront.rightUp)) { return VerticalDirection.LOWER; } if (isBlockInFront(blocksInFront.leftDown) || isBlockInFront(blocksInFront.centerDown) || isBlockInFront(blocksInFront.rightDown) || isFenceDown(blocksInFront.fenceGateTrace)) { return VerticalDirection.HIGHER; } return VerticalDirection.NONE; } private boolean isBlockInFront(MovingObjectPosition trace) { return trace != null && trace.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK && BlockUtils.hasCollision(trace.getBlockPos()); } private boolean isFenceDown(MovingObjectPosition trace) { return trace != null && trace.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK && BlockUtils.hasCollision(trace.getBlockPos()) && BlockUtils.getBlock(trace.getBlockPos()) instanceof BlockFenceGate; } public enum VerticalDirection { HIGHER, LOWER, NONE } private boolean checkForStuck(Vec3 positionVec3) { if (!stuckCheckDelay.passed()) return false; if (this.ticksAtLastPos > 15) { this.ticksAtLastPos = 0; this.lastPosCheck = positionVec3; return positionVec3.squareDistanceTo(this.lastPosCheck) < 2.25; } double diff = positionVec3.squareDistanceTo(this.lastPosCheck); if (diff < 2.25) { this.ticksAtLastPos++; } else { this.ticksAtLastPos = 0; this.lastPosCheck = positionVec3; } stuckCheckDelay.schedule(100); return false; } private boolean shouldJump(Vec3 next, Vec3 current) { int jumpBoost = mc.thePlayer.getActivePotionEffect(Potion.jump) != null ? mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier() + 1 : 0; return next.yCoord - current.yCoord > 0.25 + jumpBoost * 0.1 && mc.thePlayer.onGround && next.yCoord - current.yCoord < jumpBoost * 0.1 + 0.5; } private final Clock flyDelay = new Clock(); private boolean fly(Vec3 next, Vec3 current) { if (mc.thePlayer.motionY < -0.0784000015258789 || BlockUtils.getRelativeBlock(0, 0, 0).getMaterial().isLiquid()) if (flyDelay.passed()) { if (!mc.thePlayer.capabilities.isFlying) { mc.thePlayer.capabilities.isFlying = true; mc.thePlayer.sendPlayerAbilities(); } flyDelay.reset(); } else if (flyDelay.isScheduled()) { return true; } if (mc.thePlayer.onGround && next.yCoord - current.yCoord > 0.5) { mc.thePlayer.jump(); flyDelay.schedule(180 + (long) (Math.random() * 180)); return true; } else { Vec3 closestToPlayer; try { closestToPlayer = path.stream().min(Comparator.comparingDouble((vec1) -> vec1.distanceTo(mc.thePlayer.getPositionVector()))).orElse(path.get(0)); } catch (IndexOutOfBoundsException e) { return false; } if (next.yCoord - closestToPlayer.yCoord > 0.5) { if (!flyDelay.isScheduled()) { flyDelay.schedule(180 + (long) (Math.random() * 180)); } return !mc.thePlayer.capabilities.isFlying; } } return false; } @SubscribeEvent public void onDraw(RenderWorldLastEvent event) { ArrayList<Vec3> copyPath = new ArrayList<>(path); if (copyPath.isEmpty()) return; if (!isRunning()) return; if (FarmHelperConfig.streamerMode) return; RenderManager renderManager = mc.getRenderManager(); Vec3 current = mc.thePlayer.getPositionVector(); Vec3 next = getNext(copyPath); AxisAlignedBB currenNode = new AxisAlignedBB(current.xCoord - 0.05, current.yCoord - 0.05, current.zCoord - 0.05, current.xCoord + 0.05, current.yCoord + 0.05, current.zCoord + 0.05); AxisAlignedBB nextBB = new AxisAlignedBB(next.xCoord - 0.05, next.yCoord - 0.05, next.zCoord - 0.05, next.xCoord + 0.05, next.yCoord + 0.05, next.zCoord + 0.05); RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); currenNode = currenNode.offset(-rendermanager.viewerPosX, -rendermanager.viewerPosY, -rendermanager.viewerPosZ); nextBB = nextBB.offset(-rendermanager.viewerPosX, -rendermanager.viewerPosY, -rendermanager.viewerPosZ); RenderUtils.drawBox(currenNode, Color.GREEN); RenderUtils.drawBox(nextBB, Color.BLUE); for (int i = 0; i < copyPath.size() - 1; i++) { Vec3 from = new Vec3(copyPath.get(i).xCoord, copyPath.get(i).yCoord, copyPath.get(i).zCoord); Vec3 to = new Vec3(copyPath.get(i + 1).xCoord, copyPath.get(i + 1).yCoord, copyPath.get(i + 1).zCoord); from = from.addVector(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ); RenderUtils.drawTracer(from, to, Color.RED); } if (!FarmHelperConfig.debugMode) return; BlocksInFront blocksInFront = getCollidingBlocks(); drawCollidingBlock(blocksInFront.leftUp, renderManager, blocksInFront.leftUpTarget); drawCollidingBlock(blocksInFront.centerUp, renderManager, blocksInFront.centerUpTarget); drawCollidingBlock(blocksInFront.rightUp, renderManager, blocksInFront.rightUpTarget); drawCollidingBlock(blocksInFront.leftDown, renderManager, blocksInFront.leftDownTarget); drawCollidingBlock(blocksInFront.centerDown, renderManager, blocksInFront.centerDownTarget); drawCollidingBlock(blocksInFront.rightDown, renderManager, blocksInFront.rightDownTarget); drawCollidingBlock(blocksInFront.fenceGateTrace, renderManager, blocksInFront.fenceGateCheck); } private final Color blockedColor = new Color(255, 0, 0, 100); private final Color freeColor = new Color(0, 255, 0, 100); public void drawCollidingBlock(MovingObjectPosition mop, RenderManager renderManager, Vec3 target) { if (mop != null && mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK && BlockUtils.hasCollision(mop.getBlockPos())) { BlockPos blockPos = mop.getBlockPos(); RenderUtils.drawBox(new AxisAlignedBB(blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockPos.getX() + 1, blockPos.getY() + 1, blockPos.getZ() + 1).offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ), blockedColor); } else { RenderUtils.drawBox(new AxisAlignedBB(target.xCoord, target.yCoord, target.zCoord, target.xCoord + 0.1, target.yCoord + 0.1, target.zCoord + 0.1).offset(-renderManager.viewerPosX, -renderManager.viewerPosY, -renderManager.viewerPosZ), freeColor); } } public BlocksInFront getCollidingBlocks() { Vec3 directionGoing = AngleUtils.getVectorForRotation(0, neededYaw); Vec3 directionGoingLeft = AngleUtils.getVectorForRotation(0, neededYaw - 20); Vec3 directionGoingRight = AngleUtils.getVectorForRotation(0, neededYaw + 20); Vec3 target = mc.thePlayer.getPositionVector().addVector(directionGoing.xCoord * 0.75, -0.1, directionGoing.zCoord * 0.75); Vec3 targetLeft = mc.thePlayer.getPositionVector().addVector(directionGoingLeft.xCoord * 0.75, -0.1, directionGoingLeft.zCoord * 0.75); Vec3 targetRight = mc.thePlayer.getPositionVector().addVector(directionGoingRight.xCoord * 0.75, -0.1, directionGoingRight.zCoord * 0.75); Vec3 targetUp = mc.thePlayer.getPositionVector().addVector(directionGoing.xCoord * 0.75, mc.thePlayer.height + 0.1, directionGoing.zCoord * 0.75); Vec3 targetLeftUp = mc.thePlayer.getPositionVector().addVector(directionGoingLeft.xCoord * 0.75, mc.thePlayer.height + 0.1, directionGoingLeft.zCoord * 0.75); Vec3 targetRightUp = mc.thePlayer.getPositionVector().addVector(directionGoingRight.xCoord * 0.75, mc.thePlayer.height + 0.1, directionGoingRight.zCoord * 0.75); Vec3 fenceGateCheck = mc.thePlayer.getPositionVector().addVector(directionGoing.xCoord * 0.25, -0.75, directionGoing.zCoord * 0.25); MovingObjectPosition trace = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector(), target, false, true, false); MovingObjectPosition traceLeft = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector(), targetLeft, false, true, false); MovingObjectPosition traceRight = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector(), targetRight, false, true, false); MovingObjectPosition traceUp = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector().addVector(0, mc.thePlayer.height, 0), targetUp, false, true, false); MovingObjectPosition traceLeftUp = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector().addVector(0, mc.thePlayer.height, 0), targetLeftUp, false, true, false); MovingObjectPosition traceRightUp = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector().addVector(0, mc.thePlayer.height, 0), targetRightUp, false, true, false); MovingObjectPosition fenceGateTrace = mc.theWorld.rayTraceBlocks(mc.thePlayer.getPositionVector(), fenceGateCheck, false, true, false); return new BlocksInFront(targetLeftUp, traceLeftUp, targetUp, traceUp, targetRightUp, traceRightUp, targetLeft, traceLeft, target, trace, targetRight, traceRight, fenceGateCheck, fenceGateTrace); } private Vec3 getNext(ArrayList<Vec3> path) { if (path.isEmpty()) { return mc.thePlayer.getPositionVector(); } try { Vec3 current = mc.thePlayer.getPositionVector(); Vec3 closestToPlayer = path.stream().min(Comparator.comparingDouble(vec -> vec.distanceTo(current))).orElse(path.get(path.size() - 2)); return path.get(path.indexOf(closestToPlayer) + 1); } catch (IndexOutOfBoundsException e) { return path.get(path.size() - 1); } } public enum State { NONE, CALCULATING, FAILED, PATHING, DECELERATING, WAITING_FOR_DECELERATION } public static class Position { public BlockPos pos; public Rotation rotation; Position(BlockPos pos, Rotation rotation) { this.pos = pos; this.rotation = rotation; } } public static class BlocksInFront { public Vec3 leftUpTarget; public MovingObjectPosition leftUp; public Vec3 centerUpTarget; public MovingObjectPosition centerUp; public Vec3 rightUpTarget; public MovingObjectPosition rightUp; public Vec3 leftDownTarget; public MovingObjectPosition leftDown; public Vec3 centerDownTarget; public MovingObjectPosition centerDown; public Vec3 rightDownTarget; public MovingObjectPosition rightDown; public Vec3 fenceGateCheck; public MovingObjectPosition fenceGateTrace; public BlocksInFront(Vec3 leftUpTarget, MovingObjectPosition leftUp, Vec3 centerUpTarget, MovingObjectPosition centerUp, Vec3 rightUpTarget, MovingObjectPosition rightUp, Vec3 leftDownTarget, MovingObjectPosition leftDown, Vec3 centerDownTarget, MovingObjectPosition centerDown, Vec3 rightDownTarget, MovingObjectPosition rightDown, Vec3 fenceGateCheck, MovingObjectPosition fenceGateTrace) { this.leftUpTarget = leftUpTarget; this.leftUp = leftUp; this.centerUpTarget = centerUpTarget; this.centerUp = centerUp; this.rightUpTarget = rightUpTarget; this.rightUp = rightUp; this.leftDownTarget = leftDownTarget; this.leftDown = leftDown; this.centerDownTarget = centerDownTarget; this.centerDown = centerDown; this.rightDownTarget = rightDownTarget; this.rightDown = rightDown; this.fenceGateCheck = fenceGateCheck; this.fenceGateTrace = fenceGateTrace; } } }
0
0.965854
1
0.965854
game-dev
MEDIA
0.903796
game-dev
0.979098
1
0.979098
SonyWWS/SLED
4,748
tool/SledLuaLanguagePlugin/Dom/SledLuaVarEnvType.cs
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System.Collections.Generic; using Sce.Atf.Applications; using Sce.Sled.Lua.Resources; using Sce.Sled.Shared.Dom; namespace Sce.Sled.Lua.Dom { public class SledLuaVarEnvType : SledLuaVarBaseType { #region SledVarBaseType Overrides public override string Name { get { return GetAttribute<string>(SledLuaSchema.SledLuaVarEnvType.nameAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.nameAttribute, value); SetSortKey(); } } public override IList<SledVarLocationType> Locations { get { return GetChildList<SledVarLocationType>(SledLuaSchema.SledLuaVarEnvType.LocationsChild); } } #endregion #region SledLuaVarBaseType Overrides public override string DisplayName { get { return GetAttribute<string>(SledLuaSchema.SledLuaVarEnvType.display_nameAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.display_nameAttribute, value); } } public override string UniqueName { get { return GetAttribute<string>(SledLuaSchema.SledLuaVarEnvType.unique_nameAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.unique_nameAttribute, value); } } public override string What { get { return GetAttribute<string>(SledLuaSchema.SledLuaVarEnvType.typeAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.typeAttribute, value); SetWhatSortKey(); } } public override string Value { get { return GetAttribute<string>(SledLuaSchema.SledLuaVarEnvType.valueAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.valueAttribute, value); SetValueSortKey(); } } public override int KeyType { get { return GetAttribute<int>(SledLuaSchema.SledLuaVarEnvType.keytypeAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.keytypeAttribute, value); } } public override bool Expanded { get { return GetAttribute<bool>(SledLuaSchema.SledLuaVarEnvType.expandedAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.expandedAttribute, value); } } public override bool Visible { get { return GetAttribute<bool>(SledLuaSchema.SledLuaVarEnvType.visibleAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.visibleAttribute, value); } } public override IEnumerable<ISledLuaVarBaseType> Variables { get { return EnvVars; } } public override IList<SledLuaVarNameTypePairType> TargetHierarchy { get { return GetChildList<SledLuaVarNameTypePairType>(SledLuaSchema.SledLuaVarEnvType.TargetHierarchyChild); } } public override void GenerateUniqueName() { var uniqueName = Resource.Lua + Resource.Colon + Resource.E + Resource.Colon + Name + Resource.Colon + What + Resource.Colon + KeyType; UniqueName = uniqueName; } public override SledLuaVarScopeType Scope { get { return SledLuaVarScopeType.Environment; } } #endregion #region IITemView Interface public override void GetInfo(object item, ItemInfo info) { info.Label = DisplayName; info.Properties = new[] { What, Value, SledLuaVarScopeTypeString.ToString(Scope) }; info.IsLeaf = (LuaType != LuaType.LUA_TTABLE); info.ImageIndex = info.GetImageIndex(Atf.Resources.DataImage); info.Description = Name + Resource.Space + Resource.Colon + Resource.Space + What + Resource.Space + Resource.Colon + Resource.Space + Value; info.IsExpandedInView = Expanded; } #endregion #region ICloneable Interface public override object Clone() { var clone = (SledLuaVarEnvType)base.Clone(); return clone; } #endregion public int Level { get { return GetAttribute<int>(SledLuaSchema.SledLuaVarEnvType.levelAttribute); } set { SetAttribute(SledLuaSchema.SledLuaVarEnvType.levelAttribute, value); } } public IList<SledLuaVarEnvType> EnvVars { get { return GetChildList<SledLuaVarEnvType>(SledLuaSchema.SledLuaVarEnvType.EnvVarsChild); } } } }
0
0.712885
1
0.712885
game-dev
MEDIA
0.608598
game-dev,desktop-app
0.547198
1
0.547198
Jannyboy11/InvSee-plus-plus
5,585
InvSee++_Platforms/Impl_1_12_2_R1/src/main/java/com/janboerman/invsee/spigot/impl_1_12_R1/EnderNmsInventory.java
package com.janboerman.invsee.spigot.impl_1_12_R1; import com.janboerman.invsee.spigot.api.CreationOptions; import com.janboerman.invsee.spigot.api.target.Target; import com.janboerman.invsee.spigot.api.template.EnderChestSlot; import com.janboerman.invsee.spigot.internal.inventory.AbstractNmsInventory; import net.minecraft.server.v1_12_R1.*; import org.bukkit.craftbukkit.v1_12_R1.entity.CraftHumanEntity; import org.bukkit.craftbukkit.v1_12_R1.util.CraftChatMessage; import java.util.List; import java.util.UUID; class EnderNmsInventory extends AbstractNmsInventory<EnderChestSlot, EnderBukkitInventory, EnderNmsInventory> implements IInventory, ITileEntityContainer { protected NonNullList<ItemStack> storageContents; EnderNmsInventory(UUID spectatedPlayerUuid, String spectatedPlayerName, NonNullList<ItemStack> storageContents, CreationOptions<EnderChestSlot> creationOptions) { super(spectatedPlayerUuid, spectatedPlayerName, creationOptions); this.storageContents = storageContents; } @Override protected EnderBukkitInventory createBukkit() { return new EnderBukkitInventory(this); } @Override public void setMaxStackSize(int size) { this.maxStack = size; } @Override public int getMaxStackSize() { return maxStack; } @Override public int defaultMaxStack() { return IInventory.MAX_STACK; } @Override public void shallowCopyFrom(EnderNmsInventory from) { setMaxStackSize(from.getMaxStackSize()); this.storageContents = from.storageContents; update(); } @Override public int getSize() { return storageContents.size(); } @Override public boolean x_() { // isEmpty for (ItemStack stack : storageContents) { if (!stack.isEmpty()) return false; } return true; } @Override public ItemStack getItem(int slot) { if (slot < 0 || slot >= getSize()) return InvseeImpl.EMPTY_STACK; return storageContents.get(slot); } @Override public ItemStack splitStack(int slot, int subtractAmount) { if (slot < 0 || slot >= getSize()) return InvseeImpl.EMPTY_STACK; ItemStack stack = ContainerUtil.a(storageContents, slot, subtractAmount); if (!stack.isEmpty()) { update(); } return stack; } @Override public ItemStack splitWithoutUpdate(int slot) { if (slot < 0 || slot >= getSize()) return InvseeImpl.EMPTY_STACK; net.minecraft.server.v1_12_R1.ItemStack stack = storageContents.get(slot); if (stack.isEmpty()) { return InvseeImpl.EMPTY_STACK; } else { storageContents.set(slot, InvseeImpl.EMPTY_STACK); return stack; } } @Override public void setItem(int slot, ItemStack itemStack) { if (slot < 0 || slot >= getSize()) return; storageContents.set(slot, itemStack); if (!itemStack.isEmpty() && itemStack.getCount() > getMaxStackSize()) { itemStack.setCount(getMaxStackSize()); } update(); } @Override public void update() { //called after an item in the inventory was removed, added or updated. //looking at InventorySubContainer, I don't think we need to do anything here. //but just to be sure, we make sure our viewers get an updated view! // for (HumanEntity viewer : getViewers()) { // if (viewer instanceof Player) { // ((Player) viewer).updateInventory(); // } // } } @Override public boolean a(EntityHuman entityHuman) { return true; } @Override public void startOpen(EntityHuman entityHuman) { onOpen(entityHuman.getBukkitEntity()); } @Override public void closeContainer(EntityHuman entityHuman) { onClose(entityHuman.getBukkitEntity()); } @Override public boolean b(int slot, ItemStack itemStack) { //allowHopperInput return true; } @Override public int getProperty(int idx) { return 0; } @Override public void setProperty(int idx, int prop) { } @Override public int h() { //property count return 0; } @Override public List<ItemStack> getContents() { return storageContents; } @Override public void onOpen(CraftHumanEntity who) { super.onOpen(who); } @Override public void onClose(CraftHumanEntity who) { super.onClose(who); } @Override public void clear() { storageContents.clear(); } @Override public String getName() { return creationOptions.getTitle().titleFor(Target.byGameProfile(targetPlayerUuid, targetPlayerName)); } @Override public boolean hasCustomName() { return creationOptions.getTitle() != null; } @Override public IChatBaseComponent getScoreboardDisplayName() { return CraftChatMessage.fromString(creationOptions.getTitle().titleFor(Target.byGameProfile(targetPlayerUuid, targetPlayerName)))[0]; } @Override public Container createContainer(PlayerInventory playerInventory, EntityHuman entityHuman) { EntityPlayer entityPlayer = (EntityPlayer) entityHuman; return new EnderNmsContainer(entityPlayer.nextContainerCounter(), this, playerInventory, playerInventory.player, creationOptions); } @Override public String getContainerName() { return "minecraft:container"; } }
0
0.945314
1
0.945314
game-dev
MEDIA
0.994458
game-dev
0.973788
1
0.973788
gadgetron/gadgetron
1,295
gadgets/mri_core/generic_recon_gadgets/GenericReconImageToImageArrayGadget.h
/** \file GenericReconImageToImageArrayGadget.h \brief The conversion gadget, from incoming images to IsmrmrdImageArray \author Hui Xue */ #pragma once #include <complex> #include "gadgetron_mricore_export.h" #include "Gadget.h" #include "ismrmrd/ismrmrd.h" #include "ismrmrd/meta.h" #include "ismrmrd/xml.h" #include "hoNDArray.h" #include "mri_core_def.h" #include "mri_core_data.h" namespace Gadgetron { class EXPORTGADGETSMRICORE GenericReconImageToImageArrayGadget : public Gadget3<ISMRMRD::ImageHeader, hoNDArray<std::complex<float>>, ISMRMRD::MetaContainer> { public: GADGET_DECLARE(GenericReconImageToImageArrayGadget); typedef std::complex<float> ValueType; typedef Gadget3< ISMRMRD::ImageHeader, hoNDArray< ValueType >, ISMRMRD::MetaContainer > BaseClass; GenericReconImageToImageArrayGadget(); ~GenericReconImageToImageArrayGadget(); virtual int close(unsigned long flags); GADGET_PROPERTY(verbose, bool, "Whether to print more information", false); protected: virtual int process_config(ACE_Message_Block* mb); virtual int process(GadgetContainerMessage<ISMRMRD::ImageHeader>* m1, GadgetContainerMessage< hoNDArray<ValueType> >* m2, GadgetContainerMessage<ISMRMRD::MetaContainer>* m3); int process_called_times_; }; }
0
0.73311
1
0.73311
game-dev
MEDIA
0.291714
game-dev
0.578068
1
0.578068
CalamityTeam/CalamityModPublic
1,561
Items/Accessories/AscendantInsignia.cs
using System; using System.Collections.Generic; using CalamityMod.CalPlayer; using CalamityMod.Items.Materials; using CalamityMod.Items.Placeables; using CalamityMod.Items.Placeables.Ores; using CalamityMod.Rarities; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Items.Accessories { [LegacyName("YharimsInsignia")] public class AscendantInsignia : ModItem, ILocalizedModType { public new string LocalizationCategory => "Items.Accessories"; public override void ModifyTooltips(List<TooltipLine> list) => list.IntegrateHotkey(CalamityKeybinds.AscendantInsigniaHotKey); public override void SetDefaults() { Item.width = 46; Item.height = 36; Item.value = CalamityGlobalItem.RarityPureGreenBuyPrice; Item.accessory = true; Item.rare = ModContent.RarityType<PureGreen>(); } public override void UpdateAccessory(Player player, bool hideVisual) { CalamityPlayer modPlayer = player.Calamity(); modPlayer.ascendantInsignia = true; player.empressBrooch = true; } public override void AddRecipes() { CreateRecipe(). AddIngredient(ItemID.EmpressFlightBooster). AddIngredient<EffulgentFeather>(5). AddIngredient(ItemID.SoulofFlight, 10). AddIngredient<RuinousSoul>(5). AddTile(TileID.LunarCraftingStation). Register(); } } }
0
0.821302
1
0.821302
game-dev
MEDIA
0.97945
game-dev
0.713842
1
0.713842
OpenXRay/xray-15
9,310
cs/engine/xrGame/level_graph.cpp
//////////////////////////////////////////////////////////////////////////// // Module : level_graph.cpp // Created : 02.10.2001 // Modified : 11.11.2003 // Author : Oles Shihkovtsov, Dmitriy Iassenev // Description : Level graph //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "level_graph.h" #include "profiler.h" LPCSTR LEVEL_GRAPH_NAME = "level.ai"; #ifdef AI_COMPILER CLevelGraph::CLevelGraph (LPCSTR filename) #else CLevelGraph::CLevelGraph () #endif { #ifndef AI_COMPILER #ifdef DEBUG sh_debug->create ("debug\\ai_nodes","$null"); #endif string_path file_name; FS.update_path (file_name,"$level$",LEVEL_GRAPH_NAME); #else string256 file_name; strconcat (sizeof(file_name), file_name, filename, LEVEL_GRAPH_NAME); #endif m_reader = FS.r_open (file_name); // m_header & data m_header = (CHeader*)m_reader->pointer(); R_ASSERT (header().version() == XRAI_CURRENT_VERSION); m_reader->advance (sizeof(CHeader)); m_nodes = (CVertex*)m_reader->pointer(); m_row_length = iFloor((header().box().max.z - header().box().min.z)/header().cell_size() + EPS_L + 1.5f); m_column_length = iFloor((header().box().max.x - header().box().min.x)/header().cell_size() + EPS_L + 1.5f); m_access_mask.assign (header().vertex_count(),true); unpack_xz (vertex_position(header().box().max),m_max_x,m_max_z); #ifdef DEBUG # ifndef AI_COMPILER m_current_level_id = -1; m_current_actual = false; m_current_center = Fvector().set(flt_max,flt_max,flt_max); m_current_radius = Fvector().set(flt_max,flt_max,flt_max); # endif #endif } CLevelGraph::~CLevelGraph () { FS.r_close (m_reader); } u32 CLevelGraph::vertex (const Fvector &position) const { CLevelGraph::CPosition _node_position; vertex_position (_node_position,position); float min_dist = flt_max; u32 selected; set_invalid_vertex (selected); for (u32 i=0; i<header().vertex_count(); ++i) { float dist = distance(i,position); if (dist < min_dist) { min_dist = dist; selected = i; } } VERIFY (valid_vertex_id(selected)); return (selected); } u32 CLevelGraph::vertex (u32 current_node_id, const Fvector& position) const { START_PROFILE("Level_Graph::find vertex") #ifndef AI_COMPILER Device.Statistic->AI_Node.Begin (); #endif u32 id; if (valid_vertex_position(position)) { // so, our position is inside the level graph bounding box if (valid_vertex_id(current_node_id) && inside(vertex(current_node_id),position)) { // so, our node corresponds to the position #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif return (current_node_id); } // so, our node doesn't correspond to the position // try to search it with O(logN) time algorithm u32 _vertex_id = vertex_id(position); if (valid_vertex_id(_vertex_id)) { // so, there is a node which corresponds with x and z to the position bool ok = true; if (valid_vertex_id(current_node_id)) { { CVertex const &vertex = *this->vertex(current_node_id); for (u32 i=0; i<4; ++i) { if (vertex.link(i) == _vertex_id) { #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif // AI_COMPILER return (_vertex_id); } } } { CVertex const &vertex = *this->vertex(_vertex_id); for (u32 i=0; i<4; ++i) { if (vertex.link(i) == current_node_id) { #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif // AI_COMPILER return (_vertex_id); } } } float y0 = vertex_plane_y(current_node_id,position.x,position.z); float y1 = vertex_plane_y(_vertex_id,position.x,position.z); bool over0 = position.y > y0; bool over1 = position.y > y1; float y_dist0 = position.y - y0; float y_dist1 = position.y - y1; if (over0) { if (over1) { if (y_dist1 - y_dist0 > 1.f) ok = false; else ok = true; } else { if (y_dist0 - y_dist1 > 1.f) ok = false; else ok = true; } } else { ok = true; } } if (ok) { #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif return (_vertex_id); } } } if (!valid_vertex_id(current_node_id)) { // so, we do not have a correct current node // performing very slow full search id = vertex(position); VERIFY (valid_vertex_id(id)); #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif return (id); } u32 new_vertex_id = guess_vertex_id(current_node_id, position); if (new_vertex_id != current_node_id) return (new_vertex_id); // so, our position is outside the level graph bounding box // or // there is no node for the current position // try to search the nearest one iteratively SContour _contour; Fvector point; u32 best_vertex_id = current_node_id; contour (_contour,current_node_id); nearest (point,position,_contour); float best_distance_sqr = position.distance_to_sqr(point); const_iterator i,e; begin (current_node_id,i,e); for ( ; i != e; ++i) { u32 level_vertex_id = value(current_node_id,i); if (!valid_vertex_id(level_vertex_id)) continue; contour (_contour,level_vertex_id); nearest (point,position,_contour); float distance_sqr = position.distance_to_sqr(point); if (best_distance_sqr > distance_sqr) { best_distance_sqr = distance_sqr; best_vertex_id = level_vertex_id; } } #ifndef AI_COMPILER Device.Statistic->AI_Node.End(); #endif return (best_vertex_id); STOP_PROFILE } u32 CLevelGraph::vertex_id (const Fvector &position) const { VERIFY2 ( valid_vertex_position(position), make_string( "invalid position for CLevelGraph::vertex_id specified: [%f][%f][%f]", VPUSH(position) ) ); CPosition _vertex_position = vertex_position(position); CVertex *B = m_nodes; CVertex *E = m_nodes + header().vertex_count(); CVertex *I = std::lower_bound (B,E,_vertex_position.xz()); if ((I == E) || ((*I).position().xz() != _vertex_position.xz())) return (u32(-1)); u32 best_vertex_id = u32(I - B); float y = vertex_plane_y(best_vertex_id,position.x,position.z); for (++I; I != E; ++I) { if ((*I).position().xz() != _vertex_position.xz()) break; u32 new_vertex_id = u32(I - B); float _y = vertex_plane_y(new_vertex_id,position.x,position.z); if (y <= position.y) { // so, current node is under the specified position if (_y <= position.y) { // so, new node is under the specified position if (position.y - _y < position.y - y) { // so, new node is closer to the specified position y = _y; best_vertex_id = new_vertex_id; } } } else // so, current node is over the specified position if (_y <= position.y) { // so, new node is under the specified position y = _y; best_vertex_id = new_vertex_id; } else // so, new node is over the specified position if (_y - position.y < y - position.y) { // so, new node is closer to the specified position y = _y; best_vertex_id = new_vertex_id; } } return (best_vertex_id); } static const int max_guess_vertex_count = 4; u32 CLevelGraph::guess_vertex_id (u32 const &current_vertex_id, Fvector const &position) const { VERIFY (valid_vertex_id(current_vertex_id)); CPosition vertex_position; if (valid_vertex_position(position)) vertex_position = this->vertex_position(position); else vertex_position = vertex(current_vertex_id)->position(); u32 x, z; unpack_xz (vertex_position, x, z); SContour vertex_contour; contour (vertex_contour, current_vertex_id); Fvector best_point; float result_distance = nearest(best_point, position, vertex_contour); u32 result_vertex_id = current_vertex_id; CVertex const *B = m_nodes; CVertex const *E = m_nodes + header().vertex_count(); u32 start_x = (u32)_max( 0, int(x) - max_guess_vertex_count); u32 stop_x = _min( max_x(), x + (u32)max_guess_vertex_count); u32 start_z = (u32)_max( 0, int(z) - max_guess_vertex_count); u32 stop_z = _min( max_z(),z + (u32)max_guess_vertex_count); for (u32 i = start_x; i<=stop_x; ++i) { for (u32 j = start_z; j <= stop_z; ++j) { u32 test_xz = i*m_row_length + j; CVertex const *I = std::lower_bound(B,E,test_xz); if (I == E) continue; if ((*I).position().xz() != test_xz) continue; u32 best_vertex_id = u32(I - B); contour (vertex_contour, best_vertex_id); float best_distance = nearest(best_point, position, vertex_contour); for (++I; I != E; ++I) { if ((*I).position().xz() != test_xz) break; u32 vertex_id = u32(I - B); Fvector point; contour (vertex_contour, vertex_id); float distance = nearest(point, position, vertex_contour); if (distance >= best_distance) continue; best_point = point; best_distance = distance; best_vertex_id = vertex_id; } if (_abs(best_point.y - position.y) >= 3.f) continue; if (result_distance <= best_distance) continue; result_distance = best_distance; result_vertex_id = best_vertex_id; } } return (result_vertex_id); }
0
0.811164
1
0.811164
game-dev
MEDIA
0.405709
game-dev
0.933085
1
0.933085
tempo-sim/Tempo
4,422
External/Traffic/Source/MassTraffic/Private/MassTrafficSignInitIntersectionsProcessor.cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "MassTrafficSignInitIntersectionsProcessor.h" #include "MassTrafficFragments.h" #include "MassTrafficDelegates.h" #include "MassTrafficFieldOperations.h" #include "MassCrowdSubsystem.h" #include "MassExecutionContext.h" UMassTrafficSignInitIntersectionsProcessor::UMassTrafficSignInitIntersectionsProcessor() : EntityQuery(*this) { bAutoRegisterWithProcessingPhases = false; } #if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION < 6 void UMassTrafficSignInitIntersectionsProcessor::ConfigureQueries() #else void UMassTrafficSignInitIntersectionsProcessor::ConfigureQueries(const TSharedRef<FMassEntityManager>& EntityManager) #endif { EntityQuery.AddRequirement<FMassTrafficSignIntersectionFragment>(EMassFragmentAccess::ReadWrite); EntityQuery.AddRequirement<FTransformFragment>(EMassFragmentAccess::ReadWrite); EntityQuery.AddSubsystemRequirement<UMassCrowdSubsystem>(EMassFragmentAccess::ReadWrite); EntityQuery.AddSubsystemRequirement<UMassTrafficSubsystem>(EMassFragmentAccess::ReadWrite); ProcessorRequirements.AddSubsystemRequirement<UMassTrafficSubsystem>(EMassFragmentAccess::ReadWrite); } void UMassTrafficSignInitIntersectionsProcessor::Execute(FMassEntityManager& EntityManager, FMassExecutionContext& Context) { // Cast AuxData to required FMassTrafficSignIntersectionSpawnData FInstancedStruct& AuxInput = Context.GetMutableAuxData(); if (!ensure(AuxInput.GetPtr<FMassTrafficSignIntersectionSpawnData>())) { return; } FMassTrafficSignIntersectionSpawnData& TrafficSignIntersectionsSpawnData = AuxInput.GetMutable<FMassTrafficSignIntersectionSpawnData>(); // Process chunks int32 Offset = 0; #if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION < 6 EntityQuery.ForEachEntityChunk(EntityManager, Context, [&](FMassExecutionContext& QueryContext) #else EntityQuery.ForEachEntityChunk(Context, [&](FMassExecutionContext& QueryContext) #endif { // Get Mass crowd subsystem. UMassCrowdSubsystem* MassCrowdSubsystem = QueryContext.GetMutableSubsystem<UMassCrowdSubsystem>(); if (!ensureMsgf(MassCrowdSubsystem != nullptr, TEXT("Must get valid MassCrowdSubsystem in UMassTrafficSignInitIntersectionsProcessor::Execute."))) { return; } UMassTrafficSubsystem* MassTrafficSubsystem = QueryContext.GetMutableSubsystem<UMassTrafficSubsystem>(); if (!ensureMsgf(MassTrafficSubsystem != nullptr, TEXT("Must get valid MassTrafficSubsystem in UMassTrafficSignInitIntersectionsProcessor::Execute."))) { return; } const int32 NumEntities = QueryContext.GetNumEntities(); const TArrayView<FMassTrafficSignIntersectionFragment> TrafficSignIntersectionFragments = QueryContext.GetMutableFragmentView<FMassTrafficSignIntersectionFragment>(); const TArrayView<FTransformFragment> TransformFragments = QueryContext.GetMutableFragmentView<FTransformFragment>(); // Swap in pre-initialized fragments // Note: We do a Memswap here instead of a Memcpy as Memcpy would copy the internal TArray // data pointers from the AuxInput TArrays which will be freed at the end of spawn FMemory::Memswap(TrafficSignIntersectionFragments.GetData(), &TrafficSignIntersectionsSpawnData.TrafficSignIntersectionFragments[Offset], sizeof(FMassTrafficSignIntersectionFragment) * NumEntities); // Swap in transforms check(sizeof(FTransformFragment) == sizeof(FTransform)); FMemory::Memswap(TransformFragments.GetData(), &TrafficSignIntersectionsSpawnData.TrafficSignIntersectionTransforms[Offset], sizeof(FTransformFragment) * NumEntities); // Init intersection lane states - for (int32 EntityIndex = 0; EntityIndex < NumEntities; ++EntityIndex) { const FMassEntityHandle IntersectionEntityHandle = QueryContext.GetEntity(EntityIndex); FMassTrafficSignIntersectionFragment& TrafficSignIntersectionFragment = TrafficSignIntersectionFragments[EntityIndex]; // Tell each of the traffic sign controlled lanes which FMassTrafficSignIntersectionFragment is associated with it. for (FMassTrafficSignIntersectionSide& IntersectionSide : TrafficSignIntersectionFragment.IntersectionSides) { for (auto& VehicleIntersectionLane : IntersectionSide.VehicleIntersectionLanes) { VehicleIntersectionLane.Key->IntersectionEntityHandle = IntersectionEntityHandle; } } TrafficSignIntersectionFragment.RestartIntersection(*MassCrowdSubsystem); } Offset += NumEntities; }); }
0
0.781803
1
0.781803
game-dev
MEDIA
0.446481
game-dev
0.954274
1
0.954274
Goob-Station/Goob-Station
8,590
Content.Shared/Weapons/Ranged/Systems/SharedGunSystem.Magazine.cs
// SPDX-FileCopyrightText: 2022 ElectroJr <leonsfriedrich@gmail.com> // SPDX-FileCopyrightText: 2022 Kara <lunarautomaton6@gmail.com> // SPDX-FileCopyrightText: 2022 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 T-Stalker <43253663+DogZeroX@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 T-Stalker <le0nel_1van@hotmail.com> // SPDX-FileCopyrightText: 2022 metalgearsloth <metalgearsloth@gmail.com> // SPDX-FileCopyrightText: 2023 Scribbles0 <91828755+Scribbles0@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 TaralGit <76408146+TaralGit@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 and_a <and_a@DESKTOP-RJENGIR> // SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 metalgearsloth <comedian_vs_clown@hotmail.com> // SPDX-FileCopyrightText: 2024 DrSmugleaf <10968691+DrSmugleaf@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 geraeumig <171753363+geraeumig@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 geraeumig <alfenos@proton.me> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aviu00 <93730715+Aviu00@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 slarticodefast <161409025+slarticodefast@users.noreply.github.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Shared.Examine; using Content.Shared.Interaction.Events; using Content.Shared.Verbs; using Content.Shared.Weapons.Ranged.Events; using Robust.Shared.Containers; namespace Content.Shared.Weapons.Ranged.Systems; public abstract partial class SharedGunSystem { protected const string MagazineSlot = "gun_magazine"; protected virtual void InitializeMagazine() { SubscribeLocalEvent<MagazineAmmoProviderComponent, MapInitEvent>(OnMagazineMapInit); SubscribeLocalEvent<MagazineAmmoProviderComponent, TakeAmmoEvent>(OnMagazineTakeAmmo); SubscribeLocalEvent<MagazineAmmoProviderComponent, GetAmmoCountEvent>(OnMagazineAmmoCount); SubscribeLocalEvent<MagazineAmmoProviderComponent, GetVerbsEvent<AlternativeVerb>>(OnMagazineVerb); SubscribeLocalEvent<MagazineAmmoProviderComponent, EntInsertedIntoContainerMessage>(OnMagazineSlotChange); SubscribeLocalEvent<MagazineAmmoProviderComponent, EntRemovedFromContainerMessage>(OnMagazineSlotChange); SubscribeLocalEvent<MagazineAmmoProviderComponent, UseInHandEvent>(OnMagazineUse); SubscribeLocalEvent<MagazineAmmoProviderComponent, ExaminedEvent>(OnMagazineExamine); } private void OnMagazineMapInit(Entity<MagazineAmmoProviderComponent> ent, ref MapInitEvent args) { MagazineSlotChanged(ent); } private void OnMagazineExamine(EntityUid uid, MagazineAmmoProviderComponent component, ExaminedEvent args) { if (!args.IsInDetailsRange) return; var (count, _) = GetMagazineCountCapacity(uid, component); args.PushMarkup(Loc.GetString("gun-magazine-examine", ("color", AmmoExamineColor), ("count", count))); } private void OnMagazineUse(EntityUid uid, MagazineAmmoProviderComponent component, UseInHandEvent args) { // not checking for args.Handled or marking as such because we only relay the event to the magazine entity var magEnt = GetMagazineEntity(uid); if (magEnt == null) return; RaiseLocalEvent(magEnt.Value, args); UpdateAmmoCount(uid); UpdateMagazineAppearance(uid, component, magEnt.Value); } private void OnMagazineVerb(EntityUid uid, MagazineAmmoProviderComponent component, GetVerbsEvent<AlternativeVerb> args) { if (!args.CanInteract || !args.CanAccess) return; var magEnt = GetMagazineEntity(uid); if (magEnt != null) { RaiseLocalEvent(magEnt.Value, args); UpdateMagazineAppearance(magEnt.Value, component, magEnt.Value); } } protected virtual void OnMagazineSlotChange(EntityUid uid, MagazineAmmoProviderComponent component, ContainerModifiedMessage args) { if (MagazineSlot != args.Container.ID) return; MagazineSlotChanged((uid, component)); } private void MagazineSlotChanged(Entity<MagazineAmmoProviderComponent> ent) { UpdateAmmoCount(ent); if (!TryComp<AppearanceComponent>(ent, out var appearance)) return; var magEnt = GetMagazineEntity(ent); Appearance.SetData(ent, AmmoVisuals.MagLoaded, magEnt != null, appearance); if (magEnt != null) { UpdateMagazineAppearance(ent, ent, magEnt.Value); } } protected (int, int) GetMagazineCountCapacity(EntityUid uid, MagazineAmmoProviderComponent component) { var count = 0; var capacity = 1; var magEnt = GetMagazineEntity(uid); if (magEnt != null) { var ev = new GetAmmoCountEvent(); RaiseLocalEvent(magEnt.Value, ref ev, false); count += ev.Count; capacity += ev.Capacity; } return (count, capacity); } public EntityUid? GetMagazineEntity(EntityUid uid) // Goob edit { if (!Containers.TryGetContainer(uid, MagazineSlot, out var container) || container is not ContainerSlot slot) { return null; } return slot.ContainedEntity; } private void OnMagazineAmmoCount(EntityUid uid, MagazineAmmoProviderComponent component, ref GetAmmoCountEvent args) { var magEntity = GetMagazineEntity(uid); if (magEntity == null) return; RaiseLocalEvent(magEntity.Value, ref args); } private void OnMagazineTakeAmmo(EntityUid uid, MagazineAmmoProviderComponent component, TakeAmmoEvent args) { var magEntity = GetMagazineEntity(uid); TryComp<AppearanceComponent>(uid, out var appearance); if (magEntity == null) { Appearance.SetData(uid, AmmoVisuals.MagLoaded, false, appearance); return; } // Pass the event onwards. RaiseLocalEvent(magEntity.Value, args); // Should be Dirtied by what other ammoprovider is handling it. var ammoEv = new GetAmmoCountEvent(); RaiseLocalEvent(magEntity.Value, ref ammoEv); FinaliseMagazineTakeAmmo(uid, component, ammoEv.Count, ammoEv.Capacity, args.User, appearance); } private void FinaliseMagazineTakeAmmo(EntityUid uid, MagazineAmmoProviderComponent component, int count, int capacity, EntityUid? user, AppearanceComponent? appearance) { // If no ammo then check for autoeject var ejectMag = component.AutoEject && count == 0; if (ejectMag) { EjectMagazine(uid, component); Audio.PlayPredicted(component.SoundAutoEject, uid, user); } UpdateMagazineAppearance(uid, appearance, !ejectMag, count, capacity); } private void UpdateMagazineAppearance(EntityUid uid, MagazineAmmoProviderComponent component, EntityUid magEnt) { TryComp<AppearanceComponent>(uid, out var appearance); var count = 0; var capacity = 0; if (TryComp<AppearanceComponent>(magEnt, out var magAppearance)) { Appearance.TryGetData<int>(magEnt, AmmoVisuals.AmmoCount, out var addCount, magAppearance); Appearance.TryGetData<int>(magEnt, AmmoVisuals.AmmoMax, out var addCapacity, magAppearance); count += addCount; capacity += addCapacity; } UpdateMagazineAppearance(uid, appearance, true, count, capacity); } private void UpdateMagazineAppearance(EntityUid uid, AppearanceComponent? appearance, bool magLoaded, int count, int capacity) { if (appearance == null) return; // Copy the magazine's appearance data Appearance.SetData(uid, AmmoVisuals.MagLoaded, magLoaded, appearance); Appearance.SetData(uid, AmmoVisuals.HasAmmo, count != 0, appearance); Appearance.SetData(uid, AmmoVisuals.AmmoCount, count, appearance); Appearance.SetData(uid, AmmoVisuals.AmmoMax, capacity, appearance); } private void EjectMagazine(EntityUid uid, MagazineAmmoProviderComponent component) { var ent = GetMagazineEntity(uid); if (ent == null) return; _slots.TryEject(uid, MagazineSlot, null, out var a, excludeUserAudio: true); } }
0
0.945874
1
0.945874
game-dev
MEDIA
0.932278
game-dev
0.990945
1
0.990945
alliedmodders/hl2sdk
4,802
common/GameUI/IGameUI.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef IGAMEUI_H #define IGAMEUI_H #ifdef _WIN32 #pragma once #endif #include "interface.h" #include "vgui/IPanel.h" #if !defined( _X360 ) #include "xbox/xboxstubs.h" #endif // reasons why the user can't connect to a game server enum ESteamLoginFailure { STEAMLOGINFAILURE_NONE, STEAMLOGINFAILURE_BADTICKET, STEAMLOGINFAILURE_NOSTEAMLOGIN, STEAMLOGINFAILURE_VACBANNED, STEAMLOGINFAILURE_LOGGED_IN_ELSEWHERE }; enum ESystemNotify { SYSTEMNOTIFY_STORAGEDEVICES_CHANGED, SYSTEMNOTIFY_USER_SIGNEDIN, SYSTEMNOTIFY_USER_SIGNEDOUT, SYSTEMNOTIFY_XUIOPENING, SYSTEMNOTIFY_XUICLOSED, SYSTEMNOTIFY_INVITE_SHUTDOWN, // Cross-game invite is causing us to shutdown }; //----------------------------------------------------------------------------- // Purpose: contains all the functions that the GameUI dll exports //----------------------------------------------------------------------------- abstract_class IGameUI { public: // initialization/shutdown virtual void Initialize( CreateInterfaceFn appFactory ) = 0; virtual void PostInit() = 0; // connect to other interfaces at the same level (gameui.dll/server.dll/client.dll) virtual void Connect( CreateInterfaceFn gameFactory ) = 0; virtual void Start() = 0; virtual void Shutdown() = 0; virtual void RunFrame() = 0; // notifications virtual void OnGameUIActivated() = 0; virtual void OnGameUIHidden() = 0; // OLD: Use OnConnectToServer2 virtual void OLD_OnConnectToServer(const char *game, int IP, int port) = 0; virtual void OnDisconnectFromServer_OLD( uint8 eSteamLoginFailure, const char *username ) = 0; virtual void OnLevelLoadingStarted(bool bShowProgressDialog) = 0; virtual void OnLevelLoadingFinished(bool bError, const char *failureReason, const char *extendedReason) = 0; // level loading progress, returns true if the screen needs updating virtual bool UpdateProgressBar(float progress, const char *statusText) = 0; // Shows progress desc, returns previous setting... (used with custom progress bars ) virtual bool SetShowProgressText( bool show ) = 0; // !!!!!!!!!members added after "GameUI011" initial release!!!!!!!!!!!!!!!!!!! virtual void ShowNewGameDialog( int chapter ) = 0; // Xbox 360 virtual void SessionNotification( const int notification, const int param = 0 ) = 0; virtual void SystemNotification( const int notification ) = 0; virtual void ShowMessageDialog( const uint nType, vgui::Panel *pOwner ) = 0; virtual void UpdatePlayerInfo( uint64 nPlayerId, const char *pName, int nTeam, byte cVoiceState, int nPlayersNeeded, bool bHost ) = 0; virtual void SessionSearchResult( int searchIdx, void *pHostData, XSESSION_SEARCHRESULT *pResult, int ping ) = 0; virtual void OnCreditsFinished( void ) = 0; // inserts specified panel as background for level load dialog virtual void SetLoadingBackgroundDialog( vgui::VPANEL panel ) = 0; // Bonus maps interfaces virtual void BonusMapUnlock( const char *pchFileName = NULL, const char *pchMapName = NULL ) = 0; virtual void BonusMapComplete( const char *pchFileName = NULL, const char *pchMapName = NULL ) = 0; virtual void BonusMapChallengeUpdate( const char *pchFileName, const char *pchMapName, const char *pchChallengeName, int iBest ) = 0; virtual void BonusMapChallengeNames( char *pchFileName, char *pchMapName, char *pchChallengeName ) = 0; virtual void BonusMapChallengeObjectives( int &iBronze, int &iSilver, int &iGold ) = 0; virtual void BonusMapDatabaseSave( void ) = 0; virtual int BonusMapNumAdvancedCompleted( void ) = 0; virtual void BonusMapNumMedals( int piNumMedals[ 3 ] ) = 0; virtual void OnConnectToServer2(const char *game, int IP, int connectionPort, int queryPort) = 0; // X360 Storage device validation: // returns true right away if storage device has been previously selected. // otherwise returns false and will set the variable pointed by pStorageDeviceValidated to 1 // once the storage device is selected by user. virtual bool ValidateStorageDevice( int *pStorageDeviceValidated ) = 0; virtual void SetProgressOnStart() = 0; virtual void OnDisconnectFromServer( uint8 eSteamLoginFailure ) = 0; virtual void OnConfirmQuit( void ) = 0; virtual bool IsMainMenuVisible( void ) = 0; // Client DLL is providing us with a panel that it wants to replace the main menu with virtual void SetMainMenuOverride( vgui::VPANEL panel ) = 0; // Client DLL is telling us that a main menu command was issued, probably from its custom main menu panel virtual void SendMainMenuCommand( const char *pszCommand ) = 0; }; #define GAMEUI_INTERFACE_VERSION "GameUI011" #endif // IGAMEUI_H
0
0.918774
1
0.918774
game-dev
MEDIA
0.811329
game-dev
0.568095
1
0.568095
tgstation/tgstation
7,692
code/datums/components/cleaner.dm
/** * Component that can be used to clean things. * Takes care of duration, cleaning skill and special cleaning interactions. * A callback can be set by the datum holding the cleaner to add custom functionality. * Soap uses a callback to decrease the amount of uses it has left after cleaning for example. */ /datum/component/cleaner /// The time it takes to clean something, without reductions from the cleaning skill modifier. var/base_cleaning_duration /// Offsets the cleaning duration modifier that you get from your cleaning skill, the duration won't be modified to be more than the base duration. var/skill_duration_modifier_offset /// Determines what this cleaner can wash off, [the available options are found here](code/__DEFINES/cleaning.html). var/cleaning_strength /// Gets called before you start cleaning, returns TRUE/FALSE whether the clean should actually wash tiles, or DO_NOT_CLEAN to not clean at all. var/datum/callback/pre_clean_callback /// Gets called when something is successfully cleaned. var/datum/callback/on_cleaned_callback /datum/component/cleaner/Initialize( base_cleaning_duration = 3 SECONDS, skill_duration_modifier_offset = 0, cleaning_strength = CLEAN_SCRUB, datum/callback/pre_clean_callback = null, datum/callback/on_cleaned_callback = null, ) src.base_cleaning_duration = base_cleaning_duration src.skill_duration_modifier_offset = skill_duration_modifier_offset src.cleaning_strength = cleaning_strength src.pre_clean_callback = pre_clean_callback src.on_cleaned_callback = on_cleaned_callback /datum/component/cleaner/Destroy(force) pre_clean_callback = null on_cleaned_callback = null return ..() /datum/component/cleaner/RegisterWithParent() if(ismob(parent)) RegisterSignal(parent, COMSIG_LIVING_UNARMED_ATTACK, PROC_REF(on_unarmed_attack)) if(isitem(parent)) RegisterSignal(parent, COMSIG_ITEM_INTERACTING_WITH_ATOM, PROC_REF(on_interaction)) /datum/component/cleaner/UnregisterFromParent() UnregisterSignal(parent, list( COMSIG_ITEM_INTERACTING_WITH_ATOM, COMSIG_LIVING_UNARMED_ATTACK, )) /** * Handles the COMSIG_LIVING_UNARMED_ATTACK signal used for cleanbots * Redirects to afterattack, while setting parent (the bot) as user. */ /datum/component/cleaner/proc/on_unarmed_attack(datum/source, atom/target, proximity_flags, modifiers) SIGNAL_HANDLER if(on_interaction(source, source, target, modifiers) & ITEM_INTERACT_ANY_BLOCKER) return COMPONENT_CANCEL_ATTACK_CHAIN return NONE /** * Handles the COMSIG_ITEM_INTERACTING_WITH_ATOM signal by calling the clean proc. */ /datum/component/cleaner/proc/on_interaction(datum/source, mob/living/user, atom/target, list/modifiers) SIGNAL_HANDLER if(isitem(source) && SHOULD_SKIP_INTERACTION(target, source, user)) return NONE var/call_wash = TRUE var/give_xp = TRUE if(pre_clean_callback) var/callback_return = pre_clean_callback.Invoke(source, target, user) if(callback_return & CLEAN_BLOCKED) return (callback_return & CLEAN_DONT_BLOCK_INTERACTION) ? NONE : ITEM_INTERACT_BLOCKING if(callback_return & CLEAN_NO_WASH) call_wash = FALSE if(callback_return & CLEAN_NO_XP) give_xp = FALSE INVOKE_ASYNC(src, PROC_REF(clean), source, target, user, call_wash, give_xp) return ITEM_INTERACT_SUCCESS /** * Cleans something using this cleaner. * The cleaning duration is modified by the cleaning skill of the user. * Successfully cleaning gives cleaning experience to the user and invokes the on_cleaned_callback. * * Arguments * * source the datum that sent the signal to start cleaning * * target the thing being cleaned * * user the person doing the cleaning * * call_wash set this to false if the target should not be wash()ed * * grant_xp set this to false if the user should not be granted cleaning experience */ /datum/component/cleaner/proc/clean(datum/source, atom/target, mob/living/user, call_wash = TRUE, grant_xp = TRUE) //make sure we don't attempt to clean something while it's already being cleaned if(HAS_TRAIT(target, TRAIT_CURRENTLY_CLEANING) || (SEND_SIGNAL(target, COMSIG_ATOM_PRE_CLEAN, user) & COMSIG_ATOM_CANCEL_CLEAN)) return //add the trait and overlay ADD_TRAIT(target, TRAIT_CURRENTLY_CLEANING, REF(src)) // We need to update our planes on overlay changes RegisterSignal(target, COMSIG_MOVABLE_Z_CHANGED, PROC_REF(cleaning_target_moved)) var/mutable_appearance/low_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, target, GAME_PLANE) var/mutable_appearance/high_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, target, ABOVE_GAME_PLANE) var/list/icon_offsets = target.get_oversized_icon_offsets() low_bubble.pixel_w = icon_offsets["x"] low_bubble.pixel_z = icon_offsets["y"] high_bubble.pixel_w = icon_offsets["x"] high_bubble.pixel_z = icon_offsets["y"] if(target.plane > low_bubble.plane) //check if the higher overlay is necessary target.add_overlay(high_bubble) else if(target.plane == low_bubble.plane) if(target.layer > low_bubble.layer) target.add_overlay(high_bubble) else target.add_overlay(low_bubble) else //(target.plane < low_bubble.plane) target.add_overlay(low_bubble) //set the cleaning duration var/cleaning_duration = base_cleaning_duration if(user.mind) //higher cleaning skill can make the duration shorter //offsets the multiplier you get from cleaning skill, but doesn't allow the duration to be longer than the base duration cleaning_duration = (cleaning_duration * min(user.mind.get_skill_modifier(/datum/skill/cleaning, SKILL_SPEED_MODIFIER)+skill_duration_modifier_offset, 1)) // Assoc list, collects all items being cleaned with its value being any blood on it var/list/all_cleaned = list() all_cleaned[target] = GET_ATOM_BLOOD_DNA(target) || list() //do the cleaning var/clean_succeeded = FALSE if(do_after(user, cleaning_duration, target = target)) clean_succeeded = TRUE for(var/obj/effect/decal/cleanable/cleanable_decal in target) //it's important to do this before you wash all of the cleanables off if(call_wash && grant_xp) user.mind?.adjust_experience(/datum/skill/cleaning, round(cleanable_decal.beauty / CLEAN_SKILL_BEAUTY_ADJUSTMENT)) all_cleaned[cleanable_decal] = GET_ATOM_BLOOD_DNA(cleanable_decal) if(call_wash && target.wash(cleaning_strength) && grant_xp) user.mind?.adjust_experience(/datum/skill/cleaning, round(CLEAN_SKILL_GENERIC_WASH_XP)) on_cleaned_callback?.Invoke(source, target, user, clean_succeeded, all_cleaned) //remove the cleaning overlay target.cut_overlay(low_bubble) target.cut_overlay(high_bubble) UnregisterSignal(target, COMSIG_MOVABLE_Z_CHANGED) REMOVE_TRAIT(target, TRAIT_CURRENTLY_CLEANING, REF(src)) /datum/component/cleaner/proc/cleaning_target_moved(atom/movable/source, turf/old_turf, turf/new_turf, same_z_layer) if(same_z_layer) return // First, get rid of the old overlay var/mutable_appearance/old_low_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, old_turf, GAME_PLANE) var/mutable_appearance/old_high_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, old_turf, ABOVE_GAME_PLANE) source.cut_overlay(old_low_bubble) source.cut_overlay(old_high_bubble) // Now, add the new one var/mutable_appearance/new_low_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, new_turf, GAME_PLANE) var/mutable_appearance/new_high_bubble = mutable_appearance('icons/effects/effects.dmi', "bubbles", CLEANABLE_OBJECT_LAYER, new_turf, ABOVE_GAME_PLANE) source.add_overlay(new_low_bubble) source.add_overlay(new_high_bubble)
0
0.821571
1
0.821571
game-dev
MEDIA
0.394886
game-dev
0.904753
1
0.904753
evestera/svg-halftone
1,660
svg-halftone-wasm/src/lib.rs
use cfg_if::cfg_if; use std::str::FromStr; use wasm_bindgen::prelude::*; use svg_halftone_lib::{create_halftone_svg, image, Grid, Options, Shape}; cfg_if! { // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function to get better error messages if we ever panic. if #[cfg(feature = "console_error_panic_hook")] { use console_error_panic_hook::set_once as set_panic_hook; } else { #[inline] fn set_panic_hook() {} } } cfg_if! { // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. if #[cfg(feature = "wee_alloc")] { #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; } } #[wasm_bindgen] pub fn run( bytes: &[u8], output_width: f64, spacing: f64, shape: &str, grid: &str, invert: bool, cut_paths: bool, ) -> Option<String> { set_panic_hook(); let img = match image::load_from_memory(bytes) { Ok(img) => img, Err(_) => return None }; let (shape, grid) = match (Shape::from_str(shape).ok(), Grid::from_str(grid).ok()) { (Some(shape), Some(grid)) => (shape, grid), (Some(shape), None) => (shape, Grid::from(shape)), (None, Some(grid)) => (Shape::from(grid), grid), (None, None) => (Shape::Circle, Grid::Rect), }; let data = create_halftone_svg(Options { image: img, output_width, spacing, shape, grid, invert, cut_paths, contrast: None, multi_sample: true, }); Some(format!("{}", data)) }
0
0.987505
1
0.987505
game-dev
MEDIA
0.477515
game-dev,graphics-rendering
0.90355
1
0.90355
Sigma-Skidder-Team/SigmaRebase
41,113
src/main/java/net/optifine/CustomItems.java
package net.optifine; import com.mojang.blaze3d.platform.GlStateManager; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.entity.model.EntityModel; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ItemModelGenerator; import net.minecraft.client.renderer.model.ModelBakery; import net.minecraft.client.renderer.texture.AtlasTexture; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.LivingEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ArmorItem; import net.minecraft.item.EnchantedBookItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.item.PotionItem; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.potion.Effect; import net.minecraft.resources.IResourcePack; import net.minecraft.resources.ResourcePackType; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Util; import net.minecraft.util.registry.Registry; import net.optifine.config.NbtTagValue; import net.optifine.render.Blender; import net.optifine.shaders.Shaders; import net.optifine.shaders.ShadersRender; import net.optifine.util.EnchantmentUtils; import net.optifine.util.PropertiesOrdered; import net.optifine.util.ResUtils; import net.optifine.util.StrUtils; public class CustomItems { private static CustomItemProperties[][] itemProperties = (CustomItemProperties[][])null; private static CustomItemProperties[][] enchantmentProperties = (CustomItemProperties[][])null; private static Map mapPotionIds = null; private static ItemModelGenerator itemModelGenerator = new ItemModelGenerator(); private static boolean useGlint = true; private static boolean renderOffHand = false; public static final int MASK_POTION_SPLASH = 16384; public static final int MASK_POTION_NAME = 63; public static final int MASK_POTION_EXTENDED = 64; public static final String KEY_TEXTURE_OVERLAY = "texture.potion_overlay"; public static final String KEY_TEXTURE_SPLASH = "texture.potion_bottle_splash"; public static final String KEY_TEXTURE_DRINKABLE = "texture.potion_bottle_drinkable"; public static final String DEFAULT_TEXTURE_OVERLAY = "item/potion_overlay"; public static final String DEFAULT_TEXTURE_SPLASH = "item/potion_bottle_splash"; public static final String DEFAULT_TEXTURE_DRINKABLE = "item/potion_bottle_drinkable"; private static final int[][] EMPTY_INT2_ARRAY = new int[0][]; private static final Map<String, Integer> mapPotionDamages = makeMapPotionDamages(); private static final String TYPE_POTION_NORMAL = "normal"; private static final String TYPE_POTION_SPLASH = "splash"; private static final String TYPE_POTION_LINGER = "linger"; public static void update() { itemProperties = (CustomItemProperties[][])null; enchantmentProperties = (CustomItemProperties[][])null; useGlint = true; if (Config.isCustomItems()) { readCitProperties("optifine/cit.properties"); IResourcePack[] airesourcepack = Config.getResourcePacks(); for (int i = airesourcepack.length - 1; i >= 0; --i) { IResourcePack iresourcepack = airesourcepack[i]; update(iresourcepack); } update(Config.getDefaultResourcePack()); if (itemProperties.length <= 0) { itemProperties = (CustomItemProperties[][])null; } if (enchantmentProperties.length <= 0) { enchantmentProperties = (CustomItemProperties[][])null; } } } private static void readCitProperties(String fileName) { try { ResourceLocation resourcelocation = new ResourceLocation(fileName); InputStream inputstream = Config.getResourceStream(resourcelocation); if (inputstream == null) { return; } Config.dbg("CustomItems: Loading " + fileName); Properties properties = new PropertiesOrdered(); properties.load(inputstream); inputstream.close(); useGlint = Config.parseBoolean(properties.getProperty("useGlint"), true); } catch (FileNotFoundException filenotfoundexception) { return; } catch (IOException ioexception) { ioexception.printStackTrace(); } } private static void update(IResourcePack rp) { String[] astring = ResUtils.collectFiles(rp, "optifine/cit/", ".properties", (String[])null); Map<String, CustomItemProperties> map = makeAutoImageProperties(rp); if (map.size() > 0) { Set<String> set = map.keySet(); String[] astring1 = set.toArray(new String[set.size()]); astring = (String[])Config.addObjectsToArray(astring, astring1); } Arrays.sort((Object[])astring); List<List<CustomItemProperties>> list = makePropertyList(itemProperties); List<List<CustomItemProperties>> list1 = makePropertyList(enchantmentProperties); for (int i = 0; i < astring.length; ++i) { String s = astring[i]; Config.dbg("CustomItems: " + s); try { CustomItemProperties customitemproperties = null; if (map.containsKey(s)) { customitemproperties = map.get(s); } if (customitemproperties == null) { ResourceLocation resourcelocation = new ResourceLocation(s); InputStream inputstream = rp.getResourceStream(ResourcePackType.CLIENT_RESOURCES, resourcelocation); if (inputstream == null) { Config.warn("CustomItems file not found: " + s); continue; } Properties properties = new PropertiesOrdered(); properties.load(inputstream); inputstream.close(); customitemproperties = new CustomItemProperties(properties, s); } if (customitemproperties.isValid(s)) { addToItemList(customitemproperties, list); addToEnchantmentList(customitemproperties, list1); } } catch (FileNotFoundException filenotfoundexception) { Config.warn("CustomItems file not found: " + s); } catch (Exception exception) { exception.printStackTrace(); } } itemProperties = propertyListToArray(list); enchantmentProperties = propertyListToArray(list1); Comparator comparator = getPropertiesComparator(); for (int j = 0; j < itemProperties.length; ++j) { CustomItemProperties[] acustomitemproperties = itemProperties[j]; if (acustomitemproperties != null) { Arrays.sort(acustomitemproperties, comparator); } } for (int k = 0; k < enchantmentProperties.length; ++k) { CustomItemProperties[] acustomitemproperties1 = enchantmentProperties[k]; if (acustomitemproperties1 != null) { Arrays.sort(acustomitemproperties1, comparator); } } } private static Comparator getPropertiesComparator() { return new Comparator() { public int compare(Object o1, Object o2) { CustomItemProperties customitemproperties = (CustomItemProperties)o1; CustomItemProperties customitemproperties1 = (CustomItemProperties)o2; if (customitemproperties.layer != customitemproperties1.layer) { return customitemproperties.layer - customitemproperties1.layer; } else if (customitemproperties.weight != customitemproperties1.weight) { return customitemproperties1.weight - customitemproperties.weight; } else { return !customitemproperties.basePath.equals(customitemproperties1.basePath) ? customitemproperties.basePath.compareTo(customitemproperties1.basePath) : customitemproperties.name.compareTo(customitemproperties1.name); } } }; } public static void updateIcons(AtlasTexture textureMap) { for (CustomItemProperties customitemproperties : getAllProperties()) { customitemproperties.updateIcons(textureMap); } } public static void refreshIcons(AtlasTexture textureMap) { for (CustomItemProperties customitemproperties : getAllProperties()) { customitemproperties.refreshIcons(textureMap); } } public static void loadModels(ModelBakery modelBakery) { for (CustomItemProperties customitemproperties : getAllProperties()) { customitemproperties.loadModels(modelBakery); } } public static void updateModels() { for (CustomItemProperties customitemproperties : getAllProperties()) { if (customitemproperties.type == 1) { AtlasTexture atlastexture = Config.getTextureMap(); customitemproperties.updateModelTexture(atlastexture, itemModelGenerator); customitemproperties.updateModelsFull(); } } } private static List<CustomItemProperties> getAllProperties() { List<CustomItemProperties> list = new ArrayList<>(); addAll(itemProperties, list); addAll(enchantmentProperties, list); return list; } private static void addAll(CustomItemProperties[][] cipsArr, List<CustomItemProperties> list) { if (cipsArr != null) { for (int i = 0; i < cipsArr.length; ++i) { CustomItemProperties[] acustomitemproperties = cipsArr[i]; if (acustomitemproperties != null) { for (int j = 0; j < acustomitemproperties.length; ++j) { CustomItemProperties customitemproperties = acustomitemproperties[j]; if (customitemproperties != null) { list.add(customitemproperties); } } } } } } private static Map<String, CustomItemProperties> makeAutoImageProperties(IResourcePack rp) { Map<String, CustomItemProperties> map = new HashMap<>(); map.putAll(makePotionImageProperties(rp, "normal", Registry.ITEM.getKey(Items.POTION))); map.putAll(makePotionImageProperties(rp, "splash", Registry.ITEM.getKey(Items.SPLASH_POTION))); map.putAll(makePotionImageProperties(rp, "linger", Registry.ITEM.getKey(Items.LINGERING_POTION))); return map; } private static Map<String, CustomItemProperties> makePotionImageProperties(IResourcePack rp, String type, ResourceLocation itemId) { Map<String, CustomItemProperties> map = new HashMap<>(); String s = type + "/"; String[] astring = new String[] {"optifine/cit/potion/" + s, "optifine/cit/Potion/" + s}; String[] astring1 = new String[] {".png"}; String[] astring2 = ResUtils.collectFiles(rp, astring, astring1); for (int i = 0; i < astring2.length; ++i) { String s1 = astring2[i]; String name = StrUtils.removePrefixSuffix(s1, astring, astring1); Properties properties = makePotionProperties(name, type, itemId, s1); if (properties != null) { String s3 = StrUtils.removeSuffix(s1, astring1) + ".properties"; CustomItemProperties customitemproperties = new CustomItemProperties(properties, s3); map.put(s3, customitemproperties); } } return map; } private static Properties makePotionProperties(String name, String type, ResourceLocation itemId, String path) { if (StrUtils.endsWith(name, new String[] {"_n", "_s"})) { return null; } else if (name.equals("empty") && type.equals("normal")) { itemId = Registry.ITEM.getKey(Items.GLASS_BOTTLE); Properties properties = new PropertiesOrdered(); properties.put("type", "item"); properties.put("items", itemId.toString()); return properties; } else { int[] aint = (int[])getMapPotionIds().get(name); if (aint == null) { Config.warn("Potion not found for image: " + path); return null; } else { StringBuffer stringbuffer = new StringBuffer(); for (int i = 0; i < aint.length; ++i) { int j = aint[i]; if (type.equals("splash")) { j |= 16384; } if (i > 0) { stringbuffer.append(" "); } stringbuffer.append(j); } int k = 16447; if (name.equals("water") || name.equals("mundane")) { k |= 64; } Properties properties1 = new PropertiesOrdered(); properties1.put("type", "item"); properties1.put("items", itemId.toString()); properties1.put("damage", stringbuffer.toString()); properties1.put("damageMask", "" + k); if (type.equals("splash")) { properties1.put("texture.potion_bottle_splash", name); } else { properties1.put("texture.potion_bottle_drinkable", name); } return properties1; } } } private static Map getMapPotionIds() { if (mapPotionIds == null) { mapPotionIds = new LinkedHashMap(); mapPotionIds.put("water", getPotionId(0, 0)); mapPotionIds.put("awkward", getPotionId(0, 1)); mapPotionIds.put("thick", getPotionId(0, 2)); mapPotionIds.put("potent", getPotionId(0, 3)); mapPotionIds.put("regeneration", getPotionIds(1)); mapPotionIds.put("movespeed", getPotionIds(2)); mapPotionIds.put("fireresistance", getPotionIds(3)); mapPotionIds.put("poison", getPotionIds(4)); mapPotionIds.put("heal", getPotionIds(5)); mapPotionIds.put("nightvision", getPotionIds(6)); mapPotionIds.put("clear", getPotionId(7, 0)); mapPotionIds.put("bungling", getPotionId(7, 1)); mapPotionIds.put("charming", getPotionId(7, 2)); mapPotionIds.put("rank", getPotionId(7, 3)); mapPotionIds.put("weakness", getPotionIds(8)); mapPotionIds.put("damageboost", getPotionIds(9)); mapPotionIds.put("moveslowdown", getPotionIds(10)); mapPotionIds.put("leaping", getPotionIds(11)); mapPotionIds.put("harm", getPotionIds(12)); mapPotionIds.put("waterbreathing", getPotionIds(13)); mapPotionIds.put("invisibility", getPotionIds(14)); mapPotionIds.put("thin", getPotionId(15, 0)); mapPotionIds.put("debonair", getPotionId(15, 1)); mapPotionIds.put("sparkling", getPotionId(15, 2)); mapPotionIds.put("stinky", getPotionId(15, 3)); mapPotionIds.put("mundane", getPotionId(0, 4)); mapPotionIds.put("speed", mapPotionIds.get("movespeed")); mapPotionIds.put("fire_resistance", mapPotionIds.get("fireresistance")); mapPotionIds.put("instant_health", mapPotionIds.get("heal")); mapPotionIds.put("night_vision", mapPotionIds.get("nightvision")); mapPotionIds.put("strength", mapPotionIds.get("damageboost")); mapPotionIds.put("slowness", mapPotionIds.get("moveslowdown")); mapPotionIds.put("instant_damage", mapPotionIds.get("harm")); mapPotionIds.put("water_breathing", mapPotionIds.get("waterbreathing")); } return mapPotionIds; } private static int[] getPotionIds(int baseId) { return new int[] {baseId, baseId + 16, baseId + 32, baseId + 48}; } private static int[] getPotionId(int baseId, int subId) { return new int[] {baseId + subId * 16}; } private static int getPotionNameDamage(String name) { String s = "effect." + name; for (ResourceLocation resourcelocation : Registry.EFFECTS.keySet()) { if (Registry.EFFECTS.containsKey(resourcelocation)) { Effect effect = Registry.EFFECTS.getOrDefault(resourcelocation); String s1 = effect.getName(); if (s.equals(s1)) { return Effect.getId(effect); } } } return -1; } private static List<List<CustomItemProperties>> makePropertyList(CustomItemProperties[][] propsArr) { List<List<CustomItemProperties>> list = new ArrayList<>(); if (propsArr != null) { for (int i = 0; i < propsArr.length; ++i) { CustomItemProperties[] acustomitemproperties = propsArr[i]; List<CustomItemProperties> list1 = null; if (acustomitemproperties != null) { list1 = new ArrayList<>(Arrays.asList(acustomitemproperties)); } list.add(list1); } } return list; } private static CustomItemProperties[][] propertyListToArray(List list) { CustomItemProperties[][] acustomitemproperties = new CustomItemProperties[list.size()][]; for (int i = 0; i < list.size(); ++i) { List lista = (List)list.get(i); if (lista != null) { CustomItemProperties[] acustomitemproperties1 = (CustomItemProperties[]) lista.toArray(new CustomItemProperties[lista.size()]); Arrays.sort(acustomitemproperties1, new CustomItemsComparator()); acustomitemproperties[i] = acustomitemproperties1; } } return acustomitemproperties; } private static void addToItemList(CustomItemProperties cp, List<List<CustomItemProperties>> itemList) { if (cp.items != null) { for (int i = 0; i < cp.items.length; ++i) { int j = cp.items[i]; if (j <= 0) { Config.warn("Invalid item ID: " + j); } else { addToList(cp, itemList, j); } } } } private static void addToEnchantmentList(CustomItemProperties cp, List<List<CustomItemProperties>> enchantmentList) { if (cp.type == 2) { if (cp.enchantmentIds != null) { int i = getMaxEnchantmentId() + 1; for (int j = 0; j < i; ++j) { if (Config.equalsOne(j, cp.enchantmentIds)) { addToList(cp, enchantmentList, j); } } } } } private static int getMaxEnchantmentId() { int i = 0; while (true) { Enchantment enchantment = Registry.ENCHANTMENT.getByValue(i); if (enchantment == null) { return i; } ++i; } } private static void addToList(CustomItemProperties cp, List<List<CustomItemProperties>> list, int id) { while (id >= list.size()) { list.add((List<CustomItemProperties>)null); } List<CustomItemProperties> lista = list.get(id); if (lista == null) { lista = new ArrayList<>(); list.set(id, lista); } lista.add(cp); } public static IBakedModel getCustomItemModel(ItemStack itemStack, IBakedModel model, ResourceLocation modelLocation, boolean fullModel) { if (!fullModel && model.isGui3d()) { return model; } else if (itemProperties == null) { return model; } else { CustomItemProperties customitemproperties = getCustomItemProperties(itemStack, 1); if (customitemproperties == null) { return model; } else { IBakedModel ibakedmodel = customitemproperties.getBakedModel(modelLocation, fullModel); return ibakedmodel != null ? ibakedmodel : model; } } } public static ResourceLocation getCustomArmorTexture(ItemStack itemStack, EquipmentSlotType slot, String overlay, ResourceLocation locArmor) { if (itemProperties == null) { return locArmor; } else { ResourceLocation resourcelocation = getCustomArmorLocation(itemStack, slot, overlay); return resourcelocation == null ? locArmor : resourcelocation; } } private static ResourceLocation getCustomArmorLocation(ItemStack itemStack, EquipmentSlotType slot, String overlay) { CustomItemProperties customitemproperties = getCustomItemProperties(itemStack, 3); if (customitemproperties == null) { return null; } else if (customitemproperties.mapTextureLocations == null) { return customitemproperties.textureLocation; } else { Item item = itemStack.getItem(); if (!(item instanceof ArmorItem)) { return null; } else { ArmorItem armoritem = (ArmorItem)item; String s = armoritem.getArmorMaterial().getName(); int i = slot == EquipmentSlotType.LEGS ? 2 : 1; StringBuffer stringbuffer = new StringBuffer(); stringbuffer.append("texture."); stringbuffer.append(s); stringbuffer.append("_layer_"); stringbuffer.append(i); if (overlay != null) { stringbuffer.append("_"); stringbuffer.append(overlay); } String s1 = stringbuffer.toString(); ResourceLocation resourcelocation = (ResourceLocation)customitemproperties.mapTextureLocations.get(s1); return resourcelocation == null ? customitemproperties.textureLocation : resourcelocation; } } } public static ResourceLocation getCustomElytraTexture(ItemStack itemStack, ResourceLocation locElytra) { if (itemProperties == null) { return locElytra; } else { CustomItemProperties customitemproperties = getCustomItemProperties(itemStack, 4); if (customitemproperties == null) { return locElytra; } else { return customitemproperties.textureLocation == null ? locElytra : customitemproperties.textureLocation; } } } private static CustomItemProperties getCustomItemProperties(ItemStack itemStack, int type) { if (itemProperties == null) { return null; } else if (itemStack == null) { return null; } else { Item item = itemStack.getItem(); int i = Item.getIdFromItem(item); if (i >= 0 && i < itemProperties.length) { CustomItemProperties[] acustomitemproperties = itemProperties[i]; if (acustomitemproperties != null) { for (int j = 0; j < acustomitemproperties.length; ++j) { CustomItemProperties customitemproperties = acustomitemproperties[j]; if (customitemproperties.type == type && matchesProperties(customitemproperties, itemStack, (int[][])null)) { return customitemproperties; } } } } return null; } } private static boolean matchesProperties(CustomItemProperties cip, ItemStack itemStack, int[][] enchantmentIdLevels) { Item item = itemStack.getItem(); if (cip.damage != null) { int i = getItemStackDamage(itemStack); if (i < 0) { return false; } if (cip.damageMask != 0) { i &= cip.damageMask; } if (cip.damagePercent) { int j = item.getMaxDamage(); i = (int)((double)(i * 100) / (double)j); } if (!cip.damage.isInRange(i)) { return false; } } if (cip.stackSize != null && !cip.stackSize.isInRange(itemStack.getCount())) { return false; } else { int[][] aint = enchantmentIdLevels; if (cip.enchantmentIds != null) { if (enchantmentIdLevels == null) { aint = getEnchantmentIdLevels(itemStack); } boolean flag = false; for (int k = 0; k < aint.length; ++k) { int l = aint[k][0]; if (Config.equalsOne(l, cip.enchantmentIds)) { flag = true; break; } } if (!flag) { return false; } } if (cip.enchantmentLevels != null) { if (aint == null) { aint = getEnchantmentIdLevels(itemStack); } boolean flag1 = false; for (int i1 = 0; i1 < aint.length; ++i1) { int k1 = aint[i1][1]; if (cip.enchantmentLevels.isInRange(k1)) { flag1 = true; break; } } if (!flag1) { return false; } } if (cip.nbtTagValues != null) { CompoundNBT compoundnbt = itemStack.getTag(); for (int j1 = 0; j1 < cip.nbtTagValues.length; ++j1) { NbtTagValue nbttagvalue = cip.nbtTagValues[j1]; if (!nbttagvalue.matches(compoundnbt)) { return false; } } } if (cip.hand != 0) { if (cip.hand == 1 && renderOffHand) { return false; } if (cip.hand == 2 && !renderOffHand) { return false; } } return true; } } private static int getItemStackDamage(ItemStack itemStack) { Item item = itemStack.getItem(); return item instanceof PotionItem ? getPotionDamage(itemStack) : itemStack.getDamage(); } private static int getPotionDamage(ItemStack itemStack) { CompoundNBT compoundnbt = itemStack.getTag(); if (compoundnbt == null) { return 0; } else { String s = compoundnbt.getString("Potion"); if (s != null && !s.equals("")) { Integer integer = mapPotionDamages.get(s); if (integer == null) { return -1; } else { int i = integer; if (itemStack.getItem() == Items.SPLASH_POTION) { i |= 16384; } return i; } } else { return 0; } } } private static Map<String, Integer> makeMapPotionDamages() { Map<String, Integer> map = new HashMap<>(); addPotion("water", 0, false, map); addPotion("awkward", 16, false, map); addPotion("thick", 32, false, map); addPotion("mundane", 64, false, map); addPotion("regeneration", 1, true, map); addPotion("swiftness", 2, true, map); addPotion("fire_resistance", 3, true, map); addPotion("poison", 4, true, map); addPotion("healing", 5, true, map); addPotion("night_vision", 6, true, map); addPotion("weakness", 8, true, map); addPotion("strength", 9, true, map); addPotion("slowness", 10, true, map); addPotion("leaping", 11, true, map); addPotion("harming", 12, true, map); addPotion("water_breathing", 13, true, map); addPotion("invisibility", 14, true, map); return map; } private static void addPotion(String name, int value, boolean extended, Map<String, Integer> map) { if (extended) { value |= 8192; } map.put("minecraft:" + name, value); if (extended) { int i = value | 32; map.put("minecraft:strong_" + name, i); int j = value | 64; map.put("minecraft:long_" + name, j); } } private static int[][] getEnchantmentIdLevels(ItemStack itemStack) { Item item = itemStack.getItem(); ListNBT listnbt1; if (item == Items.ENCHANTED_BOOK) { EnchantedBookItem enchantedbookitem = (EnchantedBookItem)Items.ENCHANTED_BOOK; listnbt1 = EnchantedBookItem.getEnchantments(itemStack); } else { listnbt1 = itemStack.getEnchantmentTagList(); } ListNBT listnbt = listnbt1; if (listnbt != null && listnbt.size() > 0) { int[][] aint = new int[listnbt.size()][2]; for (int i = 0; i < listnbt.size(); ++i) { CompoundNBT compoundnbt = listnbt.getCompound(i); String s = compoundnbt.getString("id"); int j = compoundnbt.getInt("lvl"); Enchantment enchantment = EnchantmentUtils.getEnchantment(s); if (enchantment != null) { int k = Registry.ENCHANTMENT.getId(enchantment); aint[i][0] = k; aint[i][1] = j; } } return aint; } else { return EMPTY_INT2_ARRAY; } } public static boolean renderCustomEffect(ItemRenderer renderItem, ItemStack itemStack, IBakedModel model) { if (enchantmentProperties == null) { return false; } else if (itemStack == null) { return false; } else { int[][] aint = getEnchantmentIdLevels(itemStack); if (aint.length <= 0) { return false; } else { Set set = null; boolean flag = false; TextureManager texturemanager = Config.getTextureManager(); for (int i = 0; i < aint.length; ++i) { int j = aint[i][0]; if (j >= 0 && j < enchantmentProperties.length) { CustomItemProperties[] acustomitemproperties = enchantmentProperties[j]; if (acustomitemproperties != null) { for (int k = 0; k < acustomitemproperties.length; ++k) { CustomItemProperties customitemproperties = acustomitemproperties[k]; if (set == null) { set = new HashSet(); } if (set.add(j) && matchesProperties(customitemproperties, itemStack, aint) && customitemproperties.textureLocation != null) { texturemanager.bindTexture(customitemproperties.textureLocation); float f = customitemproperties.getTextureWidth(texturemanager); if (!flag) { flag = true; GlStateManager.depthMask(false); GlStateManager.depthFunc(514); GlStateManager.disableLighting(); GlStateManager.matrixMode(5890); } Blender.setupBlend(customitemproperties.blend, 1.0F); GlStateManager.pushMatrix(); GlStateManager.scalef(f, f, f); float f1 = customitemproperties.speed * (float)(Util.milliTime() % 3000L) / 3000.0F / 8.0F; GlStateManager.translatef(f1, 0.0F, 0.0F); GlStateManager.rotatef(customitemproperties.rotation, 0.0F, 0.0F, 1.0F); GlStateManager.popMatrix(); } } } } } if (flag) { GlStateManager.enableAlphaTest(); GlStateManager.enableBlend(); GlStateManager.blendFunc(770, 771); GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.matrixMode(5888); GlStateManager.enableLighting(); GlStateManager.depthFunc(515); GlStateManager.depthMask(true); texturemanager.bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE); } return flag; } } } public static boolean renderCustomArmorEffect(LivingEntity entity, ItemStack itemStack, EntityModel model, float limbSwing, float prevLimbSwing, float partialTicks, float timeLimbSwing, float yaw, float pitch, float scale) { if (enchantmentProperties == null) { return false; } else if (Config.isShaders() && Shaders.isShadowPass) { return false; } else if (itemStack == null) { return false; } else { int[][] aint = getEnchantmentIdLevels(itemStack); if (aint.length <= 0) { return false; } else { Set set = null; boolean flag = false; TextureManager texturemanager = Config.getTextureManager(); for (int i = 0; i < aint.length; ++i) { int j = aint[i][0]; if (j >= 0 && j < enchantmentProperties.length) { CustomItemProperties[] acustomitemproperties = enchantmentProperties[j]; if (acustomitemproperties != null) { for (int k = 0; k < acustomitemproperties.length; ++k) { CustomItemProperties customitemproperties = acustomitemproperties[k]; if (set == null) { set = new HashSet(); } if (set.add(j) && matchesProperties(customitemproperties, itemStack, aint) && customitemproperties.textureLocation != null) { texturemanager.bindTexture(customitemproperties.textureLocation); float f = customitemproperties.getTextureWidth(texturemanager); if (!flag) { flag = true; if (Config.isShaders()) { ShadersRender.renderEnchantedGlintBegin(); } GlStateManager.enableBlend(); GlStateManager.depthFunc(514); GlStateManager.depthMask(false); } Blender.setupBlend(customitemproperties.blend, 1.0F); GlStateManager.disableLighting(); GlStateManager.matrixMode(5890); GlStateManager.loadIdentity(); GlStateManager.rotatef(customitemproperties.rotation, 0.0F, 0.0F, 1.0F); float f1 = f / 8.0F; GlStateManager.scalef(f1, f1 / 2.0F, f1); float f2 = customitemproperties.speed * (float)(Util.milliTime() % 3000L) / 3000.0F / 8.0F; GlStateManager.translatef(0.0F, f2, 0.0F); GlStateManager.matrixMode(5888); } } } } } if (flag) { GlStateManager.enableAlphaTest(); GlStateManager.enableBlend(); GlStateManager.blendFunc(770, 771); GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.matrixMode(5890); GlStateManager.loadIdentity(); GlStateManager.matrixMode(5888); GlStateManager.enableLighting(); GlStateManager.depthMask(true); GlStateManager.depthFunc(515); GlStateManager.disableBlend(); if (Config.isShaders()) { ShadersRender.renderEnchantedGlintEnd(); } } return flag; } } } public static boolean isUseGlint() { return useGlint; } public static void setRenderOffHand(boolean renderOffHand) { CustomItems.renderOffHand = renderOffHand; } }
0
0.966564
1
0.966564
game-dev
MEDIA
0.949269
game-dev
0.972386
1
0.972386
BobLChen/VulkanDemos
5,291
external/vulkan/linux/include/glslang/MachineIndependent/Initialize.h
// // Copyright (C) 2002-2005 3Dlabs Inc. Ltd. // Copyright (C) 2013-2016 LunarG, Inc. // // 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 3Dlabs Inc. Ltd. 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 HOLDERS 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. // #ifndef _INITIALIZE_INCLUDED_ #define _INITIALIZE_INCLUDED_ #include "../Include/ResourceLimits.h" #include "../Include/Common.h" #include "../Include/ShHandle.h" #include "SymbolTable.h" #include "Versions.h" namespace glslang { // // This is made to hold parseable strings for almost all the built-in // functions and variables for one specific combination of version // and profile. (Some still need to be added programmatically.) // This is a base class for language-specific derivations, which // can be used for language independent builtins. // // The strings are organized by // commonBuiltins: intersection of all stages' built-ins, processed just once // stageBuiltins[]: anything a stage needs that's not in commonBuiltins // class TBuiltInParseables { public: POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator()) TBuiltInParseables(); virtual ~TBuiltInParseables(); virtual void initialize(int version, EProfile, const SpvVersion& spvVersion) = 0; virtual void initialize(const TBuiltInResource& resources, int version, EProfile, const SpvVersion& spvVersion, EShLanguage) = 0; virtual const TString& getCommonString() const { return commonBuiltins; } virtual const TString& getStageString(EShLanguage language) const { return stageBuiltins[language]; } virtual void identifyBuiltIns(int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TSymbolTable& symbolTable) = 0; virtual void identifyBuiltIns(int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TSymbolTable& symbolTable, const TBuiltInResource &resources) = 0; protected: TString commonBuiltins; TString stageBuiltins[EShLangCount]; }; // // This is a GLSL specific derivation of TBuiltInParseables. To present a stable // interface and match other similar code, it is called TBuiltIns, rather // than TBuiltInParseablesGlsl. // class TBuiltIns : public TBuiltInParseables { public: POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator()) TBuiltIns(); virtual ~TBuiltIns(); void initialize(int version, EProfile, const SpvVersion& spvVersion); void initialize(const TBuiltInResource& resources, int version, EProfile, const SpvVersion& spvVersion, EShLanguage); void identifyBuiltIns(int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TSymbolTable& symbolTable); void identifyBuiltIns(int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TSymbolTable& symbolTable, const TBuiltInResource &resources); protected: void addTabledBuiltins(int version, EProfile profile, const SpvVersion& spvVersion); void relateTabledBuiltins(int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage, TSymbolTable&); void add2ndGenerationSamplingImaging(int version, EProfile profile, const SpvVersion& spvVersion); void addSubpassSampling(TSampler, const TString& typeName, int version, EProfile profile); void addQueryFunctions(TSampler, const TString& typeName, int version, EProfile profile); void addImageFunctions(TSampler, const TString& typeName, int version, EProfile profile); void addSamplingFunctions(TSampler, const TString& typeName, int version, EProfile profile); void addGatherFunctions(TSampler, const TString& typeName, int version, EProfile profile); // Helpers for making textual representations of the permutations // of texturing/imaging functions. const char* postfixes[5]; const char* prefixes[EbtNumTypes]; int dimMap[EsdNumDims]; }; } // end namespace glslang #endif // _INITIALIZE_INCLUDED_
0
0.816647
1
0.816647
game-dev
MEDIA
0.415906
game-dev,graphics-rendering
0.812822
1
0.812822
magefree/mage
2,166
Mage.Sets/src/mage/cards/s/SevenDwarves.java
package mage.cards.s; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.effects.common.InfoEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.mageobject.NamePredicate; import mage.filter.predicate.mageobject.AnotherPredicate; import java.util.UUID; /** * @author TheElk801 */ public final class SevenDwarves extends CardImpl { private static final FilterPermanent filter = new FilterControlledCreaturePermanent(); static { filter.add(AnotherPredicate.instance); filter.add(new NamePredicate("Seven Dwarves")); } private static final DynamicValue xValue = new PermanentsOnBattlefieldCount(filter); public SevenDwarves(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}"); this.subtype.add(SubType.DWARF); this.power = new MageInt(2); this.toughness = new MageInt(2); // Seven Dwarves gets +1/+1 for each other creature named Seven Dwarves you control. this.addAbility(new SimpleStaticAbility( new BoostSourceEffect(xValue, xValue, Duration.WhileOnBattlefield).setText( "{this} gets +1/+1 for each other creature named Seven Dwarves you control" ) )); // A deck can have up to seven cards named Seven Dwarves. this.addAbility(new SimpleStaticAbility( Zone.ALL, new InfoEffect("A deck can have up to seven cards named Seven Dwarves.") )); } private SevenDwarves(final SevenDwarves card) { super(card); } @Override public SevenDwarves copy() { return new SevenDwarves(this); } }
0
0.946074
1
0.946074
game-dev
MEDIA
0.97315
game-dev
0.989472
1
0.989472
Orckestra/C1-CMS-Foundation
2,942
Composite/Core/Serialization/SystemPrimitivValueXmlSerializer.cs
using System; using System.Xml.Linq; using Composite.Core.Types; namespace Composite.Core.Serialization { internal sealed class SystemPrimitivValueXmlSerializer : IValueXmlSerializer { public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject) { if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType"); if ((objectToSerializeType != typeof(int)) && (objectToSerializeType != typeof(long)) && (objectToSerializeType != typeof(bool)) && (objectToSerializeType != typeof(string)) && (objectToSerializeType != typeof(double)) && (objectToSerializeType != typeof(decimal)) && (objectToSerializeType != typeof(Guid)) && (objectToSerializeType != typeof(DateTime))) { serializedObject = null; return false; } serializedObject = new XElement("Value"); string serializedType = TypeManager.SerializeType(objectToSerializeType); serializedObject.Add(new XAttribute("type", serializedType)); if (objectToSerialize != null) { serializedObject.Add(new XAttribute("value", objectToSerialize)); } return true; } public bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject) { if (serializedObject == null) throw new ArgumentNullException("serializedObject"); deserializedObject = null; if (serializedObject.Name.LocalName != "Value") return false; XAttribute typeAttribute = serializedObject.Attribute("type"); if (typeAttribute == null) return false; XAttribute valueAttribute = serializedObject.Attribute("value"); if (valueAttribute == null) return true; Type type = TypeManager.GetType(typeAttribute.Value); if (type == typeof(int)) deserializedObject = (int)valueAttribute; else if (type == typeof(long)) deserializedObject = (long)valueAttribute; else if (type == typeof(bool)) deserializedObject = (bool)valueAttribute; else if (type == typeof(string)) deserializedObject = (string)valueAttribute; else if (type == typeof(double)) deserializedObject = (double)valueAttribute; else if (type == typeof(decimal)) deserializedObject = (decimal)valueAttribute; else if (type == typeof(Guid)) deserializedObject = (Guid)valueAttribute; else if (type == typeof(DateTime)) deserializedObject = (DateTime)valueAttribute; else { return false; } return true; } } }
0
0.768057
1
0.768057
game-dev
MEDIA
0.252278
game-dev
0.811393
1
0.811393
josh-m/RW-Decompile
5,169
RimWorld/TrainingCardUtility.cs
using System; using System.Collections.Generic; using UnityEngine; using Verse; namespace RimWorld { [StaticConstructorOnStartup] public static class TrainingCardUtility { public const float RowHeight = 28f; private const float InfoHeaderHeight = 50f; [TweakValue("Interface", -100f, 300f)] private static float TrainabilityLeft = 220f; [TweakValue("Interface", -100f, 300f)] private static float TrainabilityTop = 0f; private static readonly Texture2D LearnedTrainingTex = ContentFinder<Texture2D>.Get("UI/Icons/FixedCheck", true); private static readonly Texture2D LearnedNotTrainingTex = ContentFinder<Texture2D>.Get("UI/Icons/FixedCheckOff", true); public static void DrawTrainingCard(Rect rect, Pawn pawn) { Text.Font = GameFont.Small; Rect rect2 = new Rect(TrainingCardUtility.TrainabilityLeft, TrainingCardUtility.TrainabilityTop, 30f, 30f); TooltipHandler.TipRegion(rect2, "RenameAnimal".Translate()); if (Widgets.ButtonImage(rect2, TexButton.Rename)) { Find.WindowStack.Add(new Dialog_NamePawn(pawn)); } Listing_Standard listing_Standard = new Listing_Standard(); listing_Standard.Begin(rect); listing_Standard.Label("CreatureTrainability".Translate(pawn.def.label).CapitalizeFirst() + ": " + pawn.RaceProps.trainability.LabelCap, 22f, null); Listing_Standard arg_F6_0 = listing_Standard; string label = "CreatureWildness".Translate(pawn.def.label).CapitalizeFirst() + ": " + pawn.RaceProps.wildness.ToStringPercent(); string wildnessExplanation = TrainableUtility.GetWildnessExplanation(pawn.def); arg_F6_0.Label(label, 22f, wildnessExplanation); if (pawn.training.HasLearned(TrainableDefOf.Obedience)) { Rect rect3 = listing_Standard.GetRect(25f); Widgets.Label(rect3, "Master".Translate() + ": "); rect3.xMin = rect3.center.x; TrainableUtility.MasterSelectButton(rect3, pawn, false); } listing_Standard.Gap(12f); float num = 50f; List<TrainableDef> trainableDefsInListOrder = TrainableUtility.TrainableDefsInListOrder; for (int i = 0; i < trainableDefsInListOrder.Count; i++) { if (TrainingCardUtility.TryDrawTrainableRow(listing_Standard.GetRect(28f), pawn, trainableDefsInListOrder[i])) { num += 28f; } } listing_Standard.End(); } private static bool TryDrawTrainableRow(Rect rect, Pawn pawn, TrainableDef td) { bool flag = pawn.training.HasLearned(td); bool flag2; AcceptanceReport canTrain = pawn.training.CanAssignToTrain(td, out flag2); if (!flag2) { return false; } Widgets.DrawHighlightIfMouseover(rect); Rect rect2 = rect; rect2.width -= 50f; rect2.xMin += (float)td.indent * 10f; Rect rect3 = rect; rect3.xMin = rect3.xMax - 50f + 17f; TrainingCardUtility.DoTrainableCheckbox(rect2, pawn, td, canTrain, true, false); if (flag) { GUI.color = Color.green; } Text.Anchor = TextAnchor.MiddleLeft; Widgets.Label(rect3, pawn.training.GetSteps(td) + " / " + td.steps); Text.Anchor = TextAnchor.UpperLeft; if (DebugSettings.godMode && !pawn.training.HasLearned(td)) { Rect rect4 = rect3; rect4.yMin = rect4.yMax - 10f; rect4.xMin = rect4.xMax - 10f; if (Widgets.ButtonText(rect4, "+", true, false, true)) { pawn.training.Train(td, pawn.Map.mapPawns.FreeColonistsSpawned.RandomElement<Pawn>(), false); } } TrainingCardUtility.DoTrainableTooltip(rect, pawn, td, canTrain); GUI.color = Color.white; return true; } public static void DoTrainableCheckbox(Rect rect, Pawn pawn, TrainableDef td, AcceptanceReport canTrain, bool drawLabel, bool doTooltip) { bool flag = pawn.training.HasLearned(td); bool wanted = pawn.training.GetWanted(td); bool flag2 = wanted; Texture2D texChecked = (!flag) ? null : TrainingCardUtility.LearnedTrainingTex; Texture2D texUnchecked = (!flag) ? null : TrainingCardUtility.LearnedNotTrainingTex; if (drawLabel) { Widgets.CheckboxLabeled(rect, td.LabelCap, ref wanted, !canTrain.Accepted, texChecked, texUnchecked, false); } else { Widgets.Checkbox(rect.position, ref wanted, rect.width, !canTrain.Accepted, true, texChecked, texUnchecked); } if (wanted != flag2) { PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.AnimalTraining, KnowledgeAmount.Total); pawn.training.SetWantedRecursive(td, wanted); } if (doTooltip) { TrainingCardUtility.DoTrainableTooltip(rect, pawn, td, canTrain); } } private static void DoTrainableTooltip(Rect rect, Pawn pawn, TrainableDef td, AcceptanceReport canTrain) { TooltipHandler.TipRegion(rect, delegate { string text = td.LabelCap + "\n\n" + td.description; if (!canTrain.Accepted) { text = text + "\n\n" + canTrain.Reason; } else if (!td.prerequisites.NullOrEmpty<TrainableDef>()) { text += "\n"; for (int i = 0; i < td.prerequisites.Count; i++) { if (!pawn.training.HasLearned(td.prerequisites[i])) { text = text + "\n" + "TrainingNeedsPrerequisite".Translate(td.prerequisites[i].LabelCap); } } } return text; }, (int)(rect.y * 612f + rect.x)); } } }
0
0.933908
1
0.933908
game-dev
MEDIA
0.974255
game-dev
0.854815
1
0.854815
holycake/mhsj
8,380
feature/smith.c
// smith.c #include <ansi.h> inherit NPC; inherit F_VENDOR; string ask_me(); int do_gu(string arg); int do_dapi(string arg); int do_cuihuo(string arg); int do_repair(string arg); void reward(object me); // no create_function: inherit by other NPC void init() { add_action("do_vendor_list", "list"); add_action("do_buy", "buy"); add_action("do_gu", "gu"); add_action("do_dapi", "dapi"); add_action("do_cuihuo", "cuihuo"); add_action("do_repair", "repair"); add_action("do_repair", "xiuli"); } void setup() { set("inquiry/job", (: ask_me :)); set("inquiry/修理", "你想要修(repair)点什么?"); ::setup(); } string ask_me() { object me = this_player(); /* if (me->query("level") > 10) return "让您老干这个未免屈尊了吧?";*/ if (me->query("qi") < 40) return "你还是歇会儿吧!要是出了人命我可承担不起。"; if (me->query_temp("smith/gu")) return "让你鼓风箱,你怎么还磨蹭(gu)?"; if (me->query_temp("smith/dapi")) return "叫你打的坯你打了没有(dapi)?"; if (me->query_temp("smith/cuihuo")) return "干活怎么尽偷懒?快给我淬火去(cuihuo)!"; switch(random(3)) { case 0: me->set_temp("smith/gu", 1); return "好!你帮我鼓一会儿风箱(gu)。"; case 1: me->set_temp("smith/dapi", 1); return "这样吧,你帮我打一下坯吧(dapi)!"; case 2: me->set_temp("smith/cuihuo", 1); return "去帮我把这些刚出炉的淬一下火(cuihuo)。"; } } int do_gu(string arg) { object me = this_player(); int skill_exp; if (me->is_busy()) return notify_fail("你现在正忙。\n"); if (! me->query_temp("smith/gu")) { message_vision("$n刚偷偷的拉起鼓风机,鼓了几阵风。" "就听见$N对$n大喝道:滚开,乱搞什么。\n", this_object(), me); return 1; } message_vision("$n拉起鼓风机拼命鼓了起来,$N看了点了点头。\n",this_object(), me); skill_exp=random((int)me->query("level")*100); me->improve_skill("force",skill_exp); write(HIR+"> 【系统提示】:"NOR+HIG"你在<鼓风>中对<运气>有所领悟,[基本内功] 熟练度提升 +"+skill_exp+"\n"NOR); call_out("reward",3,me); return 1; } int do_dapi(string arg) { object me = this_player(); int skill_exp; if (me->is_busy()) return notify_fail("你现在正忙。\n"); if (! me->query_temp("smith/dapi")) { message_vision("$n拿起几块生铁,在手里掂了掂。" "就听见$N对$n大喝道:放下,乱搞什么。\n", this_object(), me); return 1; } message_vision("$n拿着锤子对刚出炉的火热的生铁用力敲打着," "$N“嗯”了一声,看上去有些满意。\n", this_object(), me); skill_exp=random((int)me->query("level")*100); me->improve_skill("unarmed",skill_exp); write(HIR+"> 【系统提示】:"NOR+HIG"你在<打坯>中对<拳脚运用>所领悟,[基本拳脚] 熟练度提升 +"+skill_exp+"\n"NOR); call_out("reward",3,me); return 1; } int do_cuihuo(string arg) { object me = this_player(); int skill_exp; if (me->is_busy()) return notify_fail("你现在正忙。\n"); if (! me->query_temp("smith/cuihuo")) { message_vision("$n刚抄起一个打造好的坯子," "就听见$N对$n大喝道:放下,别给我搞坏了。\n", this_object(), me); return 1; } message_vision("$N用铁钳抄起一块火红的坯子,伸进了水" "池,“哧”的一声轻烟四冒。\n", me); skill_exp=random((int)me->query("level")*100); me->improve_skill("dodge",skill_exp); write(HIR+"> 【系统提示】:"NOR+HIG"你在<淬火>中对<腾转挪移>所领悟,[基本轻功] 熟练度提升 +"+skill_exp+"\n"NOR); call_out("reward",3,me); return 1; } void reward(object me) { object coin; int exp_add, pot_add; me->delete_temp("smith/gu"); me->delete_temp("smith/dapi"); me->delete_temp("smith/cuihuo"); coin = new("/obj/money/coin"); coin->set_amount(15 + random(35)); coin->move(this_object()); me->add("score",1); message_vision("$N对$n道:这是给你的工钱。\n你的江湖阅历增加了。\n",this_object(), me); command("give coin to " + me->query("id")); exp_add = random(100); pot_add = random(20); write(HIG"你辛苦工作获得: 经验:+"+exp_add+" 潜能:+"+pot_add+""NOR); me->add("combat_exp",exp_add); me->add("potential", pot_add); me->receive_damage("qi", 2 + random(10)); me->start_busy(3); } int do_repair(string arg) { object me; object ob; mixed msg; int consistence; int cost; mapping repair; if (! arg) return 0; me = this_player(); if (! objectp(ob = present(arg, me))) return notify_fail("你身上好像没有这样东西。\n"); if (undefinedp(consistence = ob->query("consistence"))) return notify_fail(ob->name() + "似乎不需要在这里修理吧?\n"); if (consistence >= 100) return notify_fail(ob->name() + "现在完好无损,修理做什么?\n"); if (! undefinedp(msg = ob->query("no_repair"))) { if (stringp(msg)) write(name() + "道:这我可修理不了。\n"); else write(name() + "道:" + msg); return 1; } if (mapp(repair = me->query_temp("pending/repair")) && repair["item"] == ob) { if (me->is_busy()) return notify_fail("你现在正忙着呢!\n"); notify_fail("你先带够了钱再说。\n"); if (MONEY_D->player_pay(me, repair["cost"]) != 1) return 0; message_vision("$n把" + ob->name() + "递给了$N。只见$N" "拿起工具,东敲西补,将" + ob->name() + "好好修了修。\n", this_object(), me); ob->set("consistence", 100); message_vision("$N道:“好了!”随手把" + ob->name() + "还给了$n,$n看了看,满意的掏出了一些钱" "付了帐。\n", this_object(), me); me->start_busy(1 + random(100 - consistence) / 10); me->delete_temp("pending/repair"); return 1; } cost = (120 - consistence) * ob->query("value") / 480; if (cost >= 100000) cost = ((cost - 100000) / 2 + 100000) / 10000 * 10000; else if (cost >= 10000) cost = cost / 1000 * 1000; else if (cost >= 1000) cost = cost / 100 * 100; else if (cost >= 100) cost = cost / 10 * 10; msg = "$n拿出一" + ob->query("unit") + ob->name() + ",$N瞥了一眼,道:“要修好它得要" + MONEY_D->price_str(cost) + "才行。”\n"; if (me->query("family/family_name") == "段氏皇族" && ob->item_owner() == me->query("id")) { cost /= 2; msg += "$n道:“呦,是您啊,不好意思,打个五折,就" + MONEY_D->price_str(cost) + "吧!”\n"; } else if (me->query_skill("higgling", 1) >= 30 && cost >= 50) { cost = cost * 500 / (me->query_skill("higgling", 1) + 500); switch (random(5)) { case 0: msg += "$n道:“大哥,看在我常年照顾你生意份上,还不给点折扣?”\n"; break; case 1: msg += "$n道:“你们大老板可是我的熟人啊,这个,这个...”\n"; break; case 2: msg += "$n道:“这位大哥好,您最近生意这么好... 给点折扣如何?”\n"; break; case 3: msg += "$n道:“太贵了,我实在没这么多了,便宜点,便宜点就好。”\n"; break; case 4: msg += "$n道:“我急修,这样吧,下次我一定给足,这次您就行个好,便宜点吧。”\n"; break; } if (cost >= 1000) cost = cost / 100 * 100; else cost = cost / 10 * 10; msg += "$N耸耸肩道:“算了,算了,那就" + MONEY_D->price_str(cost) + "好了。”\n"; } message_vision(msg, this_object(), me); tell_object(me, YEL "如果你的确想修理这件物品,请再输入一次这条命令。\n" NOR); me->set_temp("pending/repair/item", ob); me->set_temp("pending/repair/cost", cost); return 1; }
0
0.778747
1
0.778747
game-dev
MEDIA
0.908422
game-dev
0.68468
1
0.68468
modernuo/ModernUO
2,180
Projects/UOContent/Engines/Veteran Rewards/RewardDemolitionGump.cs
using Server.Items; using Server.Multis; using Server.Network; namespace Server.Gumps { public class RewardDemolitionGump : Gump { private readonly IAddon m_Addon; public override bool Singleton => true; public RewardDemolitionGump(IAddon addon, int question) : base(150, 50) { m_Addon = addon; Closable = true; Disposable = true; Draggable = true; Resizable = false; AddBackground(0, 0, 220, 170, 0x13BE); AddBackground(10, 10, 200, 150, 0xBB8); AddHtmlLocalized(20, 30, 180, 60, question); // Do you wish to re-deed this decoration? AddHtmlLocalized(55, 100, 150, 25, 1011011); // CONTINUE AddButton(20, 100, 0xFA5, 0xFA7, (int)Buttons.Confirm); AddHtmlLocalized(55, 125, 150, 25, 1011012); // CANCEL AddButton(20, 125, 0xFA5, 0xFA7, (int)Buttons.Cancel); } public override void OnResponse(NetState sender, in RelayInfo info) { if (m_Addon is not Item item || item.Deleted) { return; } if (info.ButtonID != (int)Buttons.Confirm) { return; } var m = sender.Mobile; var house = BaseHouse.FindHouseAt(m); if (house?.IsOwner(m) != true) { // You can only re-deed this decoration if you are the house owner or originally placed the decoration. m.SendLocalizedMessage(1049784); return; } if (m.InRange(item.Location, 2)) { var deed = m_Addon.Deed; if (deed != null) { m.AddToBackpack(deed); house.Addons.Remove(item); item.Delete(); } } else { m.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019045); // I can't reach that. } } private enum Buttons { Cancel, Confirm } } }
0
0.76348
1
0.76348
game-dev
MEDIA
0.947748
game-dev
0.795721
1
0.795721
czyzby/gdx-lml
2,271
lml/src/main/java/com/github/czyzby/lml/parser/impl/attribute/progress/OnCompleteLmlAtrribute.java
package com.github.czyzby.lml.parser.impl.attribute.progress; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.github.czyzby.lml.parser.LmlParser; import com.github.czyzby.lml.parser.action.ActorConsumer; import com.github.czyzby.lml.parser.tag.LmlAttribute; import com.github.czyzby.lml.parser.tag.LmlTag; /** Adds a change listener that invokes an action when progress bar value changes and reaches its maximum value. Expects * an action ID. Mapped to "onComplete", "complete". Note that it might be invoked multiple times if change events of * reaching max value are posted more than once. If the referenced action returns true (boolean), listener will be * removed. See {@link #REMOVE_LISTENER}. * * @author MJ */ public class OnCompleteLmlAtrribute implements LmlAttribute<ProgressBar> { /** If returned by the action referenced in the attribute, attached listener will be removed. Utility reference for * code clarity. This matches boolean true value; if false or null is returned, listener is kept. */ public static final Boolean REMOVE_LISTENER = Boolean.TRUE; @Override public Class<ProgressBar> getHandledType() { return ProgressBar.class; } @Override public void process(final LmlParser parser, final LmlTag tag, final ProgressBar actor, final String rawAttributeData) { final ActorConsumer<?, ProgressBar> action = parser.parseAction(rawAttributeData, actor); if (action == null) { parser.throwErrorIfStrict( "Unable to attach listener for " + actor + " with invalid action ID: " + rawAttributeData); return; } actor.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor widget) { if (actor.getValue() >= actor.getMaxValue()) { final Object result = action.consume(actor); if (result instanceof Boolean && ((Boolean) result).booleanValue()) { actor.removeListener(this); } } } }); } }
0
0.844996
1
0.844996
game-dev
MEDIA
0.316754
game-dev
0.929729
1
0.929729
Grimrukh/SoulsAI
8,977
ai_scripts/m15_01_00_00/256002_battle.lua
REGISTER_GOAL(GOAL_LightKnight_Rapier256002_Battle, "LightKnight_Rapier256002Battle") local Att3000_Dist_min = 0 local Att3000_Dist_max = 2.1 local Att3003_Dist_min = 3.5 local Att3003_Dist_max = 5.5 local Att3004_Dist_min = 1.5 local Att3004_Dist_max = 2.4 local Att3005_Dist_min = 0 local Att3005_Dist_max = 1.3 REGISTER_GOAL_NO_UPDATE(GOAL_LightKnight_Rapier256002_Battle, 1) function OnIf_256002(ai, goal, codeNo) if ai:HasSpecialEffectId(TARGET_SELF, 3151) then ai:SetTimer(0, 120) else ai:SetTimer(0, 30) end return end Att3000_Dist_min = Att3004_Dist_max Att3000_Dist_min = Att3000_Dist_max Att3000_Dist_min = Att3005_Dist_max Att3000_Dist_min = Att3003_Dist_max function LightKnight_Rapier256002Battle_Activate(ai, goal) local ObserveNo = 0 local BackstabDist = 5 local BackstabAng = 30 ObserveAreaForBackstab(ai, goal, ObserveNo, BackstabDist, BackstabAng) local actPerArr = {} local actFuncArr = {} local defFuncParamTbl = {} Common_Clear_Param(actPerArr, actFuncArr, defFuncParamTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local hprate = ai:GetHpRate(TARGET_SELF) if ai:IsLadderAct(TARGET_SELF) then actPerArr[2] = 100 elseif hprate <= 0.4 and ai:IsFinishTimer(0) == true then if 4.5 <= targetDist then actPerArr[1] = 0 actPerArr[2] = 15 actPerArr[3] = 10 actPerArr[4] = 75 actPerArr[7] = 0 actPerArr[8] = 0 elseif 3 <= targetDist then actPerArr[1] = 7 actPerArr[2] = 20 actPerArr[3] = 8 actPerArr[4] = 50 actPerArr[7] = 15 actPerArr[8] = 0 else actPerArr[1] = 0 actPerArr[2] = 35 actPerArr[3] = 20 actPerArr[4] = 35 actPerArr[7] = 0 actPerArr[8] = 10 end elseif 8 <= targetDist then actPerArr[1] = 0 actPerArr[2] = 15 actPerArr[3] = 15 actPerArr[7] = 70 actPerArr[8] = 0 elseif 3.5 <= targetDist then actPerArr[1] = 15 actPerArr[2] = 40 actPerArr[3] = 15 actPerArr[7] = 30 actPerArr[8] = 0 elseif 1.5 <= targetDist then actPerArr[1] = 35 actPerArr[2] = 35 actPerArr[3] = 15 actPerArr[7] = 0 actPerArr[8] = 25 else actPerArr[1] = 0 actPerArr[2] = 65 actPerArr[3] = 20 actPerArr[7] = 0 actPerArr[8] = 15 end local local0 = {Att3004_Dist_max, 75, 3004, DIST_Middle, nil} defFuncParamTbl[1] = local0 local0 = {} local local1, local2, local3, local4 = nil local0[1] = Att3000_Dist_max local0[2] = 75 local0[3] = 10 local0[4] = 30 local0[5] = local1 local0[6] = local2 local0[7] = local3 local0[8] = local4 defFuncParamTbl[2] = local0 local0 = {Att3005_Dist_max, 100, 3005, DIST_Middle, nil} defFuncParamTbl[3] = local0 actFuncArr[4] = REGIST_FUNC(ai, goal, LightKnight_Rapier256002_Act04) local0 = {Att3003_Dist_max, 75, 3003, DIST_Middle, nil} defFuncParamTbl[7] = local0 local0 = {nil} defFuncParamTbl[8] = local0 local0 = {100, 60, 5, 5, 0, 15, 15} local atkAfterFunc = REGIST_FUNC(ai, goal, HumanCommon_ActAfter_AdjustSpace_IncludeSidestep, local0) Common_Battle_Activate(ai, goal, actPerArr, actFuncArr, atkAfterFunc, defFuncParamTbl) return end function LightKnight_Rapier256002_Act04(ai, goal, paramTbl) local fate = ai:GetRandam_Int(1, 100) if fate <= 40 then goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 5, TARGET_ENE_0, 4.5, TARGET_ENE_0, true, 9910) goal:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3200, TARGET_ENE_0, DIST_None) else goal:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 2.5) goal:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3200, TARGET_ENE_0, DIST_None) end goal:AddSubGoal(GOAL_COMMON_If, 15, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function LightKnight_Rapier256002Battle_Update(ai, goal) return GOAL_RESULT_Continue end function LightKnight_Rapier256002Battle_Terminate(ai, goal) return end Att3000_Dist_min = Att3000_Dist_max Att3000_Dist_min = Att3003_Dist_max function LightKnight_Rapier256002Battle_Interupt(ai, goal) if ai:IsLadderAct(TARGET_SELF) then return false end local fate = ai:GetRandam_Int(1, 100) local fate2 = ai:GetRandam_Int(1, 100) local fate3 = ai:GetRandam_Int(1, 100) local targetDist = ai:GetDist(TARGET_ENE_0) local distResponse = 3 local oddsResponse = 25 local oddsStep = 20 local bkStepPer = 60 local leftStepPer = 20 local rightStepPer = 20 local safetyDist = 2.8 local oddsLeaveAndSide = 50 local timeSide = 3.5 local distLeave = 2.5 if FindAttack_Step_or_Guard(ai, goal, distResponse, oddsResponse, oddsStep, bkStepPer, leftStepPer, rightStepPer, safetyDist, oddsLeaveAndSide, timeSide, distLeave) then return true end local distResponse = 3 local oddsResponse = 25 local oddsStep = 40 local bkStepPer = 60 local leftStepPer = 20 local rightStepPer = 20 local safetyDist = 2.8 local oddsLeaveAndSide = 50 local timeSide = 3.5 local distLeave = 2.5 if Damaged_Step_or_Guard(ai, goal, distResponse, oddsResponse, oddsStep, bkStepPer, leftStepPer, rightStepPer, safetyDist, oddsLeaveAndSide, timeSide, distLeave) then return true end local distGuardBreak_Act = 2.1 local oddsGuardBreak_Act = 30 if GuardBreak_Act(ai, goal, distGuardBreak_Act, oddsGuardBreak_Act) then goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) return true end local distMissSwing_Int = 5.5 local oddsMissSwing_Int = 60 if MissSwing_Int(ai, goal, distMissSwing_Int, oddsMissSwing_Int) then if targetDist <= 3.5 then goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, Att3000_Dist_max, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) else goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3003, TARGET_ENE_0, DIST_Middle, 0) end return true end local distUseItem_Act = 8 local oddsUseItem_Act = 15 if UseItem_Act(ai, goal, distUseItem_Act, oddsUseItem_Act) then if targetDist <= 3.5 then goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, Att3000_Dist_max, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) else goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, Att3003_Dist_max, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3003, TARGET_ENE_0, DIST_Middle, 0) end return true end local distResNear = 4.5 local distResFar = 13 local oddsResNear = 0 local oddsResFar = 50 local fate = ai:GetRandam_Int(1, 100) local fate2 = ai:GetRandam_Int(1, 100) local targetDist = ai:GetDist(TARGET_ENE_0) local ResBehavID = Shoot_2dist(ai, goal, distResNear, distResFar, oddsResNear, oddsResFar) if ResBehavID == 1 then goal:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Int(30, 45), true, true, 9910) elseif ResBehavID == 2 then goal:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Int(30, 45), true, true, 9910) end local oddsResponse = 50 local bkStepPer = 60 local leftStepPer = 20 local rightStepPer = 20 local safetyDist = 2.8 if RebByOpGuard_Step(ai, goal, oddsResponse, bkStepPer, leftStepPer, rightStepPer, safetyDist) then return true else local distSuccessGuard_Act = 2.1 local oddsSuccessGuard_Act = 50 if SuccessGuard_Act(ai, goal, distSuccessGuard_Act, oddsSuccessGuard_Act) then goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) return true else local ParryDist = 3 local ParryAng = 60 local ParryThrowDist = 4 local ParryThrowAng = 60 if Parry_Act(ai, goal, ParryDist, ParryAng, ParryThrowDist, ParryThrowAng) then return true else local ObserveNo = 0 local ApproachDist = 1 local TimerIndex = 0 local Time = 20 if Backstab_Act(ai, goal, ObserveNo, ApproachDist, TimerIndex, Time) then goal:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 4) return true else return false end end end end end return
0
0.936333
1
0.936333
game-dev
MEDIA
0.962397
game-dev
0.887654
1
0.887654
kuzia15/SA-MP-2.10
1,109
app/src/main/cpp/samp/game/Events/EventHandlerHistory.h
#pragma once #include "../Tasks/TaskTimer.h" #include "game/common.h" #include "game/Enums/eEventType.h" class CEvent; class CTask; struct CPedGTA; class CEventHandlerHistory { public: CTask* m_task = nullptr; CEvent* m_nonTempEvent = nullptr; CEvent* m_tempEvent = nullptr; CEvent* m_storedActiveEvent = nullptr; CTaskTimer m_storedActiveEventTimer; public: static void InjectHooks(); CEventHandlerHistory() = default; ~CEventHandlerHistory(); void ClearAllEvents(); void ClearNonTempEvent(); void ClearTempEvent(); void ClearStoredActiveEvent(); void Flush(); CEvent* GetCurrentEvent() { return m_tempEvent ? m_tempEvent : m_nonTempEvent; } int32 GetCurrentEventPriority(); CEvent* GetStoredActiveEvent() { return m_storedActiveEvent; } bool IsRespondingToEvent(eEventType eventType); void RecordCurrentEvent(CPedGTA* ped, CEvent& event); void StoreActiveEvent(); bool TakesPriorityOverCurrentEvent(CEvent& event); void TickStoredEvent(CPedGTA* ped); }; VALIDATE_SIZE(CEventHandlerHistory, (VER_x32 ? 0x1C : 0x30));
0
0.904013
1
0.904013
game-dev
MEDIA
0.950755
game-dev
0.732364
1
0.732364
PaperMC/Paper
7,132
paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java
package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; import java.util.Optional; import net.kyori.adventure.util.TriState; import net.minecraft.sounds.SoundEvent; import org.bukkit.Sound; import org.bukkit.craftbukkit.CraftLootTable; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftSound; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Mob; import org.bukkit.loot.LootTable; public abstract class CraftMob extends CraftLivingEntity implements Mob, io.papermc.paper.entity.PaperLeashable { // Paper - Leashable API private final com.destroystokyo.paper.entity.PaperPathfinder paperPathfinder; // Paper - Mob Pathfinding API public CraftMob(CraftServer server, net.minecraft.world.entity.Mob entity) { super(server, entity); this.paperPathfinder = new com.destroystokyo.paper.entity.PaperPathfinder(entity); // Paper - Mob Pathfinding API } @Override public net.minecraft.world.entity.Mob getHandle() { return (net.minecraft.world.entity.Mob) this.entity; } @Override public void setHandle(net.minecraft.world.entity.Entity entity) { super.setHandle(entity); this.paperPathfinder.setHandle(this.getHandle()); } @Override public boolean shouldDespawnInPeaceful() { return this.getHandle().shouldDespawnInPeaceful(); } @Override public void setDespawnInPeacefulOverride(final TriState state) { Preconditions.checkArgument(state != null, "TriState cannot be null"); this.getHandle().despawnInPeacefulOverride = state; } @Override public TriState getDespawnInPeacefulOverride() { return this.getHandle().despawnInPeacefulOverride; } @Override public com.destroystokyo.paper.entity.Pathfinder getPathfinder() { return this.paperPathfinder; } @Override public void setTarget(LivingEntity target) { Preconditions.checkState(!this.getHandle().generation, "Cannot set target during world generation"); net.minecraft.world.entity.Mob entity = this.getHandle(); if (target == null) { entity.setTarget(null, null); } else if (target instanceof CraftLivingEntity) { entity.setTarget(((CraftLivingEntity) target).getHandle(), null); } } @Override public CraftLivingEntity getTarget() { if (this.getHandle().getTarget() == null) return null; return (CraftLivingEntity) this.getHandle().getTarget().getBukkitEntity(); } @Override public void setAware(boolean aware) { this.getHandle().aware = aware; } @Override public boolean isAware() { return this.getHandle().aware; } @Override public Sound getAmbientSound() { SoundEvent sound = this.getHandle().getAmbientSound(); return (sound != null) ? CraftSound.minecraftToBukkit(sound) : null; } @Override public void setLootTable(LootTable table) { this.getHandle().lootTable = Optional.ofNullable(CraftLootTable.bukkitToMinecraft(table)); } @Override public LootTable getLootTable() { return CraftLootTable.minecraftToBukkit(this.getHandle().getLootTable().orElse(null)); } @Override public void setSeed(long seed) { this.getHandle().lootTableSeed = seed; } @Override public long getSeed() { return this.getHandle().lootTableSeed; } @Override public boolean isInDaylight() { return getHandle().isSunBurnTick(); } @Override public void lookAt(@org.jetbrains.annotations.NotNull org.bukkit.Location location) { com.google.common.base.Preconditions.checkNotNull(location, "location cannot be null"); com.google.common.base.Preconditions.checkArgument(location.getWorld().equals(getWorld()), "location in a different world"); getHandle().getLookControl().setLookAt(location.getX(), location.getY(), location.getZ()); } @Override public void lookAt(@org.jetbrains.annotations.NotNull org.bukkit.Location location, float headRotationSpeed, float maxHeadPitch) { com.google.common.base.Preconditions.checkNotNull(location, "location cannot be null"); com.google.common.base.Preconditions.checkArgument(location.getWorld().equals(getWorld()), "location in a different world"); getHandle().getLookControl().setLookAt(location.getX(), location.getY(), location.getZ(), headRotationSpeed, maxHeadPitch); } @Override public void lookAt(@org.jetbrains.annotations.NotNull org.bukkit.entity.Entity entity) { com.google.common.base.Preconditions.checkNotNull(entity, "entity cannot be null"); com.google.common.base.Preconditions.checkArgument(entity.getWorld().equals(getWorld()), "entity in a different world"); getHandle().getLookControl().setLookAt(((CraftEntity) entity).getHandle()); } @Override public void lookAt(@org.jetbrains.annotations.NotNull org.bukkit.entity.Entity entity, float headRotationSpeed, float maxHeadPitch) { com.google.common.base.Preconditions.checkNotNull(entity, "entity cannot be null"); com.google.common.base.Preconditions.checkArgument(entity.getWorld().equals(getWorld()), "entity in a different world"); getHandle().getLookControl().setLookAt(((CraftEntity) entity).getHandle(), headRotationSpeed, maxHeadPitch); } @Override public void lookAt(double x, double y, double z) { getHandle().getLookControl().setLookAt(x, y, z); } @Override public void lookAt(double x, double y, double z, float headRotationSpeed, float maxHeadPitch) { getHandle().getLookControl().setLookAt(x, y, z, headRotationSpeed, maxHeadPitch); } @Override public int getHeadRotationSpeed() { return getHandle().getHeadRotSpeed(); } @Override public int getMaxHeadPitch() { return getHandle().getMaxHeadXRot(); } @Override public boolean isLeftHanded() { return getHandle().isLeftHanded(); } @Override public void setLeftHanded(boolean leftHanded) { getHandle().setLeftHanded(leftHanded); } @Override public boolean isAggressive() { return this.getHandle().isAggressive(); } @Override public void setAggressive(boolean aggressive) { this.getHandle().setAggressive(aggressive); } @Override public int getPossibleExperienceReward() { return getHandle().getExperienceReward((net.minecraft.server.level.ServerLevel) this.getHandle().level(), null); } @Override public boolean isLeashed() { return io.papermc.paper.entity.PaperLeashable.super.isLeashed(); } @Override public org.bukkit.entity.Entity getLeashHolder() throws IllegalStateException { return io.papermc.paper.entity.PaperLeashable.super.getLeashHolder(); } @Override public boolean setLeashHolder(final org.bukkit.entity.Entity holder) { return io.papermc.paper.entity.PaperLeashable.super.setLeashHolder(holder); } }
0
0.907987
1
0.907987
game-dev
MEDIA
0.961959
game-dev
0.900076
1
0.900076
long-war-2/lwotc
20,157
LongWarOfTheChosen/Src/LW_Overhaul/Classes/UIStrategyMapItem_Region_LW.uc
//--------------------------------------------------------------------------------------- // FILE: UIStrategyMapItem_Region_LW.uc // AUTHOR: Amineri / Pavonis Interactive // PURPOSE: Provides on-map panel for outposts // This provides a scanning button for each outpost, as well as a button for accessing the new Outpost UI //--------------------------------------------------------------------------------------- class UIStrategyMapItem_Region_LW extends UIStrategyMapItem_Region config(LW_UI); var config bool SHOW_REGION_TOOLTIPS_CTRL; var localized string m_strOutpostTitle; var localized string m_strAlertLevel; var localized string m_strLiberatedRegion; var localized string m_strStaffingPinText; var localized string m_strStaffingPinTextMore; var localized string m_strMonthlyRegionalIncome; var string CachedRegionLabel; var string CachedHavenLabel; simulated function bool CanMakeContact() { return (class'UIUtilities_Strategy'.static.GetXComHQ().IsContactResearched() && (GetRegion().ResistanceLevel == eResLevel_Unlocked)); } simulated function bool IsContacted() { return ((GetRegion().ResistanceLevel == eResLevel_Contact) || (GetRegion().ResistanceLevel == eResLevel_Outpost)); } /* Issue # 815 : KDM : When using a controller, UIStrategyMap continuously calls UpdateSelection() --> SelectMapItemNearestLocation(). Now, within SelectMapItemNearestLocation() there is a loop which goes through each XComGameState_GeoscapeEntity and determines if its associated strategy map UI item is potentially selectable. The function IsSelectable() within UIStrategyMapItem_Region is rather odd since : 1.] It returns false if IsResHQRegion() is true; in other words, the HQ region isn't selectable. 2.] It returns false if the scan button type isn't eUIScanButtonType_Default, eUIScanButtonType_Contact, or eUIScanButtonType_Tower. Yet, the default scan button type is EUIScanButtonType_MAX which isn't even part of the enumeration. 3.] It doesn't appear to notice a region once it has a relay installed (eResLevel_Outpost). I have determined that : 1.] Whether a region is the HQ or not should have no bearing on selectability so ignore it entirely. 2.] The scan button type should have no bearing on selectability so ignore it entirely.*/ simulated function bool IsSelectable() { // KDM : The region is selectable if any of these conditions are true : // 1.] It is contactable, regardless of whether contacting has commenced. // 2.] It has been contacted, regardless of its radio relay status. // // The region is not selectable if any of these conditions are true : // 1.] It can't be contacted due to insufficient research level. // 2.] It is too far away. return (CanMakeContact() || IsContacted()); } simulated function UIStrategyMapItem InitMapItem(out XComGameState_GeoscapeEntity Entity) { local int i; local Object TextureObject; local Texture2D RegionTexture; local Vector2D CenterWorld; local X2WorldRegionTemplate RegionTemplate; local XComGameState NewGameState; local XComGameState_WorldRegion LandingSite; local XComGameStateHistory History; // Spawn the children BEFORE the super.Init because inside that super, it will trigger UpdateFlyoverText and other functions // which may assume these children already exist. ContactButton = Spawn(class'UILargeButton', self); OutpostButton = Spawn(class'UIButton', self); super(UIStrategyMapItem).InitMapItem(Entity); ContactButton.InitButton('contactButtonMC', m_strButtonMakeContact, OnContactClicked); // on stage ContactButton.OnMouseEventDelegate = ContactButtonOnMouseEvent; OutpostButton.InitButton('towerButtonMC', , OnOutpostClicked); // on stage OutpostButton.SetPosition(-5,118); ScanButton = Spawn(class'UIScanButton', self).InitScanButton(); ScanButton.SetPosition(49, 114); //This location is to stop overlapping the pin art. ScanButton.SetButtonIcon(""); ScanButton.SetDefaultDelegate(OnDefaultClicked); History = `XCOMHISTORY; LandingSite = XComGameState_WorldRegion(History.GetGameStateForObjectID(Entity.ObjectID)); RegionTemplate = LandingSite.GetMyTemplate(); TextureObject = `CONTENT.RequestGameArchetype(RegionTemplate.RegionTexturePath); if (TextureObject == none || !TextureObject.IsA('Texture2D')) { `RedScreen("Could not load region texture" @ RegionTemplate.RegionTexturePath); return self; } RegionTexture = Texture2D(TextureObject); RegionMesh = class'Helpers'.static.ConstructRegionActor(RegionTexture); for (i = 0; i < NUM_TILES; ++i) { InitRegionComponent(i, RegionTemplate); } class'Helpers'.static.GenerateCumulativeTriangleAreaArray(RegionComponents[0], CumulativeTriangleArea); // Update the Center location based on the mesh's centroid CenterWorld = `EARTH.ConvertWorldToEarth(class'Helpers'.static.GetRegionCenterLocation(RegionComponents[0], true)); if (Entity.Get2DLocation() != CenterWorld) { NewGameState = class'XComGameStateContext_ChangeContainer'.static.CreateChangeState("Update Region Center"); Entity = XComGameState_WorldRegion(NewGameState.CreateStateObject(class'XComGameState_GeoscapeEntity', Entity.ObjectID)); NewGameState.AddStateObject(Entity); Entity.Location.X = CenterWorld.X; Entity.Location.Y = CenterWorld.Y; `XCOMGAME.GameRuleset.SubmitGameState(NewGameState); } // KDM : A Long War 2 (contacted) region map item, generally speaking, has 3 buttons; we will say it has : // 1.] A radio tower button, which opens up the corresponding haven rebel screen. // 2.] A haven information button, which displays the haven region's name, advent strength, vigilance, and force. // 3.] A scan button, which starts and stops scanning at the location. // // Unfortunately, many of these buttons have help icons attached to them within flash when a controller is used. // The reason I say "unfortunately", is because they were never designed for Long War 2 usage; sometimes they will // display incorrect icons, while other times they will overlap UI elements they should not. The easiest way to deal // with them, normally, would be to set their visiblity to false, or their alpha to 0; however, they are tweened all // over the place within the Actionscript code. The result is that nulling them is the only method which will get rid of them ! // // Within Actionscript there are 4 help icons : // 1.] MapItem_Region --> consoleHint is the help icon which appears to the left of the radio tower button; it must be removed. // 2.] StrategyScanButton --> scanHint is the help icon which appears to the right of the scan button, when visible; it must be removed. // 3.] StrategyScanButton --> consoleHint appears to the left of the haven information button when no scan button is visible; it must be removed. // 4.] StrategyScanButton --> buyHint appears not to be used in region map items so it is left alone. if (`ISCONTROLLERACTIVE) { mc.SetNull("consoleHint"); ScanButton.mc.SetNull("consoleHint"); ScanButton.mc.SetNull("scanHint"); } return self; } function bool ShouldDrawResInfo(XComGameState_WorldRegion RegionState) { if (RegionState.bCanScanForContact || RegionState.HaveMadeContact()) { return true; } else if( GetStrategyMap() != none && GetStrategyMap().m_eUIState == eSMS_Resistance ) { return true; } return false; } function UpdateFlyoverText() { local XComGameStateHistory History; local XComGameState_WorldRegion RegionState; local XComGameState_AdventChosen ControllingChosen; local String RegionLabel; local String HavenLabel; local String StateLabel; local string HoverInfo; local int iResLevel; local XComGameState_LWOutpostManager OutpostManager; local XComGameState_LWOutpost OutpostState; History = `XCOMHISTORY; RegionState = XComGameState_WorldRegion(History.GetGameStateForObjectID(GeoscapeEntityRef.ObjectID)); OutpostManager = class'XComGameState_LWOutpostManager'.static.GetOutpostManager(); OutpostState = OutpostManager.GetOutpostForRegion(RegionState); HavenLabel = GetHavenLabel(RegionState, OutpostState); RegionLabel = GetRegionLabel(RegionState, OutpostState); ControllingChosen = RegionState.GetControllingChosen(); if( ControllingChosen != none && ControllingChosen.bMetXCom && !ControllingChosen.bDefeated && RegionState.HaveMadeContact() ) { AS_SetChosenIcon(ControllingChosen.GetChosenIcon()); } HoverInfo = ""; if (ShowContactButton()) { ContactButton.Show(); if (ShouldDrawResInfo(RegionState)) { HavenLabel = class'UIResistanceManagement_LW'.default.m_strRebelCountLabel $ ": " $ OutpostState.GetRebelCount(); HavenLabel = class'UIUtilities_Text'.static.GetColoredText(HavenLabel, GetIncomeColor(RegionState.ResistanceLevel)); } } else { ContactButton.Hide(); } if (RegionState.HaveMadeContact()) OutpostButton.Show(); else OutpostButton.Hide(); StateLabel = ""; //Possibly unused. if (IsResHQRegion()) iResLevel = eResLevel_Outpost + 1; else iResLevel = RegionState.ResistanceLevel; CachedRegionLabel = RegionLabel; CachedHavenLabel = HavenLabel; SetRegionInfo(RegionLabel, HavenLabel, StateLabel, iResLevel, HoverInfo); } function string GetRegionLabel(XComGameState_WorldRegion RegionState, optional XComGameState_LWOutpost OutpostState) { local String RegionLabel, StrAdviser; local XGParamTag ParamTag; local XComGameState_Unit Liaison; local StateObjectReference LiaisonRef; if (RegionState.HaveMadeContact()) { ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam")); ParamTag.IntValue0 = OutpostState.GetNumRebelsOnJob('Resupply'); ParamTag.IntValue1 = OutpostState.GetNumRebelsOnJob('Intel'); ParamTag.IntValue2 = OutpostState.GetNumRebelsOnJob('Recruit'); RegionLabel = `XEXPAND.ExpandString(m_strStaffingPinText); ParamTag.IntValue0 = OutpostState.GetNumRebelsOnJob('Hiding'); RegionLabel = RegionLabel @ `XEXPAND.ExpandString(m_strStaffingPinTextMore); if (OutPostState.HasLiaisonOfKind ('Soldier')) { LiaisonRef = OutPostState.GetLiaison(); Liaison = XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(LiaisonRef.ObjectID)); strAdviser = class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.static.GetRankIcon(Liaison.GetRank(), Liaison.GetSoldierClassTemplateName()), 16, 16, -2); } if (OutPostState.HasLiaisonOfKind ('Engineer')) { strAdviser = class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.const.EventQueue_Engineer, 16, 16, -2); } if (OutPostState.HasLiaisonOfKind ('Scientist')) { strAdviser = class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.const.EventQueue_Science, 16, 16, -2); } if (strAdviser != "") { RegionLabel @= strAdviser; } } else { RegionLabel = class'UIUtilities_Text'.static.GetColoredText(RegionState.GetMyTemplate().DisplayName, GetRegionLabelColor()); } return RegionLabel; } function string GetHavenLabel(XComGameState_WorldRegion RegionState, optional XComGameState_LWOutpost OutpostState) { local String HavenLabel; local XGParamTag ParamTag; HavenLabel = ""; // Blank string will tell the supply income and region state to hide if (RegionState.HaveMadeContact()) { ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam")); ParamTag.IntValue0 = int(OutpostState.GetIncomePoolForJob('Resupply')); ParamTag.IntValue1 = int(OutpostState.GetProjectedMonthlyIncomeForJob('Resupply')); HavenLabel = `XEXPAND.ExpandString(m_strMonthlyRegionalIncome); HavenLabel = class'UIUtilities_Text'.static.GetColoredText(HavenLabel, GetIncomeColor(RegionState.ResistanceLevel)); } return HavenLabel; } function UpdateFromGeoscapeEntity(const out XComGameState_GeoscapeEntity GeoscapeEntity) { local XComGameState_WorldRegion RegionState; local string ScanTitle; local string ScanTimeValue; local string ScanTimeLabel; local string ScanInfo; local int DaysRemaining; local String RegionLabel; local XComGameState_LWOutpostManager OutpostManager; local XComGameState_LWOutpost OutpostState; local XGParamTag ParamTag; if (!bIsInited) return; super(UIStrategyMapItem).UpdateFromGeoscapeEntity(GeoscapeEntity); RegionState = GetRegion(); if (!RegionState.HaveMadeContact() && !IsAvengerLandedHere() && !RegionState.bCanScanForContact) { ScanButton.Hide(); } else { RegionLabel = class'UIUtilities_Text'.static.GetColoredText(RegionState.GetMyTemplate().DisplayName, GetRegionLabelColor()); OutpostManager = class'XComGameState_LWOutpostManager'.static.GetOutpostManager(); OutpostState = OutpostManager.GetOutpostForRegion(RegionState); if (GetRegionLabel(RegionState, OutpostState) != CachedRegionLabel || GetHavenLabel(RegionState, OutpostState) != CachedHavenLabel) UpdateFlyoverText(); ScanButton.Show(); if (IsAvengerLandedHere()) { ScanButton.SetButtonState(eUIScanButtonState_Expanded); ScanButton.SetButtonType(eUIScanButtonType_Default); } else { ScanButton.SetButtonState(eUIScanButtonState_Default); ScanButton.SetButtonType(eUIScanButtonType_Default); } if (RegionState.bCanScanForContact) { ScanTitle = m_strScanForIntelLabel; DaysRemaining = RegionState.GetNumScanDaysRemaining(); ScanTimeValue = string(DaysRemaining); ScanTimeLabel = class'UIUtilities_Text'.static.GetDaysString(DaysRemaining); ScanInfo = ""; } else if( RegionState.bCanScanForOutpost ) { ScanTitle = m_strScanForOutpostLabel; ScanInfo = GetContactedRegionInfo(RegionState); DaysRemaining = RegionState.GetNumScanDaysRemaining(); ScanTimeValue = string(DaysRemaining); ScanTimeLabel = class'UIUtilities_Text'.static.GetDaysString(DaysRemaining); } else { ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam")); ParamTag.StrValue0 = RegionLabel; ScanTitle = `XEXPAND.ExpandString(m_strOutpostTitle); ScanInfo = GetContactedRegionInfo(RegionState); ScanTimeValue = ""; ScanTimeLabel = ""; } ScanButton.SetText(ScanTitle, ScanInfo, ScanTimeValue, ScanTimeLabel); ScanButton.AnimateIcon(`GAME.GetGeoscape().IsScanning() && IsAvengerLandedHere()); ScanButton.SetScanMeter(RegionState.GetScanPercentComplete()); ScanButton.Realize(); } } function string GetContactedRegionInfo(XComGameState_WorldRegion RegionState) { local string ScanInfo; local XComGameState_WorldRegion_LWStrategyAI RegionalAIState; local XGParamTag ParamTag; ScanInfo = ""; RegionalAIState = class'XComGameState_WorldRegion_LWStrategyAI'.static.GetRegionalAI(RegionState); if (RegionalAIState != none) { if (RegionalAIState.bLiberated) { ScanInfo = m_strLiberatedRegion; } else if(IsContacted()) { ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam")); //Primary text display ParamTag.IntValue0 = RegionalAIState.LocalAlertLevel; ParamTag.IntValue1 = RegionalAIState.LocalForceLevel; ParamTag.IntValue2 = RegionalAIState.LocalVigilanceLevel; // Re-did the main m_strAlertLevel to be the mod's previous "short version" ScanInfo = `XEXPAND.ExpandString(m_strAlertLevel); } else { ScanInfo = "?????"; } } return ScanInfo; } function OnOutpostClicked(UIButton Button) { local XComGameStateHistory History; local XComGameState_WorldRegion RegionState; local UIOutpostManagement OutpostScreen; local StateObjectReference OutpostRef; local XComHQPresentationLayer HQPres; local XComGameState_LWOutpostManager OutpostManager; local XComGameState_LWOutpost OutpostState; History = `XCOMHISTORY; RegionState = XComGameState_WorldRegion(History.GetGameStateForObjectID(GeoscapeEntityRef.ObjectID)); OutpostManager = class'XComGameState_LWOutpostManager'.static.GetOutpostManager(); OutpostState = OutpostManager.GetOutpostForRegion(RegionState); HQPres = `HQPRES; OutpostRef = OutpostState.GetReference(); OutpostScreen = HQPres.Spawn(class'UIOutpostManagement', HQPres); OutpostScreen.SetOutpost(OutpostRef); `SCREENSTACK.Push(OutpostScreen); } function OnDefaultClicked() { if (GetRegion().ResistanceActive()) { if (!IsAvengerLandedHere()) { if (!DisplayInterruptionPopup()) { GetRegion().ConfirmSelection(); } } } } // Making a copy of this dialogue chain since the is tied to the XComGameState_Region.CanInteract, which we don't want to override // On attempted selection, if the Skyranger is considered "busy" (ex. waiting on a POI to complete), display a popup // to allow user to choose whether to change activities to the new selection. function bool DisplayInterruptionPopup() { local XComGameState_GeoscapeEntity EntityState; local TDialogueBoxData DialogData; local XComGameState NewGameState; EntityState = GetRegion().GetCurrentEntityInteraction(); if (EntityState != None && EntityState.ObjectID != GetRegion().ObjectID) { // display the popup GetRegion().BeginInteraction(); // pauses the Geoscape //EntityState.OnInterruptionPopup(); -- can't access this, so directly call the TriggerEvent if appropriate if (XComGameState_WorldRegion(EntityState) != none) { NewGameState = class'XComGameStateContext_ChangeContainer'.static.CreateChangeState("Trigger Leaving Contact Site Without Scanning Event"); `XEVENTMGR.TriggerEvent('LeaveContactWithoutScan', , , NewGameState); `XCOMGAME.GameRuleset.SubmitGameState(NewGameState); } DialogData.strText = class'XComGameState_PointOfInterest'.default.m_strScanInteruptionText; //EntityState.GetInterruptionPopupQueryText(); DialogData.eType = eDialog_Normal; DialogData.strAccept = class'UIDialogueBox'.default.m_strDefaultAcceptLabel; DialogData.strCancel = class'UIDialogueBox'.default.m_strDefaultCancelLabel; DialogData.fnCallback = InterruptionPopupCallback; `HQPRES.UIRaiseDialog( DialogData ); return true; } return false; } simulated public function InterruptionPopupCallback(Name eAction) { local XComGameState_GeoscapeEntity EntityState; if (eAction == 'eUIAction_Accept') { // Give the entity being interrupted an opportunity to cleanup state EntityState = GetRegion().GetCurrentEntityInteraction(); `assert(EntityState != none); //EntityState.HandleInterruption(); // Attempt to select this entity again, now that the previous interaction has been canceled. GetRegion().InteractionComplete(true); GetRegion().ConfirmSelection(); } else if(eAction == 'eUIAction_Cancel') { GetRegion().InteractionComplete(false); } } function GenerateTooltip(string tooltipHTML) { // KDM : If a controller is being used, and SHOW_REGION_TOOLTIPS_CTRL is false, skip tooltip generation so no region tooltips show up. // The problem with region tooltips is that they were never designed for Long War; some of them are quite long, and oftentimes, they provide // information which is simply not relevant. if ((!`ISCONTROLLERACTIVE) || SHOW_REGION_TOOLTIPS_CTRL) { super.GenerateTooltip(tooltipHTML); } } simulated function bool OnUnrealCommand(int cmd, int arg) { local bool bHandled; if (!CheckInputIsReleaseOrDirectionRepeat(cmd, arg)) { return true; } bHandled = true; switch(cmd) { case class'UIUtilities_Input'.const.FXS_BUTTON_A: // KDM : A button opens up the "Make Contact" pop up screen if the contact button is visible. // Long War 2 code within UpdateFlyoverText() determines if the contact button should be visible. if (ContactButton.bIsVisible) { OnContactClicked(ContactButton); } // KDM : A button toggles scanning if the Avenger is currently at this region location. else if (IsAvengerLandedHere()) { ScanButton.ClickButtonScan(); } // KDM : A button travels to this region location if possible. else { OnDefaultClicked(); } break; case class'UIUtilities_Input'.const.FXS_BUTTON_X: // KDM : X button opens up this haven's rebel screen if the outpost button is visible. // Long War 2 code within UpdateFlyoverText() determines if the outpost button should be visible. if (OutpostButton.bIsVisible) { OnOutpostClicked(OutpostButton); } break; default: bHandled = false; break; } return bHandled || super(UIStrategyMapItem).OnUnrealCommand(cmd, arg); } defaultproperties { bDisableHitTestWhenZoomedOut = false; bProcessesMouseEvents = false; }
0
0.932285
1
0.932285
game-dev
MEDIA
0.950441
game-dev
0.906313
1
0.906313
flutter/flaux
2,985
engine/src/flutter/third_party/accessibility/ax/ax_node_position.h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_ACCESSIBILITY_AX_NODE_POSITION_H_ #define UI_ACCESSIBILITY_AX_NODE_POSITION_H_ #include <cstdint> #include <vector> #include "ax_enums.h" #include "ax_export.h" #include "ax_node.h" #include "ax_position.h" #include "ax_tree_id.h" namespace ui { // AXNodePosition includes implementations of AXPosition methods which require // knowledge of the AXPosition AXNodeType (which is unknown by AXPosition). class AX_EXPORT AXNodePosition : public AXPosition<AXNodePosition, AXNode> { public: // Creates either a text or a tree position, depending on the type of the node // provided. static AXPositionInstance CreatePosition( const AXNode& node, int child_index_or_text_offset, ax::mojom::TextAffinity affinity = ax::mojom::TextAffinity::kDownstream); AXNodePosition(); ~AXNodePosition() override; AXNodePosition(const AXNodePosition& other); AXPositionInstance Clone() const override; std::u16string GetText() const override; bool IsInLineBreak() const override; bool IsInTextObject() const override; bool IsInWhiteSpace() const override; int MaxTextOffset() const override; protected: void AnchorChild(int child_index, AXTreeID* tree_id, AXNode::AXID* child_id) const override; int AnchorChildCount() const override; int AnchorUnignoredChildCount() const override; int AnchorIndexInParent() const override; int AnchorSiblingCount() const override; std::stack<AXNode*> GetAncestorAnchors() const override; AXNode* GetLowestUnignoredAncestor() const override; void AnchorParent(AXTreeID* tree_id, AXNode::AXID* parent_id) const override; AXNode* GetNodeInTree(AXTreeID tree_id, AXNode::AXID node_id) const override; AXNode::AXID GetAnchorID(AXNode* node) const override; AXTreeID GetTreeID(AXNode* node) const override; bool IsEmbeddedObjectInParent() const override; bool IsInLineBreakingObject() const override; ax::mojom::Role GetAnchorRole() const override; ax::mojom::Role GetRole(AXNode* node) const override; AXNodeTextStyles GetTextStyles() const override; std::vector<int32_t> GetWordStartOffsets() const override; std::vector<int32_t> GetWordEndOffsets() const override; AXNode::AXID GetNextOnLineID(AXNode::AXID node_id) const override; AXNode::AXID GetPreviousOnLineID(AXNode::AXID node_id) const override; private: // Returns the parent node of the provided child. Returns the parent // node's tree id and node id through the provided output parameters, // |parent_tree_id| and |parent_id|. static AXNode* GetParent(AXNode* child, AXTreeID child_tree_id, AXTreeID* parent_tree_id, AXNode::AXID* parent_id); }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_NODE_POSITION_H_
0
0.894638
1
0.894638
game-dev
MEDIA
0.426957
game-dev
0.786579
1
0.786579
mean00/avidemux2
3,418
avidemux_plugins/ADM_scriptEngines/qtScript/src/SegmentCollection.cpp
#include <QtScript/QScriptClassPropertyIterator> #include "Segment.h" #include "SegmentCollection.h" #include "SegmentCollectionPrototype.h" namespace ADM_qtScript { class SegmentCollectionClassPropertyIterator : public QScriptClassPropertyIterator { public: SegmentCollectionClassPropertyIterator(IEditor *editor, const QScriptValue &object); ~SegmentCollectionClassPropertyIterator(); bool hasNext() const; void next(); bool hasPrevious() const; void previous(); void toFront(); void toBack(); QScriptString name() const; uint id() const; private: IEditor *_editor; uint _index; int _last; }; SegmentCollection::SegmentCollection(QScriptEngine *engine, IEditor *editor) : QObject(engine), QScriptClass(engine) { this->_editor = editor; this->_prototype = engine->newQObject( new SegmentCollectionPrototype(this, editor), QScriptEngine::ScriptOwnership, QScriptEngine::SkipMethodsInEnumeration | QScriptEngine::ExcludeSuperClassMethods | QScriptEngine::ExcludeSuperClassProperties); } QString SegmentCollection::name() const { return QLatin1String("SegmentCollection"); } QScriptClassPropertyIterator* SegmentCollection::newIterator(const QScriptValue &object) { return new SegmentCollectionClassPropertyIterator(this->_editor, object); } QScriptValue SegmentCollection::property( const QScriptValue &object, const QScriptString &name, uint id) { if (id >= this->_editor->getNbSegment()) { return QScriptValue(); } return this->engine()->newQObject( new Segment(this->_editor, this->_editor->getSegment(id)), QScriptEngine::ScriptOwnership); } QScriptValue::PropertyFlags SegmentCollection::propertyFlags( const QScriptValue &object, const QScriptString &name, uint id) { return QScriptValue::Undeletable; } QScriptValue SegmentCollection::prototype() const { return this->_prototype; } QScriptClass::QueryFlags SegmentCollection::queryProperty( const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id) { bool isArrayIndex; quint32 pos = name.toArrayIndex(&isArrayIndex); if (!isArrayIndex) { return 0; } *id = pos; if (pos >= this->_editor->getNbSegment()) { return 0; } return flags; } SegmentCollectionClassPropertyIterator::SegmentCollectionClassPropertyIterator( IEditor* editor, const QScriptValue &object) : QScriptClassPropertyIterator(object) { this->_editor = editor; this->toFront(); } SegmentCollectionClassPropertyIterator::~SegmentCollectionClassPropertyIterator() { } bool SegmentCollectionClassPropertyIterator::hasNext() const { return _index < this->_editor->getNbSegment(); } void SegmentCollectionClassPropertyIterator::next() { _last = _index; ++_index; } bool SegmentCollectionClassPropertyIterator::hasPrevious() const { return (_index > 0); } void SegmentCollectionClassPropertyIterator::previous() { --_index; _last = _index; } void SegmentCollectionClassPropertyIterator::toFront() { _index = 0; _last = -1; } void SegmentCollectionClassPropertyIterator::toBack() { _index = this->_editor->getNbSegment(); _last = -1; } QScriptString SegmentCollectionClassPropertyIterator::name() const { return object().engine()->toStringHandle(QString::number(_last)); } uint SegmentCollectionClassPropertyIterator::id() const { return _last; } }
0
0.762334
1
0.762334
game-dev
MEDIA
0.428404
game-dev
0.855521
1
0.855521
babelshift/SteamWebAPI2
4,292
src/Steam.Models/DOTA2/Cleaned/HeroDetail.cs
using System; using System.Collections.Generic; namespace Steam.Models.DOTA2 { public class HeroDetail { private const int baseHealth = 150; private const int healthPerStrength = 19; private const int baseMana = 0; private const int manaPerIntellect = 13; private const double armorFactor = 0.14; public uint Id { get; set; } public string Url { get; set; } public string Name { get; set; } public string NameInSchema { get; set; } public string Description { get; set; } public string AvatarImagePath { get; set; } public uint BaseStrength { get; set; } public uint BaseAgility { get; set; } public uint BaseIntelligence { get; set; } public uint BaseDamageMin { get; set; } public uint BaseDamageMax { get; set; } public uint BaseMoveSpeed { get; set; } public double BaseArmor { get; set; } public string Team { get; set; } public double AttackRange { get; set; } public double AttackRate { get; set; } public double TurnRate { get; set; } public string AttackType { get; set; } public double StrengthGain { get; set; } public double AgilityGain { get; set; } public double IntelligenceGain { get; set; } public DotaHeroPrimaryAttributeType PrimaryAttribute { get; set; } public string ActiveTab { get; set; } public string MinimapIconPath { get; set; } public bool IsEnabled { get; set; } public IReadOnlyCollection<HeroRole> Roles { get; set; } public IReadOnlyCollection<HeroAbilityDetail> Abilities { get; set; } public double GetBaseHealth() { return GetHealth(0); } public double GetBaseMana() { return GetMana(0); } public double GetHealth(int level) { return Math.Round(baseHealth + (healthPerStrength * (BaseStrength + (level * StrengthGain)))); } public double GetMana(int level) { return Math.Round(baseMana + (manaPerIntellect * (BaseIntelligence + (level * IntelligenceGain)))); } public double GetMinDamage(int level) { if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.STRENGTH.Key) { return Math.Round(BaseDamageMin + (BaseStrength + (level * StrengthGain))); } else if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.INTELLECT.Key) { return Math.Round(BaseDamageMin + (BaseIntelligence + (level * IntelligenceGain))); } else if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.AGILITY.Key) { return Math.Round(BaseDamageMin + (BaseAgility + (level * AgilityGain))); } else { return 0; } } public double GetMaxDamage(int level) { if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.STRENGTH.Key) { return Math.Round(BaseDamageMax + (BaseStrength + (level * StrengthGain))); } else if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.INTELLECT.Key) { return Math.Round(BaseDamageMax + (BaseIntelligence + (level * IntelligenceGain))); } else if (PrimaryAttribute.Key == DotaHeroPrimaryAttributeType.AGILITY.Key) { return Math.Round(BaseDamageMax + (BaseAgility + (level * AgilityGain))); } else { return 0; } } public double GetArmor(int level) { return BaseArmor + (GetAgility(level) * armorFactor); } public double GetStrength(int level) { return Math.Round(BaseStrength + (level * StrengthGain)); } public double GetAgility(int level) { return Math.Round(BaseAgility + (level * AgilityGain)); } public double GetIntelligence(int level) { return Math.Round(BaseIntelligence + (level * IntelligenceGain)); } } }
0
0.861301
1
0.861301
game-dev
MEDIA
0.952079
game-dev
0.960198
1
0.960198
AtomicGameEngine/AtomicGameEngine
3,096
Source/ThirdParty/Bullet/src/BulletCollision/CollisionShapes/btUniformScalingShape.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_UNIFORM_SCALING_SHAPE_H #define BT_UNIFORM_SCALING_SHAPE_H #include "btConvexShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types ///The btUniformScalingShape allows to re-use uniform scaled instances of btConvexShape in a memory efficient way. ///Istead of using btUniformScalingShape, it is better to use the non-uniform setLocalScaling method on convex shapes that implement it. ATTRIBUTE_ALIGNED16(class) btUniformScalingShape : public btConvexShape { btConvexShape* m_childConvexShape; btScalar m_uniformScalingFactor; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btUniformScalingShape( btConvexShape* convexChildShape, btScalar uniformScalingFactor); virtual ~btUniformScalingShape(); virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; btScalar getUniformScalingFactor() const { return m_uniformScalingFactor; } btConvexShape* getChildShape() { return m_childConvexShape; } const btConvexShape* getChildShape() const { return m_childConvexShape; } virtual const char* getName()const { return "UniformScalingShape"; } /////////////////////////// ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void setLocalScaling(const btVector3& scaling) ; virtual const btVector3& getLocalScaling() const ; virtual void setMargin(btScalar margin); virtual btScalar getMargin() const; virtual int getNumPreferredPenetrationDirections() const; virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const; }; #endif //BT_UNIFORM_SCALING_SHAPE_H
0
0.925721
1
0.925721
game-dev
MEDIA
0.984634
game-dev
0.778531
1
0.778531
CaffeineMC/sodium
1,268
common/src/main/java/net/caffeinemc/mods/sodium/mixin/core/world/chunk/SimpleBitStorageMixin.java
package net.caffeinemc.mods.sodium.mixin.core.world.chunk; import net.caffeinemc.mods.sodium.client.world.BitStorageExtension; import net.minecraft.util.SimpleBitStorage; import net.minecraft.world.level.chunk.Palette; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.util.Objects; @Mixin(SimpleBitStorage.class) public class SimpleBitStorageMixin implements BitStorageExtension { @Shadow @Final private long[] data; @Shadow @Final private int valuesPerLong; @Shadow @Final private long mask; @Shadow @Final private int bits; @Shadow @Final private int size; @Override public <T> void sodium$unpack(T[] out, Palette<T> palette) { int idx = 0; for (long word : this.data) { long l = word; for (int j = 0; j < this.valuesPerLong; ++j) { out[idx] = Objects.requireNonNull(palette.valueFor((int) (l & this.mask)), "Palette does not contain entry for value in storage"); l >>= this.bits; if (++idx >= this.size) { return; } } } } }
0
0.66291
1
0.66291
game-dev
MEDIA
0.992482
game-dev
0.809805
1
0.809805
BluRosie/hg-engine
1,139
armips/move/move_anim/378.s
.nds .thumb .include "armips/include/animscriptcmd.s" .include "asm/include/abilities.inc" .include "asm/include/items.inc" .include "asm/include/species.inc" .include "asm/include/moves.inc" .create "build/move/move_anim/0_378", 0 a010_378: initspriteresource loadspriteresource 0 loadspriteresource 1 loadspriteresource 2 loadspriteresource 3 loadspritemaybe 4, 0, 0, 0 loadspritemaybe 5, 0, 1, 1 loadspritemaybe 6, 0, 2, 2 loadspritemaybe 7, 0, 3, 3 callfunction 78, 1, 0, "NaN", "NaN", "NaN", "NaN", "NaN", "NaN", "NaN", "NaN", "NaN" loadparticle 0, 396 waitstate unloadspriteresource resetsprite 0 resetsprite 1 resetsprite 2 resetsprite 3 addparticle 0, 1, 17 cmd37 6, 0, 2, 2, 0, 0, 0, "NaN", "NaN" addparticle 0, 0, 17 cmd37 6, 0, 2, 2, 0, 0, 0, "NaN", "NaN" repeatse 1825, 117, 10, 5 loop 3 callfunction 42, 8, 264, 100, 80, 100, 140, 100, 1, 327685, "NaN", "NaN" wait 10 callfunction 42, 8, 264, 100, 120, 100, 80, 100, 1, 327685, "NaN", "NaN" wait 10 doloop waitparticle unloadparticle 0 end .close
0
0.812685
1
0.812685
game-dev
MEDIA
0.860748
game-dev
0.945563
1
0.945563
chunying/gaminganywhere
11,000
ga/server/event-driven/sdl12-event.h
/* * Copyright (c) 2013 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef __SDL12_EVENT_H__ #define __SDL12_EVENT_H__ #include <SDL2/SDL_keycode.h> #define SDL_RELEASED 0 #define SDL_PRESSED 1 typedef enum { SDL12_ADDEVENT, SDL12_PEEKEVENT, SDL12_GETEVENT } SDL12_eventaction; /* SDL 1.2 event type */ /** Event enumerations */ typedef enum { SDL12_NOEVENT = 0, /**< Unused (do not remove) */ SDL12_ACTIVEEVENT, /**< Application loses/gains visibility */ SDL12_KEYDOWN, /**< Keys pressed */ SDL12_KEYUP, /**< Keys released */ SDL12_MOUSEMOTION, /**< Mouse moved */ SDL12_MOUSEBUTTONDOWN, /**< Mouse button pressed */ SDL12_MOUSEBUTTONUP, /**< Mouse button released */ SDL12_JOYAXISMOTION, /**< Joystick axis motion */ SDL12_JOYBALLMOTION, /**< Joystick trackball motion */ SDL12_JOYHATMOTION, /**< Joystick hat position change */ SDL12_JOYBUTTONDOWN, /**< Joystick button pressed */ SDL12_JOYBUTTONUP, /**< Joystick button released */ SDL12_QUIT, /**< User-requested quit */ SDL12_SYSWMEVENT, /**< System specific event */ SDL12_EVENT_RESERVEDA, /**< Reserved for future use.. */ SDL12_EVENT_RESERVEDB, /**< Reserved for future use.. */ SDL12_VIDEORESIZE, /**< User resized video mode */ SDL12_VIDEOEXPOSE, /**< Screen needs to be redrawn */ SDL12_EVENT_RESERVED2, /**< Reserved for future use.. */ SDL12_EVENT_RESERVED3, /**< Reserved for future use.. */ SDL12_EVENT_RESERVED4, /**< Reserved for future use.. */ SDL12_EVENT_RESERVED5, /**< Reserved for future use.. */ SDL12_EVENT_RESERVED6, /**< Reserved for future use.. */ SDL12_EVENT_RESERVED7, /**< Reserved for future use.. */ /** Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ SDL12_USEREVENT = 24, /** This last event is only for bounding internal arrays * It is the number of bits in the event mask datatype -- Uint32 */ SDL12_NUMEVENTS = 32 } SDL12_EventType; typedef enum { /** @name ASCII mapped keysyms * The keyboard syms have been cleverly chosen to map to ASCII */ /*@{*/ SDLK12_UNKNOWN = 0, SDLK12_FIRST = 0, SDLK12_BACKSPACE = 8, SDLK12_TAB = 9, SDLK12_CLEAR = 12, SDLK12_RETURN = 13, SDLK12_PAUSE = 19, SDLK12_ESCAPE = 27, SDLK12_SPACE = 32, SDLK12_EXCLAIM = 33, SDLK12_QUOTEDBL = 34, SDLK12_HASH = 35, SDLK12_DOLLAR = 36, SDLK12_AMPERSAND = 38, SDLK12_QUOTE = 39, SDLK12_LEFTPAREN = 40, SDLK12_RIGHTPAREN = 41, SDLK12_ASTERISK = 42, SDLK12_PLUS = 43, SDLK12_COMMA = 44, SDLK12_MINUS = 45, SDLK12_PERIOD = 46, SDLK12_SLASH = 47, SDLK12_0 = 48, SDLK12_1 = 49, SDLK12_2 = 50, SDLK12_3 = 51, SDLK12_4 = 52, SDLK12_5 = 53, SDLK12_6 = 54, SDLK12_7 = 55, SDLK12_8 = 56, SDLK12_9 = 57, SDLK12_COLON = 58, SDLK12_SEMICOLON = 59, SDLK12_LESS = 60, SDLK12_EQUALS = 61, SDLK12_GREATER = 62, SDLK12_QUESTION = 63, SDLK12_AT = 64, /* Skip uppercase letters */ SDLK12_LEFTBRACKET = 91, SDLK12_BACKSLASH = 92, SDLK12_RIGHTBRACKET = 93, SDLK12_CARET = 94, SDLK12_UNDERSCORE = 95, SDLK12_BACKQUOTE = 96, SDLK12_a = 97, SDLK12_b = 98, SDLK12_c = 99, SDLK12_d = 100, SDLK12_e = 101, SDLK12_f = 102, SDLK12_g = 103, SDLK12_h = 104, SDLK12_i = 105, SDLK12_j = 106, SDLK12_k = 107, SDLK12_l = 108, SDLK12_m = 109, SDLK12_n = 110, SDLK12_o = 111, SDLK12_p = 112, SDLK12_q = 113, SDLK12_r = 114, SDLK12_s = 115, SDLK12_t = 116, SDLK12_u = 117, SDLK12_v = 118, SDLK12_w = 119, SDLK12_x = 120, SDLK12_y = 121, SDLK12_z = 122, SDLK12_DELETE = 127, /* End of ASCII mapped keysyms */ /*@}*/ /** @name International keyboard syms */ /*@{*/ SDLK12_WORLD_0 = 160, /* 0xA0 */ SDLK12_WORLD_1 = 161, SDLK12_WORLD_2 = 162, SDLK12_WORLD_3 = 163, SDLK12_WORLD_4 = 164, SDLK12_WORLD_5 = 165, SDLK12_WORLD_6 = 166, SDLK12_WORLD_7 = 167, SDLK12_WORLD_8 = 168, SDLK12_WORLD_9 = 169, SDLK12_WORLD_10 = 170, SDLK12_WORLD_11 = 171, SDLK12_WORLD_12 = 172, SDLK12_WORLD_13 = 173, SDLK12_WORLD_14 = 174, SDLK12_WORLD_15 = 175, SDLK12_WORLD_16 = 176, SDLK12_WORLD_17 = 177, SDLK12_WORLD_18 = 178, SDLK12_WORLD_19 = 179, SDLK12_WORLD_20 = 180, SDLK12_WORLD_21 = 181, SDLK12_WORLD_22 = 182, SDLK12_WORLD_23 = 183, SDLK12_WORLD_24 = 184, SDLK12_WORLD_25 = 185, SDLK12_WORLD_26 = 186, SDLK12_WORLD_27 = 187, SDLK12_WORLD_28 = 188, SDLK12_WORLD_29 = 189, SDLK12_WORLD_30 = 190, SDLK12_WORLD_31 = 191, SDLK12_WORLD_32 = 192, SDLK12_WORLD_33 = 193, SDLK12_WORLD_34 = 194, SDLK12_WORLD_35 = 195, SDLK12_WORLD_36 = 196, SDLK12_WORLD_37 = 197, SDLK12_WORLD_38 = 198, SDLK12_WORLD_39 = 199, SDLK12_WORLD_40 = 200, SDLK12_WORLD_41 = 201, SDLK12_WORLD_42 = 202, SDLK12_WORLD_43 = 203, SDLK12_WORLD_44 = 204, SDLK12_WORLD_45 = 205, SDLK12_WORLD_46 = 206, SDLK12_WORLD_47 = 207, SDLK12_WORLD_48 = 208, SDLK12_WORLD_49 = 209, SDLK12_WORLD_50 = 210, SDLK12_WORLD_51 = 211, SDLK12_WORLD_52 = 212, SDLK12_WORLD_53 = 213, SDLK12_WORLD_54 = 214, SDLK12_WORLD_55 = 215, SDLK12_WORLD_56 = 216, SDLK12_WORLD_57 = 217, SDLK12_WORLD_58 = 218, SDLK12_WORLD_59 = 219, SDLK12_WORLD_60 = 220, SDLK12_WORLD_61 = 221, SDLK12_WORLD_62 = 222, SDLK12_WORLD_63 = 223, SDLK12_WORLD_64 = 224, SDLK12_WORLD_65 = 225, SDLK12_WORLD_66 = 226, SDLK12_WORLD_67 = 227, SDLK12_WORLD_68 = 228, SDLK12_WORLD_69 = 229, SDLK12_WORLD_70 = 230, SDLK12_WORLD_71 = 231, SDLK12_WORLD_72 = 232, SDLK12_WORLD_73 = 233, SDLK12_WORLD_74 = 234, SDLK12_WORLD_75 = 235, SDLK12_WORLD_76 = 236, SDLK12_WORLD_77 = 237, SDLK12_WORLD_78 = 238, SDLK12_WORLD_79 = 239, SDLK12_WORLD_80 = 240, SDLK12_WORLD_81 = 241, SDLK12_WORLD_82 = 242, SDLK12_WORLD_83 = 243, SDLK12_WORLD_84 = 244, SDLK12_WORLD_85 = 245, SDLK12_WORLD_86 = 246, SDLK12_WORLD_87 = 247, SDLK12_WORLD_88 = 248, SDLK12_WORLD_89 = 249, SDLK12_WORLD_90 = 250, SDLK12_WORLD_91 = 251, SDLK12_WORLD_92 = 252, SDLK12_WORLD_93 = 253, SDLK12_WORLD_94 = 254, SDLK12_WORLD_95 = 255, /* 0xFF */ /*@}*/ /** @name Numeric keypad */ /*@{*/ SDLK12_KP0 = 256, SDLK12_KP1 = 257, SDLK12_KP2 = 258, SDLK12_KP3 = 259, SDLK12_KP4 = 260, SDLK12_KP5 = 261, SDLK12_KP6 = 262, SDLK12_KP7 = 263, SDLK12_KP8 = 264, SDLK12_KP9 = 265, SDLK12_KP_PERIOD = 266, SDLK12_KP_DIVIDE = 267, SDLK12_KP_MULTIPLY = 268, SDLK12_KP_MINUS = 269, SDLK12_KP_PLUS = 270, SDLK12_KP_ENTER = 271, SDLK12_KP_EQUALS = 272, /*@}*/ /** @name Arrows + Home/End pad */ /*@{*/ SDLK12_UP = 273, SDLK12_DOWN = 274, SDLK12_RIGHT = 275, SDLK12_LEFT = 276, SDLK12_INSERT = 277, SDLK12_HOME = 278, SDLK12_END = 279, SDLK12_PAGEUP = 280, SDLK12_PAGEDOWN = 281, /*@}*/ /** @name Function keys */ /*@{*/ SDLK12_F1 = 282, SDLK12_F2 = 283, SDLK12_F3 = 284, SDLK12_F4 = 285, SDLK12_F5 = 286, SDLK12_F6 = 287, SDLK12_F7 = 288, SDLK12_F8 = 289, SDLK12_F9 = 290, SDLK12_F10 = 291, SDLK12_F11 = 292, SDLK12_F12 = 293, SDLK12_F13 = 294, SDLK12_F14 = 295, SDLK12_F15 = 296, /*@}*/ /** @name Key state modifier keys */ /*@{*/ SDLK12_NUMLOCK = 300, SDLK12_CAPSLOCK = 301, SDLK12_SCROLLOCK = 302, SDLK12_RSHIFT = 303, SDLK12_LSHIFT = 304, SDLK12_RCTRL = 305, SDLK12_LCTRL = 306, SDLK12_RALT = 307, SDLK12_LALT = 308, SDLK12_RMETA = 309, SDLK12_LMETA = 310, SDLK12_LSUPER = 311, /**< Left "Windows" key */ SDLK12_RSUPER = 312, /**< Right "Windows" key */ SDLK12_MODE = 313, /**< "Alt Gr" key */ SDLK12_COMPOSE = 314, /**< Multi-key compose key */ /*@}*/ /** @name Miscellaneous function keys */ /*@{*/ SDLK12_HELP = 315, SDLK12_PRINT = 316, SDLK12_SYSREQ = 317, SDLK12_BREAK = 318, SDLK12_MENU = 319, SDLK12_POWER = 320, /**< Power Macintosh power key */ SDLK12_EURO = 321, /**< Some european keyboards */ SDLK12_UNDO = 322, /**< Atari keyboard has Undo */ /*@}*/ /* Add any other keys here */ SDLK12_LAST } SDL12Key; /* #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) #define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) #define KMOD_ALT (KMOD_LALT|KMOD_RALT) #define KMOD_META (KMOD_LMETA|KMOD_RMETA) */ typedef struct SDL12_keysym { uint8_t scancode; /**< hardware specific scancode */ SDL12Key sym; /**< SDL virtual keysym */ /*SDLMod*/SDL_Keymod mod; /**< current key modifiers */ uint16_t unicode; /**< translated character */ } SDL12_keysym; #define SDL_APPMOUSEFOCUS 0x01 /**< The app has mouse coverage */ #define SDL_APPINPUTFOCUS 0x02 /**< The app has input focus */ #define SDL_APPACTIVE 0x04 /**< The application is active */ /** Application visibility event structure */ typedef struct SDL12_ActiveEvent { uint8_t type; /**< SDL_ACTIVEEVENT */ uint8_t gain; /**< Whether given states were gained or lost (1/0) */ uint8_t state; /**< A mask of the focus states */ } SDL12_ActiveEvent; /** Keyboard event structure */ typedef struct SDL12_KeyboardEvent { uint8_t type; /**< SDL_KEYDOWN or SDL_KEYUP */ uint8_t which; /**< The keyboard device index */ uint8_t state; /**< SDL_PRESSED or SDL_RELEASED */ SDL12_keysym keysym; // need to include SDL.h } SDL12_KeyboardEvent; /** Mouse motion event */ typedef struct SDL12_MouseMotionEvent { uint8_t type; uint8_t which; uint8_t state; uint16_t x, y; int16_t xrel; int16_t yrel; } SDL12_MouseMotionEvent; /** Mouse button event */ typedef struct SDL12_MouseButtonEvent { uint8_t type; uint8_t which; uint8_t button; uint8_t state; uint16_t x, y; } SDL12_MouseButtonEvent; /** General event structure */ typedef union SDL12_Event { uint8_t type; SDL12_ActiveEvent active; SDL12_KeyboardEvent key; SDL12_MouseMotionEvent motion; SDL12_MouseButtonEvent button; /* SDL_JoyAxisEvent jaxis; SDL_JoyBallEvent jball; SDL_JoyHatEvent jhat; SDL_JoyButtonEvent jbutton; SDL_ResizeEvent resize; SDL_ExposeEvent expose; SDL_QuitEvent quit; SDL_UserEvent user; SDL_SysWMEvent syswm; */ } SDL12_Event; #define SDL12_ALLEVENTS 0xFFFFFFFF typedef int (*SDL12_EventFilter)(const SDL12_Event *event); #endif
0
0.8045
1
0.8045
game-dev
MEDIA
0.789104
game-dev
0.553025
1
0.553025
magefree/mage
1,434
Mage.Sets/src/mage/cards/w/WayfaringGiant.java
package mage.cards.w; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.common.DomainValue; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.hint.common.DomainHint; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.AbilityWord; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import java.util.UUID; /** * @author LoneFox */ public final class WayfaringGiant extends CardImpl { public WayfaringGiant(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{5}{W}"); this.subtype.add(SubType.GIANT); this.power = new MageInt(1); this.toughness = new MageInt(3); // Domain - Wayfaring Giant gets +1/+1 for each basic land type among lands you control. this.addAbility(new SimpleStaticAbility(new BoostSourceEffect( DomainValue.REGULAR, DomainValue.REGULAR, Duration.WhileOnBattlefield ).setText("{this} gets +1/+1 for each basic land type among lands you control.")) .addHint(DomainHint.instance).setAbilityWord(AbilityWord.DOMAIN)); } private WayfaringGiant(final WayfaringGiant card) { super(card); } @Override public WayfaringGiant copy() { return new WayfaringGiant(this); } }
0
0.920201
1
0.920201
game-dev
MEDIA
0.958263
game-dev
0.991007
1
0.991007
magefree/mage
1,374
Mage.Sets/src/mage/cards/s/StormCauldron.java
package mage.cards.s; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.common.TapForManaAllTriggeredAbility; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.abilities.effects.common.continuous.PlayAdditionalLandsAllEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SetTargetPointer; import mage.constants.Zone; import mage.filter.StaticFilters; import java.util.UUID; /** * @author Quercitron */ public final class StormCauldron extends CardImpl { public StormCauldron(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{5}"); // Each player may play an additional land during each of their turns. this.addAbility(new SimpleStaticAbility(new PlayAdditionalLandsAllEffect())); // Whenever a land is tapped for mana, return it to its owner's hand. this.addAbility(new TapForManaAllTriggeredAbility( new ReturnToHandTargetEffect().setText("return it to its owner's hand"), StaticFilters.FILTER_LAND_A, SetTargetPointer.PERMANENT )); } private StormCauldron(final StormCauldron card) { super(card); } @Override public StormCauldron copy() { return new StormCauldron(this); } }
0
0.981708
1
0.981708
game-dev
MEDIA
0.93287
game-dev
0.997178
1
0.997178
lukasmonk/lucaschess
4,123
Engines/Windows/cyrano/engine/moves.hpp
// // Cyrano Chess engine // // Copyright (C) 2007 Harald JOHNSEN // // 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, 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA // // #ifndef _MOVES_HPP_ #define _MOVES_HPP_ //#define inCheck(pcon, side) (FAttacked(pcon, pcon->argpi[side][ipiKING].isq, side ^ 1)) //#define inCheck(pcon, side) (Attacked(pcon, pcon->king[side], (side)^1)) #define foreachmove(pste,pcm) \ int iMove = 0;\ int moveCount = int( (pste+1)->mlist_start - pste->mlist_start);\ for(PCM pcm = pste->mlist_start; iMove < moveCount ; pcm++,iMove++) // Candidate move key. In the search, it is very useful to search the best // move first, so in the candidate move record, a sort key is kept. The // sort key may consist of some of these flags. #if 0 // bad captures before quiet moves #define cmkNONE 0x00100000 #define cmkBADCAPT 0x00200000 #else // bad captures at the end #define cmkBADCAPT 0x00100000 #define cmkNONE 0x00200000 #endif #define cmkQUEEN 0x00400000 #define cmkKILLER 0x01000000 #define cmkEQUCAPT 0x02000000 #define cmkGOODCAPT 0x04000000 #define cmkHASH 0x10000000 #define cmkPV 0x20000000 #define cmkQS 0x80000000 #define cmkMASK 0xfff00000 // Move and board conversion macros // #define From(m) ((m) & 63) #define To(m) ((m >> 6) & 63) #define Pc(m) ((m >> 12) & 15) #define Capt(m) ((m >> 16) & 15) #define Prom(m) ((m >> 20) & 3) #define Rank(sqr) ((sqr) >> 3) #define File(sqr) ((sqr) & 7) // Piece/engine constants // const int W = 1; const int B = 0; // Base piece/move types const int KING = 0; const int QUEEN = 2; const int ROOK = 4; const int BISHOP = 6; const int KNIGHT = 8; const int PAWN = 10; const int EP_CAPT = 12; const int CASTLE = 12; const int PROM = 14; const int PIECES = 14; extern const char pc_char_map[12]; typedef struct _attack { int attacks[128]; int mobility[PIECES]; int c_mobility; } Attack; // Indexes into the piece array enum PIECE_ARRAY { BK, WK, BQ, WQ, BR, WR, BB, WB, BN, WN, BP, WP, OCCU, X_OCCU, B_OCCU, W_OCCU, TEMP }; enum SPECIAL_MOVES { B_CASTLE = 12, W_CASTLE, B_EP = 12, W_EP, B_PROM, W_PROM, }; enum PROM_PIECE { PROM_Q, PROM_R, PROM_B, PROM_N }; enum SQUARES { A1, B1, C1, D1, E1, F1, G1, H1, A2, B2, C2, D2, E2, F2, G2, H2, A3, B3, C3, D3, E3, F3, G3, H3, A4, B4, C4, D4, E4, F4, G4, H4, A5, B5, C5, D5, E5, F5, G5, H5, A6, B6, C6, D6, E6, F6, G6, H6, A7, B7, C7, D7, E7, F7, G7, H7, A8, B8, C8, D8, E8, F8, G8, H8 }; extern void genAttacks(const CON *pcon, const STE *pste, int side, Attack *attack); extern void initMVVLVA(const CON * pcon); extern void perft(PCON pcon, int depth); int Attacked(const CON *pcon, int sqr, int col); U64 AttacksTo(const CON *pcon, int sqr); CM* bGenCaptures(PCON pcon, PSTE pste, CM * list); CM* bGenNonCaptures(PCON pcon, PSTE pste, CM * list); CM* bGenEvasions(PCON pcon, PSTE pste, CM * list = NULL); CM* bGenPasserPush(PCON pcon, PSTE pste, CM * list); CM* bGenPawnPush(PCON pcon, PSTE pste, CM * list); void bGenMoves(PCON pcon, PSTE pste); CM* bGenPseudoCheck(PCON pcon, PSTE pste, CM * list); void bMove(PCON pcon, PSTE pste, U32 move); void bUndoMove(PCON pcon, PSTE pste, U32 move); void bNullMove(PCON pcon, PSTE pste); void bUndoNullMove(PCON pcon, PSTE pste); static inline int legalMoveCount(const STE *pste) { return int( (pste+1)->mlist_start - pste->mlist_start) ; } extern void Print(const CON *pcon, const STE *pste); extern unsigned int MVV_LVA[16][16]; #endif // _MOVES_HPP_
0
0.834839
1
0.834839
game-dev
MEDIA
0.770815
game-dev
0.938348
1
0.938348
shawwn/noh
11,436
src/k2/c_skeletonemitter.h
// (C)2006 S2 Games // c_skeletonemitter.h // //============================================================================= #ifndef __C_SKELETONEMITTER_H__ #define __C_SKELETONEMITTER_H__ //============================================================================= // Headers //============================================================================= #include "i_emitter.h" #include "c_simpleparticle.h" #include "c_temporalproperty.h" #include "c_temporalpropertyrange.h" #include "c_range.h" //============================================================================= //============================================================================= // Definitions //============================================================================= //============================================================================= //============================================================================= // CSkeletonEmitterDef //============================================================================= class CSkeletonEmitterDef : public IEmitterDef { private: // Emitter Properties tstring m_sOwner; CRangei m_riLife; CRangei m_riExpireLife; CRangei m_riCount; CRangei m_riTimeNudge; CRangei m_riDelay; bool m_bLoop; CTemporalPropertyRangef m_rfSpawnRate; CTemporalPropertyRangei m_riMinParticleLife; CTemporalPropertyRangei m_riMaxParticleLife; CTemporalPropertyRangei m_riParticleTimeNudge; CTemporalPropertyRangef m_rfGravity; CTemporalPropertyRangef m_rfMinSpeed; CTemporalPropertyRangef m_rfMaxSpeed; CTemporalPropertyRangef m_rfMinAcceleration; CTemporalPropertyRangef m_rfMaxAcceleration; CTemporalPropertyRangef m_rfMinAngle; CTemporalPropertyRangef m_rfMaxAngle; CTemporalPropertyRangef m_rfMinInheritVelocity; CTemporalPropertyRangef m_rfMaxInheritVelocity; CTemporalPropertyRangef m_rfLimitInheritVelocity; ResHandle m_hMaterial; CVec3f m_v3Dir; EDirectionalSpace m_eDirectionalSpace; float m_fDrag; float m_fFriction; CVec3f m_v3Pos; CVec3f m_v3Offset; CTemporalPropertyv3 m_tv3OffsetSphere; CTemporalPropertyv3 m_tv3OffsetCube; CTemporalPropertyRangef m_rfMinOffsetDirection; CTemporalPropertyRangef m_rfMaxOffsetDirection; CTemporalPropertyRangef m_rfMinOffsetRadial; CTemporalPropertyRangef m_rfMaxOffsetRadial; CTemporalPropertyRangef m_rfMinOffsetRadialAngle; CTemporalPropertyRangef m_rfMaxOffsetRadialAngle; bool m_bCollide; EDirectionalSpace m_eParticleDirectionalSpace; CTemporalPropertyv3 m_tv3ParticleColor; CTemporalPropertyRangef m_rfParticleAlpha; CTemporalPropertyRangef m_rfParticleScale; float m_fDepthBias; public: virtual ~CSkeletonEmitterDef(); CSkeletonEmitterDef ( const tstring &sOwner, const CRangei &riLife, const CRangei &riExpireLife, const CRangei &riCount, const CRangei &riTimeNudge, const CRangei &riDelay, bool bLoop, const CTemporalPropertyRangef &rfSpawnRate, const CTemporalPropertyRangei &riMinParticleLife, const CTemporalPropertyRangei &riMaxParticleLife, const CTemporalPropertyRangei &riParticleTimeNudge, const CTemporalPropertyRangef &rfGravity, const CTemporalPropertyRangef &rfMinSpeed, const CTemporalPropertyRangef &rfMaxSpeed, const CTemporalPropertyRangef &rfMinAcceleration, const CTemporalPropertyRangef &rfMaxAcceleration, const CTemporalPropertyRangef &rfMinAngle, const CTemporalPropertyRangef &rfMaxAngle, const CTemporalPropertyRangef &rfMinInheritVelocity, const CTemporalPropertyRangef &rfMaxInheritVelocity, const CTemporalPropertyRangef &rfLimitInheritVelocity, ResHandle hMaterial, const CVec3f &v3Dir, EDirectionalSpace eDirectionalSpace, float fDrag, float fFriction, const CVec3f &v3Pos, const CVec3f &v3Offset, const CTemporalPropertyv3 &tv3OffsetSphere, const CTemporalPropertyv3 &tv3OffsetCube, const CTemporalPropertyRangef &rfMinOffsetDirection, const CTemporalPropertyRangef &rfMaxOffsetDirection, const CTemporalPropertyRangef &rfMinOffsetRadial, const CTemporalPropertyRangef &rfMaxOffsetRadial, const CTemporalPropertyRangef &rfMinOffsetRadialAngle, const CTemporalPropertyRangef &rfMaxOffsetRadialAngle, bool bCollide, EDirectionalSpace eParticleDirectionalSpace, const CTemporalPropertyv3 &tv3ParticleColor, const CTemporalPropertyRangef &m_rfParticleAlpha, const CTemporalPropertyRangef &m_rfParticleScale, float fDepthBias ); IEmitter* Spawn(uint uiStartTime, CParticleSystem *pParticleSystem, IEmitter *pOwner); const tstring& GetOwner() const { return m_sOwner; } int GetLife() const { return m_riLife; } int GetExpireLife() const { return m_riExpireLife; } int GetCount() const { return m_riCount; } int GetTimeNudge() const { return m_riTimeNudge; } int GetDelay() const { return m_riDelay; } bool GetLoop() const { return m_bLoop; } CTemporalPropertyf GetSpawnRate() const { return m_rfSpawnRate; } CTemporalPropertyi GetMinParticleLife() const { return m_riMinParticleLife; } CTemporalPropertyi GetMaxParticleLife() const { return m_riMaxParticleLife; } CTemporalPropertyi GetParticleTimeNudge() const { return m_riParticleTimeNudge; } CTemporalPropertyf GetGravity() const { return m_rfGravity; } CTemporalPropertyf GetMinSpeed() const { return m_rfMinSpeed; } CTemporalPropertyf GetMaxSpeed() const { return m_rfMaxSpeed; } CTemporalPropertyf GetMinAcceleration() const { return m_rfMinAcceleration; } CTemporalPropertyf GetMaxAcceleration() const { return m_rfMaxAcceleration; } CTemporalPropertyf GetMinAngle() const { return m_rfMinAngle; } CTemporalPropertyf GetMaxAngle() const { return m_rfMaxAngle; } CTemporalPropertyf GetMinInheritVelocity() const { return m_rfMinInheritVelocity; } CTemporalPropertyf GetMaxInheritVelocity() const { return m_rfMaxInheritVelocity; } CTemporalPropertyf GetLimitInheritVelocity() const { return m_rfLimitInheritVelocity; } ResHandle GetMaterial() const { return m_hMaterial; } const CVec3f& GetDir() const { return m_v3Dir; } EDirectionalSpace GetDirectionalSpace() const { return m_eDirectionalSpace; } float GetDrag() const { return m_fDrag; } float GetFriction() const { return m_fFriction; } const CVec3f& GetPos() const { return m_v3Pos; } const CVec3f& GetOffset() const { return m_v3Offset; } CTemporalPropertyv3 GetOffsetSphere() const { return m_tv3OffsetSphere; } CTemporalPropertyv3 GetOffsetCube() const { return m_tv3OffsetCube; } CTemporalPropertyf GetMinOffsetDirection() const { return m_rfMinOffsetDirection; } CTemporalPropertyf GetMaxOffsetDirection() const { return m_rfMaxOffsetDirection; } CTemporalPropertyf GetMinOffsetRadial() const { return m_rfMinOffsetRadial; } CTemporalPropertyf GetMaxOffsetRadial() const { return m_rfMaxOffsetRadial; } CTemporalPropertyf GetMinOffsetRadialAngle() const { return m_rfMinOffsetRadialAngle; } CTemporalPropertyf GetMaxOffsetRadialAngle() const { return m_rfMaxOffsetRadialAngle; } bool GetCollide() const { return m_bCollide; } EDirectionalSpace GetParticleDirectionalSpace() const { return m_eParticleDirectionalSpace; } const CTemporalPropertyv3& GetParticleColor() const { return m_tv3ParticleColor; } CTemporalPropertyf GetParticleAlpha() const { return m_rfParticleAlpha; } CTemporalPropertyf GetParticleScale() const { return m_rfParticleScale; } float GetDepthBias() const { return m_fDepthBias; } }; //============================================================================= // CSkeletonEmitter //============================================================================= class CSkeletonEmitter : public IEmitter { private: float m_fSelectionWeightRange; float m_fAccumulator; uint m_uiFrontSlot; uint m_uiBackSlot; ParticleList m_vParticles; int m_iSpawnCount; CVec3f m_v3LastBasePos; CVec3f m_v3LastBaseVelocity; CVec3f m_v3LastEmitterPos; float m_fLastLerp; float m_fLastTime; bool m_bLastActive; // Emitter Properties int m_iCount; CTemporalPropertyf m_rfSpawnRate; CTemporalPropertyi m_riMinParticleLife; CTemporalPropertyi m_riMaxParticleLife; CTemporalPropertyi m_riParticleTimeNudge; CTemporalPropertyf m_rfGravity; CTemporalPropertyf m_rfMinSpeed; CTemporalPropertyf m_rfMaxSpeed; CTemporalPropertyf m_rfMinAcceleration; CTemporalPropertyf m_rfMaxAcceleration; CTemporalPropertyf m_rfMinAngle; CTemporalPropertyf m_rfMaxAngle; CTemporalPropertyf m_rfMinInheritVelocity; CTemporalPropertyf m_rfMaxInheritVelocity; CTemporalPropertyf m_rfLimitInheritVelocity; CTemporalPropertyf m_rfMinOffsetDirection; CTemporalPropertyf m_rfMaxOffsetDirection; CTemporalPropertyf m_rfMinOffsetRadial; CTemporalPropertyf m_rfMaxOffsetRadial; CTemporalPropertyf m_rfMinOffsetRadialAngle; CTemporalPropertyf m_rfMaxOffsetRadialAngle; ResHandle m_hMaterial; CVec3f m_v3Dir; float m_fDrag; float m_fFriction; CTemporalPropertyv3 m_tv3OffsetSphere; CTemporalPropertyv3 m_tv3OffsetCube; bool m_bCollide; EDirectionalSpace m_eParticleDirectionalSpace; CTemporalPropertyv3 m_tv3ParticleColor; CTemporalPropertyf m_tfParticleAlpha; CTemporalPropertyf m_tfParticleScale; float m_fDepthBias; public: virtual ~CSkeletonEmitter(); CSkeletonEmitter(uint uiStartTime, CParticleSystem *pParticleSystem, IEmitter *pOwner, const CSkeletonEmitterDef &eSettings); virtual void ResumeFromPause(uint uiMilliseconds); bool Update(uint uiMilliseconds, ParticleTraceFn_t pfnTrace); uint GetNumBillboards(); bool GetBillboard(uint uiIndex, SBillboard &outBillboard); }; //============================================================================= #endif //__C_SIMPLEEMITTER_H__
0
0.61735
1
0.61735
game-dev
MEDIA
0.257425
game-dev
0.545319
1
0.545319
emileb/OpenGames
55,262
opengames/src/main/jni/Doom/gzdoom_2/src/po_man.cpp
//************************************************************************** //** //** PO_MAN.C : Heretic 2 : Raven Software, Corp. //** //** $RCSfile: po_man.c,v $ //** $Revision: 1.22 $ //** $Date: 95/09/28 18:20:56 $ //** $Author: cjr $ //** //************************************************************************** // HEADER FILES ------------------------------------------------------------ #include "doomdef.h" #include "p_local.h" #include "i_system.h" #include "w_wad.h" #include "m_swap.h" #include "m_bbox.h" #include "tables.h" #include "s_sndseq.h" #include "a_sharedglobal.h" #include "p_3dmidtex.h" #include "p_lnspec.h" #include "r_data/r_interpolate.h" #include "g_level.h" #include "po_man.h" #include "p_setup.h" #include "vectors.h" #include "farchive.h" // MACROS ------------------------------------------------------------------ #define PO_MAXPOLYSEGS 64 // TYPES ------------------------------------------------------------------- inline vertex_t *side_t::V1() const { return this == linedef->sidedef[0]? linedef->v1 : linedef->v2; } inline vertex_t *side_t::V2() const { return this == linedef->sidedef[0]? linedef->v2 : linedef->v1; } FArchive &operator<< (FArchive &arc, FPolyObj *&poly) { return arc.SerializePointer (polyobjs, (BYTE **)&poly, sizeof(FPolyObj)); } FArchive &operator<< (FArchive &arc, const FPolyObj *&poly) { return arc.SerializePointer (polyobjs, (BYTE **)&poly, sizeof(FPolyObj)); } inline FArchive &operator<< (FArchive &arc, podoortype_t &type) { BYTE val = (BYTE)type; arc << val; type = (podoortype_t)val; return arc; } class DPolyAction : public DThinker { DECLARE_CLASS (DPolyAction, DThinker) HAS_OBJECT_POINTERS public: DPolyAction (int polyNum); void Serialize (FArchive &arc); void Destroy(); void Stop(); int GetSpeed() const { return m_Speed; } void StopInterpolation (); protected: DPolyAction (); int m_PolyObj; int m_Speed; int m_Dist; TObjPtr<DInterpolation> m_Interpolation; void SetInterpolation (); }; class DRotatePoly : public DPolyAction { DECLARE_CLASS (DRotatePoly, DPolyAction) public: DRotatePoly (int polyNum); void Tick (); private: DRotatePoly (); friend bool EV_RotatePoly (line_t *line, int polyNum, int speed, int byteAngle, int direction, bool overRide); }; class DMovePoly : public DPolyAction { DECLARE_CLASS (DMovePoly, DPolyAction) public: DMovePoly (int polyNum); void Serialize (FArchive &arc); void Tick (); protected: DMovePoly (); int m_Angle; fixed_t m_xSpeed; // for sliding walls fixed_t m_ySpeed; friend bool EV_MovePoly (line_t *line, int polyNum, int speed, angle_t angle, fixed_t dist, bool overRide); }; class DMovePolyTo : public DPolyAction { DECLARE_CLASS(DMovePolyTo, DPolyAction) public: DMovePolyTo(int polyNum); void Serialize(FArchive &arc); void Tick(); protected: DMovePolyTo(); fixed_t m_xSpeed; fixed_t m_ySpeed; fixed_t m_xTarget; fixed_t m_yTarget; friend bool EV_MovePolyTo(line_t *line, int polyNum, int speed, fixed_t x, fixed_t y, bool overRide); }; class DPolyDoor : public DMovePoly { DECLARE_CLASS (DPolyDoor, DMovePoly) public: DPolyDoor (int polyNum, podoortype_t type); void Serialize (FArchive &arc); void Tick (); protected: int m_Direction; int m_TotalDist; int m_Tics; int m_WaitTics; podoortype_t m_Type; bool m_Close; friend bool EV_OpenPolyDoor (line_t *line, int polyNum, int speed, angle_t angle, int delay, int distance, podoortype_t type); private: DPolyDoor (); }; class FPolyMirrorIterator { FPolyObj *CurPoly; int UsedPolys[100]; // tracks mirrored polyobjects we've seen int NumUsedPolys; public: FPolyMirrorIterator(FPolyObj *poly); FPolyObj *NextMirror(); }; // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- void PO_Init (void); // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- static void RotatePt (int an, fixed_t *x, fixed_t *y, fixed_t startSpotX, fixed_t startSpotY); static void UnLinkPolyobj (FPolyObj *po); static void LinkPolyobj (FPolyObj *po); static bool CheckMobjBlocking (side_t *seg, FPolyObj *po); static void InitBlockMap (void); static void IterFindPolySides (FPolyObj *po, side_t *side); static void SpawnPolyobj (int index, int tag, int type); static void TranslateToStartSpot (int tag, int originX, int originY); static void DoMovePolyobj (FPolyObj *po, int x, int y); static void InitSegLists (); static void KillSegLists (); static FPolyNode *NewPolyNode(); static void FreePolyNode(); static void ReleaseAllPolyNodes(); // EXTERNAL DATA DECLARATIONS ---------------------------------------------- extern seg_t *segs; // PUBLIC DATA DEFINITIONS ------------------------------------------------- polyblock_t **PolyBlockMap; FPolyObj *polyobjs; // list of all poly-objects on the level int po_NumPolyobjs; polyspawns_t *polyspawns; // [RH] Let P_SpawnMapThings() find our thingies for us // PRIVATE DATA DEFINITIONS ------------------------------------------------ static TArray<SDWORD> KnownPolySides; static FPolyNode *FreePolyNodes; // CODE -------------------------------------------------------------------- //========================================================================== // // // //========================================================================== IMPLEMENT_POINTY_CLASS (DPolyAction) DECLARE_POINTER(m_Interpolation) END_POINTERS DPolyAction::DPolyAction () { } void DPolyAction::Serialize (FArchive &arc) { Super::Serialize (arc); arc << m_PolyObj << m_Speed << m_Dist << m_Interpolation; } DPolyAction::DPolyAction (int polyNum) { m_PolyObj = polyNum; m_Speed = 0; m_Dist = 0; SetInterpolation (); } void DPolyAction::Destroy() { FPolyObj *poly = PO_GetPolyobj (m_PolyObj); if (poly->specialdata == this) { poly->specialdata = NULL; } StopInterpolation(); Super::Destroy(); } void DPolyAction::Stop() { FPolyObj *poly = PO_GetPolyobj(m_PolyObj); SN_StopSequence(poly); Destroy(); } void DPolyAction::SetInterpolation () { FPolyObj *poly = PO_GetPolyobj (m_PolyObj); m_Interpolation = poly->SetInterpolation(); } void DPolyAction::StopInterpolation () { if (m_Interpolation != NULL) { m_Interpolation->DelRef(); m_Interpolation = NULL; } } //========================================================================== // // // //========================================================================== IMPLEMENT_CLASS (DRotatePoly) DRotatePoly::DRotatePoly () { } DRotatePoly::DRotatePoly (int polyNum) : Super (polyNum) { } //========================================================================== // // // //========================================================================== IMPLEMENT_CLASS (DMovePoly) DMovePoly::DMovePoly () { } void DMovePoly::Serialize (FArchive &arc) { Super::Serialize (arc); arc << m_Angle << m_xSpeed << m_ySpeed; } DMovePoly::DMovePoly (int polyNum) : Super (polyNum) { m_Angle = 0; m_xSpeed = 0; m_ySpeed = 0; } //========================================================================== // // // // //========================================================================== IMPLEMENT_CLASS(DMovePolyTo) DMovePolyTo::DMovePolyTo() { } void DMovePolyTo::Serialize(FArchive &arc) { Super::Serialize(arc); arc << m_xSpeed << m_ySpeed << m_xTarget << m_yTarget; } DMovePolyTo::DMovePolyTo(int polyNum) : Super(polyNum) { m_xSpeed = 0; m_ySpeed = 0; m_xTarget = 0; m_yTarget = 0; } //========================================================================== // // // //========================================================================== IMPLEMENT_CLASS (DPolyDoor) DPolyDoor::DPolyDoor () { } void DPolyDoor::Serialize (FArchive &arc) { Super::Serialize (arc); arc << m_Direction << m_TotalDist << m_Tics << m_WaitTics << m_Type << m_Close; } DPolyDoor::DPolyDoor (int polyNum, podoortype_t type) : Super (polyNum), m_Type (type) { m_Direction = 0; m_TotalDist = 0; m_Tics = 0; m_WaitTics = 0; m_Close = false; } // ===== Polyobj Event Code ===== //========================================================================== // // T_RotatePoly // //========================================================================== void DRotatePoly::Tick () { FPolyObj *poly = PO_GetPolyobj (m_PolyObj); if (poly == NULL) return; // Don't let non-perpetual polyobjs overshoot their targets. if (m_Dist != -1 && (unsigned int)m_Dist < (unsigned int)abs(m_Speed)) { m_Speed = m_Speed < 0 ? -m_Dist : m_Dist; } if (poly->RotatePolyobj (m_Speed)) { if (m_Dist == -1) { // perpetual polyobj return; } m_Dist -= abs(m_Speed); if (m_Dist == 0) { SN_StopSequence (poly); Destroy (); } } } //========================================================================== // // EV_RotatePoly // //========================================================================== bool EV_RotatePoly (line_t *line, int polyNum, int speed, int byteAngle, int direction, bool overRide) { DRotatePoly *pe = NULL; FPolyObj *poly; if ((poly = PO_GetPolyobj(polyNum)) == NULL) { Printf("EV_RotatePoly: Invalid polyobj num: %d\n", polyNum); return false; } FPolyMirrorIterator it(poly); while ((poly = it.NextMirror()) != NULL) { if (poly->specialdata != NULL && !overRide) { // poly is already in motion break; } pe = new DRotatePoly(poly->tag); poly->specialdata = pe; if (byteAngle != 0) { if (byteAngle == 255) { pe->m_Dist = ~0; } else { pe->m_Dist = byteAngle*(ANGLE_90/64); // Angle } } else { pe->m_Dist = ANGLE_MAX-1; } pe->m_Speed = speed*direction*(ANGLE_90/(64<<3)); SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); direction = -direction; // Reverse the direction } return pe != NULL; // Return true if something started moving. } //========================================================================== // // T_MovePoly // //========================================================================== void DMovePoly::Tick () { FPolyObj *poly = PO_GetPolyobj (m_PolyObj); if (poly != NULL) { if (poly->MovePolyobj (m_xSpeed, m_ySpeed)) { int absSpeed = abs (m_Speed); m_Dist -= absSpeed; if (m_Dist <= 0) { SN_StopSequence (poly); Destroy (); } else if (m_Dist < absSpeed) { m_Speed = m_Dist * (m_Speed < 0 ? -1 : 1); m_xSpeed = FixedMul (m_Speed, finecosine[m_Angle]); m_ySpeed = FixedMul (m_Speed, finesine[m_Angle]); } } } } //========================================================================== // // EV_MovePoly // //========================================================================== bool EV_MovePoly (line_t *line, int polyNum, int speed, angle_t angle, fixed_t dist, bool overRide) { DMovePoly *pe = NULL; FPolyObj *poly; angle_t an = angle; if ((poly = PO_GetPolyobj(polyNum)) == NULL) { Printf("EV_MovePoly: Invalid polyobj num: %d\n", polyNum); return false; } FPolyMirrorIterator it(poly); while ((poly = it.NextMirror()) != NULL) { if (poly->specialdata != NULL && !overRide) { // poly is already in motion break; } pe = new DMovePoly(poly->tag); poly->specialdata = pe; pe->m_Dist = dist; // Distance pe->m_Speed = speed; pe->m_Angle = an >> ANGLETOFINESHIFT; pe->m_xSpeed = FixedMul (pe->m_Speed, finecosine[pe->m_Angle]); pe->m_ySpeed = FixedMul (pe->m_Speed, finesine[pe->m_Angle]); SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); // Do not interpolate very fast moving polyobjects. The minimum tic count is // 3 instead of 2, because the moving crate effect in Massmouth 2, Hostitality // that this fixes isn't quite fast enough to move the crate back to its start // in just 1 tic. if (dist/speed <= 2) { pe->StopInterpolation (); } an = an + ANGLE_180; // Reverse the angle. } return pe != NULL; // Return true if something started moving. } //========================================================================== // // DMovePolyTo :: Tick // //========================================================================== void DMovePolyTo::Tick () { FPolyObj *poly = PO_GetPolyobj (m_PolyObj); if (poly != NULL) { if (poly->MovePolyobj (m_xSpeed, m_ySpeed)) { int absSpeed = abs (m_Speed); m_Dist -= absSpeed; if (m_Dist <= 0) { SN_StopSequence (poly); Destroy (); } else if (m_Dist < absSpeed) { m_Speed = m_Dist * (m_Speed < 0 ? -1 : 1); m_xSpeed = m_xTarget - poly->StartSpot.x; m_ySpeed = m_yTarget - poly->StartSpot.y; } } } } //========================================================================== // // EV_MovePolyTo // //========================================================================== bool EV_MovePolyTo(line_t *line, int polyNum, int speed, fixed_t targx, fixed_t targy, bool overRide) { DMovePolyTo *pe = NULL; FPolyObj *poly; TVector2<double> dist; double distlen; if ((poly = PO_GetPolyobj(polyNum)) == NULL) { Printf("EV_MovePolyTo: Invalid polyobj num: %d\n", polyNum); return false; } FPolyMirrorIterator it(poly); dist.X = targx - poly->StartSpot.x; dist.Y = targy - poly->StartSpot.y; distlen = dist.MakeUnit(); while ((poly = it.NextMirror()) != NULL) { if (poly->specialdata != NULL && !overRide) { // poly is already in motion break; } pe = new DMovePolyTo(poly->tag); poly->specialdata = pe; pe->m_Dist = xs_RoundToInt(distlen); pe->m_Speed = speed; pe->m_xSpeed = xs_RoundToInt(speed * dist.X); pe->m_ySpeed = xs_RoundToInt(speed * dist.Y); pe->m_xTarget = xs_RoundToInt(poly->StartSpot.x + distlen * dist.X); pe->m_yTarget = xs_RoundToInt(poly->StartSpot.y + distlen * dist.Y); if ((pe->m_Dist / pe->m_Speed) <= 2) { pe->StopInterpolation(); } dist = -dist; // reverse the direction } return pe != NULL; // Return true if something started moving. } //========================================================================== // // T_PolyDoor // //========================================================================== void DPolyDoor::Tick () { int absSpeed; FPolyObj *poly = PO_GetPolyobj (m_PolyObj); if (poly == NULL) return; if (m_Tics) { if (!--m_Tics) { SN_StartSequence (poly, poly->seqType, SEQ_DOOR, m_Close); } return; } switch (m_Type) { case PODOOR_SLIDE: if (m_Dist <= 0 || poly->MovePolyobj (m_xSpeed, m_ySpeed)) { absSpeed = abs (m_Speed); m_Dist -= absSpeed; if (m_Dist <= 0) { SN_StopSequence (poly); if (!m_Close) { m_Dist = m_TotalDist; m_Close = true; m_Tics = m_WaitTics; m_Direction = (ANGLE_MAX>>ANGLETOFINESHIFT) - m_Direction; m_xSpeed = -m_xSpeed; m_ySpeed = -m_ySpeed; } else { Destroy (); } } } else { if (poly->crush || !m_Close) { // continue moving if the poly is a crusher, or is opening return; } else { // open back up m_Dist = m_TotalDist - m_Dist; m_Direction = (ANGLE_MAX>>ANGLETOFINESHIFT)- m_Direction; m_xSpeed = -m_xSpeed; m_ySpeed = -m_ySpeed; m_Close = false; SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); } } break; case PODOOR_SWING: if (poly->RotatePolyobj (m_Speed)) { absSpeed = abs (m_Speed); if (m_Dist == -1) { // perpetual polyobj return; } m_Dist -= absSpeed; if (m_Dist <= 0) { SN_StopSequence (poly); if (!m_Close) { m_Dist = m_TotalDist; m_Close = true; m_Tics = m_WaitTics; m_Speed = -m_Speed; } else { Destroy (); } } } else { if(poly->crush || !m_Close) { // continue moving if the poly is a crusher, or is opening return; } else { // open back up and rewait m_Dist = m_TotalDist - m_Dist; m_Speed = -m_Speed; m_Close = false; SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); } } break; default: break; } } //========================================================================== // // EV_OpenPolyDoor // //========================================================================== bool EV_OpenPolyDoor (line_t *line, int polyNum, int speed, angle_t angle, int delay, int distance, podoortype_t type) { DPolyDoor *pd = NULL; FPolyObj *poly; int swingdir = 1; // ADD: PODOOR_SWINGL, PODOOR_SWINGR if ((poly = PO_GetPolyobj(polyNum)) == NULL) { Printf("EV_OpenPolyDoor: Invalid polyobj num: %d\n", polyNum); return false; } FPolyMirrorIterator it(poly); while ((poly = it.NextMirror()) != NULL) { if (poly->specialdata != NULL) { // poly is already moving break; } pd = new DPolyDoor(poly->tag, type); poly->specialdata = pd; if (type == PODOOR_SLIDE) { pd->m_WaitTics = delay; pd->m_Speed = speed; pd->m_Dist = pd->m_TotalDist = distance; // Distance pd->m_Direction = angle >> ANGLETOFINESHIFT; pd->m_xSpeed = FixedMul (pd->m_Speed, finecosine[pd->m_Direction]); pd->m_ySpeed = FixedMul (pd->m_Speed, finesine[pd->m_Direction]); SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); angle += ANGLE_180; // reverse the angle } else if (type == PODOOR_SWING) { pd->m_WaitTics = delay; pd->m_Direction = swingdir; pd->m_Speed = (speed*pd->m_Direction*(ANGLE_90/64))>>3; pd->m_Dist = pd->m_TotalDist = angle; SN_StartSequence (poly, poly->seqType, SEQ_DOOR, 0); swingdir = -swingdir; // reverse the direction } } return pd != NULL; // Return true if something started moving. } //========================================================================== // // EV_StopPoly // //========================================================================== bool EV_StopPoly(int polynum) { FPolyObj *poly; if (NULL != (poly = PO_GetPolyobj(polynum))) { if (poly->specialdata != NULL) { poly->specialdata->Stop(); } return true; } return false; } // ===== Higher Level Poly Interface code ===== //========================================================================== // // PO_GetPolyobj // //========================================================================== FPolyObj *PO_GetPolyobj (int polyNum) { int i; for (i = 0; i < po_NumPolyobjs; i++) { if (polyobjs[i].tag == polyNum) { return &polyobjs[i]; } } return NULL; } //========================================================================== // // // //========================================================================== FPolyObj::FPolyObj() { StartSpot.x = StartSpot.y = 0; angle = 0; tag = 0; memset(bbox, 0, sizeof(bbox)); validcount = 0; crush = 0; bHurtOnTouch = false; seqType = 0; size = 0; subsectorlinks = NULL; specialdata = NULL; interpolation = NULL; } //========================================================================== // // GetPolyobjMirror // //========================================================================== int FPolyObj::GetMirror() { return MirrorNum; } //========================================================================== // // ThrustMobj // //========================================================================== void FPolyObj::ThrustMobj (AActor *actor, side_t *side) { int thrustAngle; int thrustX; int thrustY; DPolyAction *pe; int force; if (!(actor->flags&MF_SHOOTABLE) && !actor->player) { return; } vertex_t *v1 = side->V1(); vertex_t *v2 = side->V2(); thrustAngle = (R_PointToAngle2 (v1->x, v1->y, v2->x, v2->y) - ANGLE_90) >> ANGLETOFINESHIFT; pe = static_cast<DPolyAction *>(specialdata); if (pe) { if (pe->IsKindOf (RUNTIME_CLASS (DRotatePoly))) { force = pe->GetSpeed() >> 8; } else { force = pe->GetSpeed() >> 3; } if (force < FRACUNIT) { force = FRACUNIT; } else if (force > 4*FRACUNIT) { force = 4*FRACUNIT; } } else { force = FRACUNIT; } thrustX = FixedMul (force, finecosine[thrustAngle]); thrustY = FixedMul (force, finesine[thrustAngle]); actor->velx += thrustX; actor->vely += thrustY; if (crush) { if (bHurtOnTouch || !P_CheckMove (actor, actor->x + thrustX, actor->y + thrustY)) { int newdam = P_DamageMobj (actor, NULL, NULL, crush, NAME_Crush); P_TraceBleed (newdam > 0 ? newdam : crush, actor); } } if (level.flags2 & LEVEL2_POLYGRIND) actor->Grind(false); // crush corpses that get caught in a polyobject's way } //========================================================================== // // UpdateSegBBox // //========================================================================== void FPolyObj::UpdateBBox () { for(unsigned i=0;i<Linedefs.Size(); i++) { line_t *line = Linedefs[i]; if (line->v1->x < line->v2->x) { line->bbox[BOXLEFT] = line->v1->x; line->bbox[BOXRIGHT] = line->v2->x; } else { line->bbox[BOXLEFT] = line->v2->x; line->bbox[BOXRIGHT] = line->v1->x; } if (line->v1->y < line->v2->y) { line->bbox[BOXBOTTOM] = line->v1->y; line->bbox[BOXTOP] = line->v2->y; } else { line->bbox[BOXBOTTOM] = line->v2->y; line->bbox[BOXTOP] = line->v1->y; } // Update the line's slopetype line->dx = line->v2->x - line->v1->x; line->dy = line->v2->y - line->v1->y; } CalcCenter(); } void FPolyObj::CalcCenter() { SQWORD cx = 0, cy = 0; for(unsigned i=0;i<Vertices.Size(); i++) { cx += Vertices[i]->x; cy += Vertices[i]->y; } CenterSpot.x = (fixed_t)(cx / Vertices.Size()); CenterSpot.y = (fixed_t)(cy / Vertices.Size()); } //========================================================================== // // PO_MovePolyobj // //========================================================================== bool FPolyObj::MovePolyobj (int x, int y, bool force) { FBoundingBox oldbounds = Bounds; UnLinkPolyobj (); DoMovePolyobj (x, y); if (!force) { bool blocked = false; for(unsigned i=0;i < Sidedefs.Size(); i++) { if (CheckMobjBlocking(Sidedefs[i])) { blocked = true; } } if (blocked) { DoMovePolyobj (-x, -y); LinkPolyobj(); return false; } } StartSpot.x += x; StartSpot.y += y; CenterSpot.x += x; CenterSpot.y += y; LinkPolyobj (); ClearSubsectorLinks(); RecalcActorFloorCeil(Bounds | oldbounds); return true; } //========================================================================== // // DoMovePolyobj // //========================================================================== void FPolyObj::DoMovePolyobj (int x, int y) { for(unsigned i=0;i < Vertices.Size(); i++) { Vertices[i]->x += x; Vertices[i]->y += y; PrevPts[i].x += x; PrevPts[i].y += y; } for (unsigned i = 0; i < Linedefs.Size(); i++) { Linedefs[i]->bbox[BOXTOP] += y; Linedefs[i]->bbox[BOXBOTTOM] += y; Linedefs[i]->bbox[BOXLEFT] += x; Linedefs[i]->bbox[BOXRIGHT] += x; } } //========================================================================== // // RotatePt // //========================================================================== static void RotatePt (int an, fixed_t *x, fixed_t *y, fixed_t startSpotX, fixed_t startSpotY) { fixed_t tr_x = *x; fixed_t tr_y = *y; *x = (DMulScale16 (tr_x, finecosine[an], -tr_y, finesine[an]) & 0xFFFFFE00) + startSpotX; *y = (DMulScale16 (tr_x, finesine[an], tr_y, finecosine[an]) & 0xFFFFFE00) + startSpotY; } //========================================================================== // // PO_RotatePolyobj // //========================================================================== bool FPolyObj::RotatePolyobj (angle_t angle, bool fromsave) { int an; bool blocked; FBoundingBox oldbounds = Bounds; an = (this->angle+angle)>>ANGLETOFINESHIFT; UnLinkPolyobj(); for(unsigned i=0;i < Vertices.Size(); i++) { PrevPts[i].x = Vertices[i]->x; PrevPts[i].y = Vertices[i]->y; Vertices[i]->x = OriginalPts[i].x; Vertices[i]->y = OriginalPts[i].y; RotatePt(an, &Vertices[i]->x, &Vertices[i]->y, StartSpot.x, StartSpot.y); } blocked = false; validcount++; UpdateBBox(); // If we are loading a savegame we do not really want to damage actors and be blocked by them. This can also cause crashes when trying to damage incompletely deserialized player pawns. if (!fromsave) { for (unsigned i = 0; i < Sidedefs.Size(); i++) { if (CheckMobjBlocking(Sidedefs[i])) { blocked = true; } } if (blocked) { for(unsigned i=0;i < Vertices.Size(); i++) { Vertices[i]->x = PrevPts[i].x; Vertices[i]->y = PrevPts[i].y; } UpdateBBox(); LinkPolyobj(); return false; } } this->angle += angle; LinkPolyobj(); ClearSubsectorLinks(); RecalcActorFloorCeil(Bounds | oldbounds); return true; } //========================================================================== // // UnLinkPolyobj // //========================================================================== void FPolyObj::UnLinkPolyobj () { polyblock_t *link; int i, j; int index; // remove the polyobj from each blockmap section for(j = bbox[BOXBOTTOM]; j <= bbox[BOXTOP]; j++) { index = j*bmapwidth; for(i = bbox[BOXLEFT]; i <= bbox[BOXRIGHT]; i++) { if(i >= 0 && i < bmapwidth && j >= 0 && j < bmapheight) { link = PolyBlockMap[index+i]; while(link != NULL && link->polyobj != this) { link = link->next; } if(link == NULL) { // polyobj not located in the link cell continue; } link->polyobj = NULL; } } } } //========================================================================== // // CheckMobjBlocking // //========================================================================== bool FPolyObj::CheckMobjBlocking (side_t *sd) { static TArray<AActor *> checker; FBlockNode *block; AActor *mobj; int i, j, k; int left, right, top, bottom; line_t *ld; bool blocked; bool performBlockingThrust; ld = sd->linedef; top = GetSafeBlockY(ld->bbox[BOXTOP]-bmaporgy); bottom = GetSafeBlockY(ld->bbox[BOXBOTTOM]-bmaporgy); left = GetSafeBlockX(ld->bbox[BOXLEFT]-bmaporgx); right = GetSafeBlockX(ld->bbox[BOXRIGHT]-bmaporgx); blocked = false; checker.Clear(); bottom = bottom < 0 ? 0 : bottom; bottom = bottom >= bmapheight ? bmapheight-1 : bottom; top = top < 0 ? 0 : top; top = top >= bmapheight ? bmapheight-1 : top; left = left < 0 ? 0 : left; left = left >= bmapwidth ? bmapwidth-1 : left; right = right < 0 ? 0 : right; right = right >= bmapwidth ? bmapwidth-1 : right; for (j = bottom*bmapwidth; j <= top*bmapwidth; j += bmapwidth) { for (i = left; i <= right; i++) { for (block = blocklinks[j+i]; block != NULL; block = block->NextActor) { mobj = block->Me; for (k = (int)checker.Size()-1; k >= 0; --k) { if (checker[k] == mobj) { break; } } if (k < 0) { checker.Push (mobj); if ((mobj->flags&MF_SOLID) && !(mobj->flags&MF_NOCLIP)) { FLineOpening open; open.top = INT_MAX; open.bottom = -INT_MAX; // [TN] Check wether this actor gets blocked by the line. if (ld->backsector != NULL && !(ld->flags & (ML_BLOCKING|ML_BLOCKEVERYTHING)) && !(ld->flags & ML_BLOCK_PLAYERS && mobj->player) && !(ld->flags & ML_BLOCKMONSTERS && mobj->flags3 & MF3_ISMONSTER) && !((mobj->flags & MF_FLOAT) && (ld->flags & ML_BLOCK_FLOATERS)) && (!(ld->flags & ML_3DMIDTEX) || (!P_LineOpening_3dMidtex(mobj, ld, open) && (mobj->z + mobj->height < open.top) ) || (open.abovemidtex && mobj->z > mobj->floorz)) ) { // [BL] We can't just continue here since we must // determine if the line's backsector is going to // be blocked. performBlockingThrust = false; } else { performBlockingThrust = true; } FBoundingBox box(mobj->x, mobj->y, mobj->radius); if (box.Right() <= ld->bbox[BOXLEFT] || box.Left() >= ld->bbox[BOXRIGHT] || box.Top() <= ld->bbox[BOXBOTTOM] || box.Bottom() >= ld->bbox[BOXTOP]) { continue; } if (box.BoxOnLineSide(ld) != -1) { continue; } // We have a two-sided linedef so we should only check one side // so that the thrust from both sides doesn't cancel each other out. // Best use the one facing the player and ignore the back side. if (ld->sidedef[1] != NULL) { int side = P_PointOnLineSide(mobj->x, mobj->y, ld); if (ld->sidedef[side] != sd) { continue; } // [BL] See if we hit below the floor/ceiling of the poly. else if(!performBlockingThrust && ( mobj->z < ld->sidedef[!side]->sector->GetSecPlane(sector_t::floor).ZatPoint(mobj->x, mobj->y) || mobj->z + mobj->height > ld->sidedef[!side]->sector->GetSecPlane(sector_t::ceiling).ZatPoint(mobj->x, mobj->y) )) { performBlockingThrust = true; } } if(performBlockingThrust) { ThrustMobj (mobj, sd); blocked = true; } else continue; } } } } } return blocked; } //========================================================================== // // LinkPolyobj // //========================================================================== void FPolyObj::LinkPolyobj () { polyblock_t **link; polyblock_t *tempLink; // calculate the polyobj bbox Bounds.ClearBox(); for(unsigned i = 0; i < Sidedefs.Size(); i++) { vertex_t *vt; vt = Sidedefs[i]->linedef->v1; Bounds.AddToBox(vt->x, vt->y); vt = Sidedefs[i]->linedef->v2; Bounds.AddToBox(vt->x, vt->y); } bbox[BOXRIGHT] = GetSafeBlockX(Bounds.Right() - bmaporgx); bbox[BOXLEFT] = GetSafeBlockX(Bounds.Left() - bmaporgx); bbox[BOXTOP] = GetSafeBlockY(Bounds.Top() - bmaporgy); bbox[BOXBOTTOM] = GetSafeBlockY(Bounds.Bottom() - bmaporgy); // add the polyobj to each blockmap section for(int j = bbox[BOXBOTTOM]*bmapwidth; j <= bbox[BOXTOP]*bmapwidth; j += bmapwidth) { for(int i = bbox[BOXLEFT]; i <= bbox[BOXRIGHT]; i++) { if(i >= 0 && i < bmapwidth && j >= 0 && j < bmapheight*bmapwidth) { link = &PolyBlockMap[j+i]; if(!(*link)) { // Create a new link at the current block cell *link = new polyblock_t; (*link)->next = NULL; (*link)->prev = NULL; (*link)->polyobj = this; continue; } else { tempLink = *link; while(tempLink->next != NULL && tempLink->polyobj != NULL) { tempLink = tempLink->next; } } if(tempLink->polyobj == NULL) { tempLink->polyobj = this; continue; } else { tempLink->next = new polyblock_t; tempLink->next->next = NULL; tempLink->next->prev = tempLink; tempLink->next->polyobj = this; } } // else, don't link the polyobj, since it's off the map } } } //=========================================================================== // // FPolyObj :: RecalcActorFloorCeil // // For each actor within the bounding box, recalculate its floorz, ceilingz, // and related values. // //=========================================================================== void FPolyObj::RecalcActorFloorCeil(FBoundingBox bounds) const { FBlockThingsIterator it(bounds); AActor *actor; while ((actor = it.Next()) != NULL) { P_FindFloorCeiling(actor); } } //=========================================================================== // // PO_ClosestPoint // // Given a point (x,y), returns the point (ox,oy) on the polyobject's walls // that is nearest to (x,y). Also returns the seg this point came from. // //=========================================================================== void FPolyObj::ClosestPoint(fixed_t fx, fixed_t fy, fixed_t &ox, fixed_t &oy, side_t **side) const { unsigned int i; double x = fx, y = fy; double bestdist = HUGE_VAL; double bestx = 0, besty = 0; side_t *bestline = NULL; for (i = 0; i < Sidedefs.Size(); ++i) { vertex_t *v1 = Sidedefs[i]->V1(); vertex_t *v2 = Sidedefs[i]->V2(); double a = v2->x - v1->x; double b = v2->y - v1->y; double den = a*a + b*b; double ix, iy, dist; if (den == 0) { // Line is actually a point! ix = v1->x; iy = v1->y; } else { double num = (x - v1->x) * a + (y - v1->y) * b; double u = num / den; if (u <= 0) { ix = v1->x; iy = v1->y; } else if (u >= 1) { ix = v2->x; iy = v2->y; } else { ix = v1->x + u * a; iy = v1->y + u * b; } } a = (ix - x); b = (iy - y); dist = a*a + b*b; if (dist < bestdist) { bestdist = dist; bestx = ix; besty = iy; bestline = Sidedefs[i]; } } ox = fixed_t(bestx); oy = fixed_t(besty); if (side != NULL) { *side = bestline; } } //========================================================================== // // InitBlockMap // //========================================================================== static void InitBlockMap (void) { int i; PolyBlockMap = new polyblock_t *[bmapwidth*bmapheight]; memset (PolyBlockMap, 0, bmapwidth*bmapheight*sizeof(polyblock_t *)); for (i = 0; i < po_NumPolyobjs; i++) { polyobjs[i].LinkPolyobj(); } } //========================================================================== // // InitSideLists [RH] // // Group sides by vertex and collect side that are known to belong to a // polyobject so that they can be initialized fast. //========================================================================== static void InitSideLists () { for (int i = 0; i < numsides; ++i) { if (sides[i].linedef != NULL && (sides[i].linedef->special == Polyobj_StartLine || sides[i].linedef->special == Polyobj_ExplicitLine)) { KnownPolySides.Push (i); } } } //========================================================================== // // KillSideLists [RH] // //========================================================================== static void KillSideLists () { KnownPolySides.Clear (); KnownPolySides.ShrinkToFit (); } //========================================================================== // // AddPolyVert // // Helper function for IterFindPolySides() // //========================================================================== static void AddPolyVert(TArray<DWORD> &vnum, DWORD vert) { for (unsigned int i = vnum.Size() - 1; i-- != 0; ) { if (vnum[i] == vert) { // Already in the set. No need to add it. return; } } vnum.Push(vert); } //========================================================================== // // IterFindPolySides // // Beginning with the first vertex of the starting side, for each vertex // in vnum, add all the sides that use it as a first vertex to the polyobj, // and add all their second vertices to vnum. This continues until there // are no new vertices in vnum. // //========================================================================== static void IterFindPolySides (FPolyObj *po, side_t *side) { static TArray<DWORD> vnum; unsigned int vnumat; assert(sidetemp != NULL); vnum.Clear(); vnum.Push(DWORD(side->V1() - vertexes)); vnumat = 0; while (vnum.Size() != vnumat) { DWORD sidenum = sidetemp[vnum[vnumat++]].b.first; while (sidenum != NO_SIDE) { po->Sidedefs.Push(&sides[sidenum]); AddPolyVert(vnum, DWORD(sides[sidenum].V2() - vertexes)); sidenum = sidetemp[sidenum].b.next; } } } //========================================================================== // // SpawnPolyobj // //========================================================================== static void SpawnPolyobj (int index, int tag, int type) { unsigned int ii; int i; int j; FPolyObj *po = &polyobjs[index]; for (ii = 0; ii < KnownPolySides.Size(); ++ii) { i = KnownPolySides[ii]; if (i < 0) { continue; } side_t *sd = &sides[i]; if (sd->linedef->special == Polyobj_StartLine && sd->linedef->args[0] == tag) { if (po->Sidedefs.Size() > 0) { I_Error ("SpawnPolyobj: Polyobj %d already spawned.\n", tag); } sd->linedef->special = 0; sd->linedef->args[0] = 0; IterFindPolySides(&polyobjs[index], sd); po->MirrorNum = sd->linedef->args[1]; po->crush = (type != PO_SPAWN_TYPE) ? 3 : 0; po->bHurtOnTouch = (type == PO_SPAWNHURT_TYPE); po->tag = tag; po->seqType = sd->linedef->args[2]; if (po->seqType < 0 || po->seqType > 63) { po->seqType = 0; } break; } } if (po->Sidedefs.Size() == 0) { // didn't find a polyobj through PO_LINE_START TArray<side_t *> polySideList; unsigned int psIndexOld; for (j = 1; j < PO_MAXPOLYSEGS; j++) { psIndexOld = po->Sidedefs.Size(); for (ii = 0; ii < KnownPolySides.Size(); ++ii) { i = KnownPolySides[ii]; if (i >= 0 && sides[i].linedef->special == Polyobj_ExplicitLine && sides[i].linedef->args[0] == tag) { if (!sides[i].linedef->args[1]) { I_Error ("SpawnPolyobj: Explicit line missing order number (probably %d) in poly %d.\n", j+1, tag); } if (sides[i].linedef->args[1] == j) { po->Sidedefs.Push (&sides[i]); } } } // Clear out any specials for these segs...we cannot clear them out // in the above loop, since we aren't guaranteed one seg per linedef. for (ii = 0; ii < KnownPolySides.Size(); ++ii) { i = KnownPolySides[ii]; if (i >= 0 && sides[i].linedef->special == Polyobj_ExplicitLine && sides[i].linedef->args[0] == tag && sides[i].linedef->args[1] == j) { sides[i].linedef->special = 0; sides[i].linedef->args[0] = 0; KnownPolySides[ii] = -1; } } if (po->Sidedefs.Size() == psIndexOld) { // Check if an explicit line order has been skipped. // A line has been skipped if there are any more explicit // lines with the current tag value. [RH] Can this actually happen? for (ii = 0; ii < KnownPolySides.Size(); ++ii) { i = KnownPolySides[ii]; if (i >= 0 && sides[i].linedef->special == Polyobj_ExplicitLine && sides[i].linedef->args[0] == tag) { I_Error ("SpawnPolyobj: Missing explicit line %d for poly %d\n", j, tag); } } } } if (po->Sidedefs.Size() > 0) { po->crush = (type != PO_SPAWN_TYPE) ? 3 : 0; po->bHurtOnTouch = (type == PO_SPAWNHURT_TYPE); po->tag = tag; po->seqType = po->Sidedefs[0]->linedef->args[3]; po->MirrorNum = po->Sidedefs[0]->linedef->args[2]; } else I_Error ("SpawnPolyobj: Poly %d does not exist\n", tag); } validcount++; for(unsigned int i=0; i<po->Sidedefs.Size(); i++) { line_t *l = po->Sidedefs[i]->linedef; if (l->validcount != validcount) { l->validcount = validcount; po->Linedefs.Push(l); vertex_t *v = l->v1; int j; for(j = po->Vertices.Size() - 1; j >= 0; j--) { if (po->Vertices[j] == v) break; } if (j < 0) po->Vertices.Push(v); v = l->v2; for(j = po->Vertices.Size() - 1; j >= 0; j--) { if (po->Vertices[j] == v) break; } if (j < 0) po->Vertices.Push(v); } } po->Sidedefs.ShrinkToFit(); po->Linedefs.ShrinkToFit(); po->Vertices.ShrinkToFit(); } //========================================================================== // // TranslateToStartSpot // //========================================================================== static void TranslateToStartSpot (int tag, int originX, int originY) { FPolyObj *po; int deltaX; int deltaY; po = NULL; for (int i = 0; i < po_NumPolyobjs; i++) { if (polyobjs[i].tag == tag) { po = &polyobjs[i]; break; } } if (po == NULL) { // didn't match the tag with a polyobj tag I_Error("TranslateToStartSpot: Unable to match polyobj tag: %d\n", tag); } if (po->Sidedefs.Size() == 0) { I_Error ("TranslateToStartSpot: Anchor point located without a StartSpot point: %d\n", tag); } po->OriginalPts.Resize(po->Sidedefs.Size()); po->PrevPts.Resize(po->Sidedefs.Size()); deltaX = originX - po->StartSpot.x; deltaY = originY - po->StartSpot.y; for (unsigned i = 0; i < po->Sidedefs.Size(); i++) { po->Sidedefs[i]->Flags |= WALLF_POLYOBJ; } for (unsigned i = 0; i < po->Linedefs.Size(); i++) { po->Linedefs[i]->bbox[BOXTOP] -= deltaY; po->Linedefs[i]->bbox[BOXBOTTOM] -= deltaY; po->Linedefs[i]->bbox[BOXLEFT] -= deltaX; po->Linedefs[i]->bbox[BOXRIGHT] -= deltaX; } for (unsigned i = 0; i < po->Vertices.Size(); i++) { po->Vertices[i]->x -= deltaX; po->Vertices[i]->y -= deltaY; po->OriginalPts[i].x = po->Vertices[i]->x - po->StartSpot.x; po->OriginalPts[i].y = po->Vertices[i]->y - po->StartSpot.y; } po->CalcCenter(); // For compatibility purposes po->CenterSubsector = R_PointInSubsector(po->CenterSpot.x, po->CenterSpot.y); } //========================================================================== // // PO_Init // //========================================================================== void PO_Init (void) { // [RH] Hexen found the polyobject-related things by reloading the map's // THINGS lump here and scanning through it. I have P_SpawnMapThing() // record those things instead, so that in here we simply need to // look at the polyspawns list. polyspawns_t *polyspawn, **prev; int polyIndex; // [RH] Make this faster InitSideLists (); polyobjs = new FPolyObj[po_NumPolyobjs]; polyIndex = 0; // index polyobj number // Find the startSpot points, and spawn each polyobj for (polyspawn = polyspawns, prev = &polyspawns; polyspawn;) { // 9301 (3001) = no crush, 9302 (3002) = crushing, 9303 = hurting touch if (polyspawn->type == PO_SPAWN_TYPE || polyspawn->type == PO_SPAWNCRUSH_TYPE || polyspawn->type == PO_SPAWNHURT_TYPE) { // Polyobj StartSpot Pt. polyobjs[polyIndex].StartSpot.x = polyspawn->x; polyobjs[polyIndex].StartSpot.y = polyspawn->y; SpawnPolyobj(polyIndex, polyspawn->angle, polyspawn->type); polyIndex++; *prev = polyspawn->next; delete polyspawn; polyspawn = *prev; } else { prev = &polyspawn->next; polyspawn = polyspawn->next; } } for (polyspawn = polyspawns; polyspawn;) { polyspawns_t *next = polyspawn->next; if (polyspawn->type == PO_ANCHOR_TYPE) { // Polyobj Anchor Pt. TranslateToStartSpot (polyspawn->angle, polyspawn->x, polyspawn->y); } delete polyspawn; polyspawn = next; } polyspawns = NULL; // check for a startspot without an anchor point for (polyIndex = 0; polyIndex < po_NumPolyobjs; polyIndex++) { if (polyobjs[polyIndex].OriginalPts.Size() == 0) { I_Error ("PO_Init: StartSpot located without an Anchor point: %d\n", polyobjs[polyIndex].tag); } } InitBlockMap(); // [RH] Don't need the seg lists anymore KillSideLists (); for(int i=0;i<numnodes;i++) { node_t *no = &nodes[i]; double fdx = (double)no->dx; double fdy = (double)no->dy; no->len = (float)sqrt(fdx * fdx + fdy * fdy); } // mark all subsectors which have a seg belonging to a polyobj // These ones should not be rendered on the textured automap. for (int i = 0; i < numsubsectors; i++) { subsector_t *ss = &subsectors[i]; for(DWORD j=0;j<ss->numlines; j++) { if (ss->firstline[j].sidedef != NULL && ss->firstline[j].sidedef->Flags & WALLF_POLYOBJ) { ss->flags |= SSECF_POLYORG; break; } } } } //========================================================================== // // PO_Busy // //========================================================================== bool PO_Busy (int polyobj) { FPolyObj *poly; poly = PO_GetPolyobj (polyobj); return (poly != NULL && poly->specialdata != NULL); } //========================================================================== // // // //========================================================================== void FPolyObj::ClearSubsectorLinks() { while (subsectorlinks != NULL) { assert(subsectorlinks->state == 1337); FPolyNode *next = subsectorlinks->snext; if (subsectorlinks->pnext != NULL) { assert(subsectorlinks->pnext->state == 1337); subsectorlinks->pnext->pprev = subsectorlinks->pprev; } if (subsectorlinks->pprev != NULL) { assert(subsectorlinks->pprev->state == 1337); subsectorlinks->pprev->pnext = subsectorlinks->pnext; } else { subsectorlinks->subsector->polys = subsectorlinks->pnext; } if (subsectorlinks->subsector->BSP != NULL) { subsectorlinks->subsector->BSP->bDirty = true; } subsectorlinks->state = -1; delete subsectorlinks; subsectorlinks = next; } subsectorlinks = NULL; } void FPolyObj::ClearAllSubsectorLinks() { for (int i = 0; i < po_NumPolyobjs; i++) { polyobjs[i].ClearSubsectorLinks(); } ReleaseAllPolyNodes(); } //========================================================================== // // GetIntersection // // adapted from P_InterceptVector // //========================================================================== static bool GetIntersection(FPolySeg *seg, node_t *bsp, FPolyVertex *v) { double frac; double num; double den; double v2x = (double)seg->v1.x; double v2y = (double)seg->v1.y; double v2dx = (double)(seg->v2.x - seg->v1.x); double v2dy = (double)(seg->v2.y - seg->v1.y); double v1x = (double)bsp->x; double v1y = (double)bsp->y; double v1dx = (double)bsp->dx; double v1dy = (double)bsp->dy; den = v1dy*v2dx - v1dx*v2dy; if (den == 0) return false; // parallel num = (v1x - v2x)*v1dy + (v2y - v1y)*v1dx; frac = num / den; if (frac < 0. || frac > 1.) return false; v->x = xs_RoundToInt(v2x + frac * v2dx); v->y = xs_RoundToInt(v2y + frac * v2dy); return true; } //========================================================================== // // PartitionDistance // // Determine the distance of a vertex to a node's partition line. // //========================================================================== static double PartitionDistance(FPolyVertex *vt, node_t *node) { return fabs(double(-node->dy) * (vt->x - node->x) + double(node->dx) * (vt->y - node->y)) / node->len; } //========================================================================== // // AddToBBox // //========================================================================== static void AddToBBox(fixed_t child[4], fixed_t parent[4]) { if (child[BOXTOP] > parent[BOXTOP]) { parent[BOXTOP] = child[BOXTOP]; } if (child[BOXBOTTOM] < parent[BOXBOTTOM]) { parent[BOXBOTTOM] = child[BOXBOTTOM]; } if (child[BOXLEFT] < parent[BOXLEFT]) { parent[BOXLEFT] = child[BOXLEFT]; } if (child[BOXRIGHT] > parent[BOXRIGHT]) { parent[BOXRIGHT] = child[BOXRIGHT]; } } //========================================================================== // // AddToBBox // //========================================================================== static void AddToBBox(FPolyVertex *v, fixed_t bbox[4]) { if (v->x < bbox[BOXLEFT]) { bbox[BOXLEFT] = v->x; } if (v->x > bbox[BOXRIGHT]) { bbox[BOXRIGHT] = v->x; } if (v->y < bbox[BOXBOTTOM]) { bbox[BOXBOTTOM] = v->y; } if (v->y > bbox[BOXTOP]) { bbox[BOXTOP] = v->y; } } //========================================================================== // // SplitPoly // //========================================================================== static void SplitPoly(FPolyNode *pnode, void *node, fixed_t bbox[4]) { static TArray<FPolySeg> lists[2]; static const double POLY_EPSILON = 0.3125; if (!((size_t)node & 1)) // Keep going until found a subsector { node_t *bsp = (node_t *)node; int centerside = R_PointOnSide(pnode->poly->CenterSpot.x, pnode->poly->CenterSpot.y, bsp); lists[0].Clear(); lists[1].Clear(); for(unsigned i=0;i<pnode->segs.Size(); i++) { FPolySeg *seg = &pnode->segs[i]; // Parts of the following code were taken from Eternity and are // being used with permission. // get distance of vertices from partition line // If the distance is too small, we may decide to // change our idea of sidedness. double dist_v1 = PartitionDistance(&seg->v1, bsp); double dist_v2 = PartitionDistance(&seg->v2, bsp); // If the distances are less than epsilon, consider the points as being // on the same side as the polyobj origin. Why? People like to build // polyobject doors flush with their door tracks. This breaks using the // usual assumptions. // Addition to Eternity code: We must also check any seg with only one // vertex inside the epsilon threshold. If not, these lines will get split but // adjoining ones with both vertices inside the threshold won't thus messing up // the order in which they get drawn. if(dist_v1 <= POLY_EPSILON) { if (dist_v2 <= POLY_EPSILON) { lists[centerside].Push(*seg); } else { int side = R_PointOnSide(seg->v2.x, seg->v2.y, bsp); lists[side].Push(*seg); } } else if (dist_v2 <= POLY_EPSILON) { int side = R_PointOnSide(seg->v1.x, seg->v1.y, bsp); lists[side].Push(*seg); } else { int side1 = R_PointOnSide(seg->v1.x, seg->v1.y, bsp); int side2 = R_PointOnSide(seg->v2.x, seg->v2.y, bsp); if(side1 != side2) { // if the partition line crosses this seg, we must split it. FPolyVertex vert; if (GetIntersection(seg, bsp, &vert)) { lists[0].Push(*seg); lists[1].Push(*seg); lists[side1].Last().v2 = vert; lists[side2].Last().v1 = vert; } else { // should never happen lists[side1].Push(*seg); } } else { // both points on the same side. lists[side1].Push(*seg); } } } if (lists[1].Size() == 0) { SplitPoly(pnode, bsp->children[0], bsp->bbox[0]); AddToBBox(bsp->bbox[0], bbox); } else if (lists[0].Size() == 0) { SplitPoly(pnode, bsp->children[1], bsp->bbox[1]); AddToBBox(bsp->bbox[1], bbox); } else { // create the new node FPolyNode *newnode = NewPolyNode(); newnode->poly = pnode->poly; newnode->segs = lists[1]; // set segs for original node pnode->segs = lists[0]; // recurse back side SplitPoly(newnode, bsp->children[1], bsp->bbox[1]); // recurse front side SplitPoly(pnode, bsp->children[0], bsp->bbox[0]); AddToBBox(bsp->bbox[0], bbox); AddToBBox(bsp->bbox[1], bbox); } } else { // we reached a subsector so we can link the node with this subsector subsector_t *sub = (subsector_t *)((BYTE *)node - 1); // Link node to subsector pnode->pnext = sub->polys; if (pnode->pnext != NULL) { assert(pnode->pnext->state == 1337); pnode->pnext->pprev = pnode; } pnode->pprev = NULL; sub->polys = pnode; // link node to polyobject pnode->snext = pnode->poly->subsectorlinks; pnode->poly->subsectorlinks = pnode; pnode->subsector = sub; // calculate bounding box for this polynode assert(pnode->segs.Size() != 0); fixed_t subbbox[4] = { FIXED_MIN, FIXED_MAX, FIXED_MAX, FIXED_MIN }; for (unsigned i = 0; i < pnode->segs.Size(); ++i) { AddToBBox(&pnode->segs[i].v1, subbbox); AddToBBox(&pnode->segs[i].v2, subbbox); } // Potentially expand the parent node's bounding box to contain these bits of polyobject. AddToBBox(subbbox, bbox); } } //========================================================================== // // // //========================================================================== void FPolyObj::CreateSubsectorLinks() { FPolyNode *node = NewPolyNode(); // Even though we don't care about it, we need to initialize this // bounding box to something so that Valgrind won't complain about it // when SplitPoly modifies it. fixed_t dummybbox[4] = { 0 }; node->poly = this; node->segs.Resize(Sidedefs.Size()); for(unsigned i=0; i<Sidedefs.Size(); i++) { FPolySeg *seg = &node->segs[i]; side_t *side = Sidedefs[i]; seg->v1 = side->V1(); seg->v2 = side->V2(); seg->wall = side; } if (!(i_compatflags & COMPATF_POLYOBJ)) { SplitPoly(node, nodes + numnodes - 1, dummybbox); } else { subsector_t *sub = CenterSubsector; // Link node to subsector node->pnext = sub->polys; if (node->pnext != NULL) { assert(node->pnext->state == 1337); node->pnext->pprev = node; } node->pprev = NULL; sub->polys = node; // link node to polyobject node->snext = node->poly->subsectorlinks; node->poly->subsectorlinks = node; node->subsector = sub; } } //========================================================================== // // // //========================================================================== void PO_LinkToSubsectors() { for (int i = 0; i < po_NumPolyobjs; i++) { if (polyobjs[i].subsectorlinks == NULL) { polyobjs[i].CreateSubsectorLinks(); } } } //========================================================================== // // NewPolyNode // //========================================================================== static FPolyNode *NewPolyNode() { FPolyNode *node; if (FreePolyNodes != NULL) { node = FreePolyNodes; FreePolyNodes = node->pnext; } else { node = new FPolyNode; } node->state = 1337; node->poly = NULL; node->pnext = NULL; node->pprev = NULL; node->subsector = NULL; node->snext = NULL; return node; } //========================================================================== // // FreePolyNode // //========================================================================== void FreePolyNode(FPolyNode *node) { node->segs.Clear(); node->pnext = FreePolyNodes; FreePolyNodes = node; } //========================================================================== // // ReleaseAllPolyNodes // //========================================================================== void ReleaseAllPolyNodes() { FPolyNode *node, *next; for (node = FreePolyNodes; node != NULL; node = next) { next = node->pnext; delete node; } } //========================================================================== // // FPolyMirrorIterator Constructor // // This class is used to avoid infinitely looping on cyclical chains of // mirrored polyobjects. // //========================================================================== FPolyMirrorIterator::FPolyMirrorIterator(FPolyObj *poly) { CurPoly = poly; if (poly != NULL) { UsedPolys[0] = poly->tag; NumUsedPolys = 1; } else { NumUsedPolys = 0; } } //========================================================================== // // FPolyMirrorIterator :: NextMirror // // Returns the polyobject that mirrors the current one, or NULL if there // is no mirroring polyobject, or there is a mirroring polyobject but it was // already returned. // //========================================================================== FPolyObj *FPolyMirrorIterator::NextMirror() { FPolyObj *poly = CurPoly, *nextpoly; if (poly == NULL) { return NULL; } // Do the work to decide which polyobject to return the next time this // function is called. int mirror = poly->GetMirror(), i; nextpoly = NULL; // Is there a mirror and we have room to remember it? if (mirror != 0 && NumUsedPolys != countof(UsedPolys)) { // Has this polyobject been returned already? for (i = 0; i < NumUsedPolys; ++i) { if (UsedPolys[i] == mirror) { break; // Yes, it has been returned. } } if (i == NumUsedPolys) { // No, it has not been returned. UsedPolys[NumUsedPolys++] = mirror; nextpoly = PO_GetPolyobj(mirror); if (nextpoly == NULL) { Printf("Invalid mirror polyobj num %d for polyobj num %d\n", mirror, UsedPolys[i - 1]); } } } CurPoly = nextpoly; return poly; }
0
0.915414
1
0.915414
game-dev
MEDIA
0.840176
game-dev
0.93287
1
0.93287
webbukkit/DynmapBlockScan
3,996
fabric-1.21/src/main/java/org/dynmapblockscan/fabric_1_21/DynmapBlockScanMod.java
package org.dynmapblockscan.fabric_1_21; import net.fabricmc.api.EnvType; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.ModContainer; import net.minecraft.server.MinecraftServer; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.loader.api.FabricLoader; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class DynmapBlockScanMod implements ModInitializer { public static DynmapBlockScanPlugin.OurLog logger = new DynmapBlockScanPlugin.OurLog(); private static final ModContainer MOD_CONTAINER = FabricLoader.getInstance().getModContainer("dynmapblockscan") .orElseThrow(() -> new RuntimeException("Failed to get mod container: dynmapblockscan")); // The instance of your mod that Forge uses. public static DynmapBlockScanMod instance; // Says where the client and server 'proxy' code is loaded. public static Proxy proxy = null; public static DynmapBlockScanPlugin plugin; public static File jarfile; public DynmapBlockScanMod(){ if(FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT){ proxy = new ClientProxy(); }else{ proxy = new Proxy(); } } @Override public void onInitialize(){ instance = this; logger.info("setup"); jarfile = MOD_CONTAINER.getOrigin().getPaths().get(0).toFile(); ServerLifecycleEvents.SERVER_STARTING.register(this::onServerStarting); ServerLifecycleEvents.SERVER_STARTED.register(this::onServerStarted); ServerLifecycleEvents.SERVER_STOPPED.register(this::onServerStopped); //FileUtils.getOrCreateDirectory(FabricLoader.getInstance().getConfigDir().resolve("dynmapblockscan"), "dynmapblockscan"); //ModLoadingContext.registerConfig("dynmapblockscan", ModConfig.Type.COMMON, SettingsConfig.SPEC, "dynmapblockscan/settings.toml"); } public static class SettingsConfig { // public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); // public static final ForgeConfigSpec SPEC; // // public static final ForgeConfigSpec.ConfigValue<List<? extends String>> excludeModules; // public static final ForgeConfigSpec.ConfigValue<List<? extends String>> excludeBlockNames; public static List<String> excludedModules = Arrays.asList("minecraft"); public static List<String> excludedBlockNames = Arrays.asList(); static { // BUILDER.comment("DynmapBlockScan settings"); // BUILDER.push("settings"); // excludeModules = BUILDER.comment("Which modules to exclude").defineList("exclude_modules", Arrays.asList("minecraft"), entry -> true); // excludeBlockNames = BUILDER.comment("Which block names to exclude").defineList("exclude_blocknames", Arrays.asList(), entry -> true); // BUILDER.pop(); // // SPEC = BUILDER.build(); } } private MinecraftServer server; public void onServerStarting(MinecraftServer server_) { server = server_; if(plugin == null) plugin = proxy.startServer(server); // plugin.setDisabledModules((List<String>) SettingsConfig.excludeModules.get()); // plugin.setDisabledBlockNames((List<String>) SettingsConfig.excludeBlockNames.get()); plugin.setDisabledModules((List<String>) SettingsConfig.excludedModules); plugin.setDisabledBlockNames((List<String>) SettingsConfig.excludedBlockNames); plugin.serverStarting(); } public void onServerStarted(MinecraftServer server_) { plugin.serverStarted(); } public void onServerStopped(MinecraftServer server_) { proxy.stopServer(plugin); plugin = null; } // @NetworkCheckHandler // public boolean netCheckHandler(Map<String, String> mods, Side side) { // return true; // } }
0
0.859336
1
0.859336
game-dev
MEDIA
0.935721
game-dev
0.819623
1
0.819623
ProjectKorra/ProjectKorra
12,091
core/src/com/projectkorra/projectkorra/earthbending/EarthGrab.java
package com.projectkorra.projectkorra.earthbending; import java.util.Arrays; import java.util.List; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Ageable; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Trident; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.Vector; import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.avatar.AvatarState; import com.projectkorra.projectkorra.util.MovementHandler; import com.projectkorra.projectkorra.util.ParticleEffect; import com.projectkorra.projectkorra.util.TempArmor; import com.projectkorra.projectkorra.util.TempArmorStand; import com.projectkorra.projectkorra.util.TempBlock; public class EarthGrab extends EarthAbility { private LivingEntity target; @Attribute(Attribute.COOLDOWN) private long cooldown; private long lastHit; private long interval; @Attribute(Attribute.RANGE) private double range; @Attribute(Attribute.SPEED) private double dragSpeed; @Attribute("TrapHealth") private double trapHP; private double trappedHP; private double damageThreshold; private GrabMode mode; private boolean initiated = false; private MovementHandler mHandler; private ArmorStand trap; private Location origin; private Vector direction; private TempArmor armor; private final Material[] crops = new Material[] { Material.WHEAT, Material.BEETROOTS, Material.CARROTS, Material.POTATOES, Material.SUGAR_CANE, Material.MELON, Material.PUMPKIN }; public static enum GrabMode { TRAP, DRAG, PROJECTING; } public EarthGrab(final Player player, final GrabMode mode) { super(player); if (hasAbility(player, EarthGrab.class)) { getAbility(player, EarthGrab.class).remove(); return; } if (bPlayer != null && this.bPlayer.isOnCooldown(this)) { //bPlayer can be null if the ability is disabled. If it is, it just won't start() return; } if (!this.isEarthbendable(player.getLocation().getBlock().getRelative(BlockFace.DOWN))) { return; } this.mode = mode; this.setFields(); this.start(); } private void setFields() { this.range = getConfig().getDouble("Abilities.Earth.EarthGrab.Range"); this.cooldown = getConfig().getLong("Abilities.Earth.EarthGrab.Cooldown"); this.dragSpeed = getConfig().getDouble("Abilities.Earth.EarthGrab.DragSpeed"); this.interval = getConfig().getLong("Abilities.Earth.EarthGrab.TrapHitInterval"); this.trapHP = getConfig().getDouble("Abilities.Earth.EarthGrab.TrapHP"); this.damageThreshold = getConfig().getDouble("Abilities.Earth.EarthGrab.DamageThreshold"); this.origin = this.player.getLocation().clone(); this.direction = this.player.getLocation().getDirection().setY(0).normalize(); this.lastHit = 0; } @Override public void progress() { if (!this.player.isOnline() || this.player.isDead()) { this.remove(); return; } if (this.target != null) { if (this.target instanceof Player) { final Player pt = (Player) this.target; if (!pt.isOnline()) { this.remove(); return; } } if (this.target.isDead()) { this.remove(); return; } } switch (this.mode) { case PROJECTING: this.project(); break; case TRAP: this.trap(); break; case DRAG: this.drag(); break; } } public void project() { this.origin = this.origin.add(this.direction); Block top = GeneralMethods.getTopBlock(this.origin, 2); if (this.origin.distance(this.player.getLocation()) > this.range) { this.remove(); return; } if (!this.isTransparent(top.getRelative(BlockFace.UP))) { this.remove(); return; } if (top.getType() == Material.FIRE) { top.setType(Material.AIR); } if (!this.isEarthbendable(top)) { Block under = top.getRelative(BlockFace.DOWN); if (this.isTransparent(top) && this.isEarthbendable(under)) { top = under; } else { this.remove(); return; } } if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.origin)) { this.remove(); return; } this.origin.setY(top.getY() + 1); ParticleEffect.BLOCK_DUST.display(this.origin, 27, 0.2, 0.5, 0.2, this.origin.getBlock().getRelative(BlockFace.DOWN).getBlockData()); playEarthbendingSound(this.origin); for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.origin, 1)) { if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId() && this.isEarthbendable(entity.getLocation().getBlock().getRelative(BlockFace.DOWN))) { if (entity instanceof Player && BendingPlayer.getBendingPlayer((Player) entity) != null) { if (CoreAbility.hasAbility((Player) entity, AvatarState.class)) { continue; } } this.target = (LivingEntity) entity; this.trappedHP = this.target.getHealth(); this.mode = GrabMode.TRAP; this.origin = this.target.getLocation().clone(); } } } public void trap() { if (!this.initiated) { final Material m = this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(); final TempArmorStand tas = new TempArmorStand(this.target.getLocation()); this.trap = tas.getArmorStand(); this.trap.setVisible(false); this.trap.setInvulnerable(false); this.trap.setSmall(true); this.trap.setHelmet(new ItemStack(m)); this.trap.setHealth(this.trapHP); this.trap.setMetadata("earthgrab:trap", new FixedMetadataValue(ProjectKorra.plugin, this)); new TempBlock(this.target.getLocation().clone().subtract(0, 1, 0).getBlock(), this.target.getLocation().clone().subtract(0, 1, 0).getBlock().getType()); this.mHandler = new MovementHandler(this.target, this); this.mHandler.stop(Element.EARTH.getColor() + "* Trapped *"); if (this.target instanceof Player || this.target instanceof Zombie || this.target instanceof Skeleton) { final ItemStack legs = new ItemStack(Material.LEATHER_LEGGINGS); final LeatherArmorMeta legmeta = (LeatherArmorMeta) legs.getItemMeta(); legmeta.setColor(Color.fromRGB(EarthArmor.getColor(m))); legs.setItemMeta(legmeta); final ItemStack feet = new ItemStack(Material.LEATHER_BOOTS); final LeatherArmorMeta footmeta = (LeatherArmorMeta) feet.getItemMeta(); footmeta.setColor(Color.fromRGB(EarthArmor.getColor(m))); feet.setItemMeta(footmeta); final ItemStack[] pieces = { (this.target.getEquipment().getArmorContents()[0] == null || this.target.getEquipment().getArmorContents()[0].getType() == Material.AIR) ? feet : null, (this.target.getEquipment().getArmorContents()[1] == null || this.target.getEquipment().getArmorContents()[1].getType() == Material.AIR) ? legs : null, null, null }; this.armor = new TempArmor(this.target, 36000000L, this, pieces); } playEarthbendingSound(this.target.getLocation()); this.initiated = true; } ParticleEffect.BLOCK_DUST.display(this.target.getLocation(), 36, 0.3, 0.6, 0.3, this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getBlockData()); if (!ElementalAbility.isAir(this.trap.getLocation().clone().subtract(0, 0.1, 0).getBlock().getType())) { this.trap.setGravity(false); } else { this.trap.setGravity(true); } if (!this.isEarthbendable(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN))) { this.remove(); return; } if (this.trap.getLocation().distance(this.target.getLocation()) > 2) { this.remove(); return; } if (this.trappedHP - this.target.getHealth() >= this.damageThreshold) { this.remove(); return; } if (this.trapHP <= 0) { this.remove(); return; } if (this.trap.isDead()) { this.remove(); return; } if (this.player.getLocation().distance(this.target.getLocation()) > this.range) { this.remove(); return; } if (!GeneralMethods.isSolid(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN))) { this.remove(); return; } if (GeneralMethods.isSolid(this.target.getLocation().getBlock())) { this.remove(); return; } } public void drag() { if (!this.player.isOnGround()) { return; } if (!this.player.isSneaking()) { this.remove(); return; } if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.player.getLocation())) { this.remove(); return; } for (final Location l : GeneralMethods.getCircle(this.player.getLocation(), (int) Math.floor(this.range), 2, false, false, 0)) { if (!Arrays.asList(this.crops).contains(l.getBlock().getType())) { continue; } final Block b = l.getBlock(); if ((b.getBlockData() instanceof Ageable && ((Ageable) b.getBlockData()).getAge() == ((Ageable) b.getBlockData()).getMaximumAge()) || b.getType() == Material.MELON || b.getType() == Material.PUMPKIN) { b.breakNaturally(); } } final List<Entity> ents = GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.range); if (ents.isEmpty()) { this.remove(); return; } for (Entity entity : ents) { if (!isEarth(entity.getLocation().clone().subtract(0, 1, 0).getBlock()) && (this.bPlayer.canSandbend() && !isSand(entity.getLocation().clone().subtract(0, 1, 0).getBlock())) && entity.getLocation().clone().subtract(0, 1, 0).getBlock().getType() != Material.FARMLAND) { continue; } if (entity instanceof Trident) { continue; } else if (entity instanceof Arrow) { final Arrow arrow = (Arrow) entity; if (arrow.getPickupStatus() == Arrow.PickupStatus.ALLOWED) { final Location l = entity.getLocation(); entity.remove(); entity = l.getWorld().dropItem(l, new ItemStack(Material.ARROW, 1)); } } else if (!(entity instanceof Item)) { continue; } final Block b = entity.getLocation().getBlock().getRelative(BlockFace.DOWN); GeneralMethods.setVelocity(this, entity, GeneralMethods.getDirection(entity.getLocation(), this.player.getLocation()).normalize().multiply(this.dragSpeed)); ParticleEffect.BLOCK_CRACK.display(entity.getLocation(), 2, 0, 0, 0, b.getBlockData()); playEarthbendingSound(entity.getLocation()); } } public void damageTrap() { if (System.currentTimeMillis() >= this.lastHit + this.interval) { this.trapHP -= 1; this.lastHit = System.currentTimeMillis(); ParticleEffect.BLOCK_CRACK.display(this.target.getLocation().clone().add(0, 1, 0), 7, 0.06, 0.3, 0.06, this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getBlockData()); playEarthbendingSound(this.target.getLocation()); } } @Override public void remove() { super.remove(); if (this.mode == GrabMode.TRAP && this.initiated) { this.mHandler.reset(); this.trap.remove(); if (TempArmor.getTempArmorList(this.target).contains(this.armor)) { this.armor.revert(); } } this.bPlayer.addCooldown(this); } @Override public boolean isSneakAbility() { return true; } @Override public boolean isHarmlessAbility() { return false; } @Override public long getCooldown() { return this.cooldown; } @Override public String getName() { return "EarthGrab"; } @Override public Location getLocation() { return this.target == null ? null : this.target.getLocation(); } public GrabMode getMode() { return this.mode; } public double getRange() { return this.range; } public LivingEntity getTarget() { return this.target; } }
0
0.928874
1
0.928874
game-dev
MEDIA
0.982387
game-dev
0.976487
1
0.976487
jrbudda/Vivecraft_114
1,461
mcppatches/mappings/conf/patches/minecraft_ff/net.minecraft.world.storage.loot.conditions.LootConditionManager.java.patch
diff -r -U 3 minecraft\net\minecraft\world\storage\loot\conditions\LootConditionManager.java minecraft_patched\net\minecraft\world\storage\loot\conditions\LootConditionManager.java --- minecraft\net\minecraft\world\storage\loot\conditions\LootConditionManager.java +++ minecraft_patched\net\minecraft\world\storage\loot\conditions\LootConditionManager.java @@ -21,7 +21,7 @@ public static <T extends ILootCondition> void func_186639_a(ILootCondition.AbstractSerializer<? extends T> p_186639_0_) { ResourceLocation resourcelocation = p_186639_0_.func_186602_a(); - Class<T> oclass = p_186639_0_.func_186604_b(); + Class<T> oclass = (Class<T>)p_186639_0_.func_186604_b(); if (field_186642_a.containsKey(resourcelocation)) { throw new IllegalArgumentException("Can't re-register item condition name " + resourcelocation); } else if (field_186643_b.containsKey(oclass)) { @@ -42,7 +42,7 @@ } public static <T extends ILootCondition> ILootCondition.AbstractSerializer<T> func_186640_a(T p_186640_0_) { - ILootCondition.AbstractSerializer<T> abstractserializer = field_186643_b.get(p_186640_0_.getClass()); + ILootCondition.AbstractSerializer<T> abstractserializer = (ILootCondition.AbstractSerializer<T>)field_186643_b.get(p_186640_0_.getClass()); if (abstractserializer == null) { throw new IllegalArgumentException("Unknown loot item condition " + p_186640_0_); } else {
0
0.714628
1
0.714628
game-dev
MEDIA
0.969405
game-dev
0.690678
1
0.690678
plantuml/plantuml
2,402
src/main/java/net/sourceforge/plantuml/real/RealMin.java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2024, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.real; import java.util.ArrayList; import java.util.Collection; import java.util.List; class RealMin extends AbstractReal implements Real { private final List<Real> all = new ArrayList<>(); RealMin(Collection<Real> reals) { super(RealMax.line(reals)); this.all.addAll(reals); } public String getName() { return "min " + all.size(); } private double cache = Double.MAX_VALUE; @Override double getCurrentValueInternal() { if (cache != Double.MAX_VALUE) return cache; double result = all.get(0).getCurrentValue(); for (int i = 1; i < all.size(); i++) { final double v = all.get(i).getCurrentValue(); if (v < result) result = v; } cache = result; return result; } public Real addFixed(double delta) { return new RealDelta(this, delta); } public Real addAtLeast(double delta) { throw new UnsupportedOperationException(); } public void ensureBiggerThan(Real other) { for (Real r : all) r.ensureBiggerThan(other); } public int size() { return all.size(); } public void printCreationStackTrace() { throw new UnsupportedOperationException(); } }
0
0.676214
1
0.676214
game-dev
MEDIA
0.253433
game-dev
0.870867
1
0.870867
XFactHD/FramedBlocks
2,292
src/main/java/io/github/xfacthd/framedblocks/common/data/skippreds/misc/CollapsibleCopycatBlockSkipPredicate.java
package io.github.xfacthd.framedblocks.common.data.skippreds.misc; import io.github.xfacthd.framedblocks.api.predicate.cull.SideSkipPredicate; import io.github.xfacthd.framedblocks.common.blockentity.special.ICollapsibleCopycatBlockEntity; import io.github.xfacthd.framedblocks.common.data.BlockType; import io.github.xfacthd.framedblocks.common.data.PropertyHolder; import io.github.xfacthd.framedblocks.common.data.skippreds.CullTest; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockState; @CullTest(BlockType.FRAMED_COLLAPSIBLE_COPYCAT_BLOCK) public final class CollapsibleCopycatBlockSkipPredicate implements SideSkipPredicate { private static final Direction[] DIRECTIONS = Direction.values(); @Override @CullTest.TestTarget(BlockType.FRAMED_COLLAPSIBLE_COPYCAT_BLOCK) public boolean test(BlockGetter level, BlockPos pos, BlockState state, BlockState adjState, Direction side) { if (adjState.getBlock() == state.getBlock()) { int solid = state.getValue(PropertyHolder.SOLID_FACES); if ((solid & (1 << side.ordinal())) == 0) { return false; } int adjSolid = adjState.getValue(PropertyHolder.SOLID_FACES); if ((adjSolid & (1 << side.getOpposite().ordinal())) == 0) { return false; } if (!(level.getBlockEntity(pos) instanceof ICollapsibleCopycatBlockEntity be)) { return false; } if (!(level.getBlockEntity(pos.relative(side)) instanceof ICollapsibleCopycatBlockEntity adjBe)) { return false; } for (Direction face : DIRECTIONS) { if (face.getAxis() == side.getAxis()) { continue; } int offset = be.getFaceOffset(state, face); int adjOffset = adjBe.getFaceOffset(adjState, face); if (offset != adjOffset) { return false; } } return true; } return false; } }
0
0.90858
1
0.90858
game-dev
MEDIA
0.918005
game-dev
0.854184
1
0.854184
LandSandBoat/server
1,653
scripts/zones/Nyzul_Isle/mobs/Imperial_Gear.lua
----------------------------------- -- Area: Nyzul Isle (Path of Darkness) -- Mob: Imperial Gear ----------------------------------- local ID = zones[xi.zone.NYZUL_ISLE] ----------------------------------- ---@type TMobEntity local entity = {} entity.onMobSpawn = function(mob) local instance = mob:getInstance() if not instance then return end local progress = instance:getProgress() if progress >= 24 then local mobs = instance:getMobs() for i, v in pairs(mobs) do if v:getID() == ID.mob.AMNAF_BLU then local pos = v:getPos() if mob:getID() == ID.mob.IMPERIAL_GEAR_OFFSET then mob:setPos(pos.x + 2, pos.y, pos.z, pos.rot) elseif mob:getID() == ID.mob.IMPERIAL_GEAR_OFFSET + 1 then mob:setPos(pos.x, pos.y, pos.z + 2, pos.rot) elseif mob:getID() == ID.mob.IMPERIAL_GEAR_OFFSET + 2 then mob:setPos(pos.x - 2, pos.y, pos.z, pos.rot) elseif mob:getID() == ID.mob.IMPERIAL_GEAR_OFFSET + 3 then mob:setPos(pos.x, pos.y, pos.z - 2, pos.rot) end end end end end entity.onMobEngage = function(mob, target) local naja = GetMobByID(ID.mob.NAJA_SALAHEEM, mob:getInstance()) if naja then naja:setLocalVar('ready', 1) end end entity.onMobDeath = function(mob, player, optParams) end entity.onMobDespawn = function(mob) local instance = mob:getInstance() if not instance then return end instance:setProgress(instance:getProgress() + 1) end return entity
0
0.948664
1
0.948664
game-dev
MEDIA
0.965115
game-dev
0.87538
1
0.87538
IJEMIN/Unity-Programming-Essence-2021
10,539
19/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/Demos/DemoProcedural/Scripts/IngameControlPanel.cs
using ExitGames.Client.Photon; using Photon.Realtime; using UnityEngine; using UnityEngine.UI; namespace Photon.Pun.Demo.Procedural { /// <summary> /// The Ingame Control Panel basically controls the WorldGenerator. /// It is only interactable for the current MasterClient in the room. /// </summary> public class IngameControlPanel : MonoBehaviourPunCallbacks { private bool isSeedValid; private InputField seedInputField; private Dropdown worldSizeDropdown; private Dropdown clusterSizeDropdown; private Dropdown worldTypeDropdown; private Button generateWorldButton; #region UNITY /// <summary> /// When the object gets created, all necessary references are set up. /// Also the UI elements get set up properly in order to control the WorldGenerator. /// </summary> public void Awake() { isSeedValid = false; seedInputField = GetComponentInChildren<InputField>(); seedInputField.characterLimit = 10; seedInputField.characterValidation = InputField.CharacterValidation.Integer; seedInputField.interactable = PhotonNetwork.PhotonServerSettings.StartInOfflineMode; seedInputField.onValueChanged.AddListener((string value) => { int seed; if (int.TryParse(value, out seed)) { isSeedValid = true; WorldGenerator.Instance.Seed = seed; } else { isSeedValid = false; Debug.LogError("Invalid Seed entered. Only numeric Seeds are allowed."); } }); worldSizeDropdown = GetComponentsInChildren<Dropdown>()[0]; worldSizeDropdown.interactable = PhotonNetwork.PhotonServerSettings.StartInOfflineMode; worldSizeDropdown.onValueChanged.AddListener((int value) => { switch (value) { case 0: { WorldGenerator.Instance.WorldSize = WorldSize.Tiny; break; } case 1: { WorldGenerator.Instance.WorldSize = WorldSize.Small; break; } case 2: { WorldGenerator.Instance.WorldSize = WorldSize.Medium; break; } case 3: { WorldGenerator.Instance.WorldSize = WorldSize.Large; break; } } }); clusterSizeDropdown = GetComponentsInChildren<Dropdown>()[1]; clusterSizeDropdown.interactable = PhotonNetwork.PhotonServerSettings.StartInOfflineMode; clusterSizeDropdown.onValueChanged.AddListener((int value) => { switch (value) { case 0: { WorldGenerator.Instance.ClusterSize = ClusterSize.Small; break; } case 1: { WorldGenerator.Instance.ClusterSize = ClusterSize.Medium; break; } case 2: { WorldGenerator.Instance.ClusterSize = ClusterSize.Large; break; } } }); worldTypeDropdown = GetComponentsInChildren<Dropdown>()[2]; worldTypeDropdown.interactable = PhotonNetwork.PhotonServerSettings.StartInOfflineMode; worldTypeDropdown.onValueChanged.AddListener((int value) => { switch (value) { case 0: { WorldGenerator.Instance.WorldType = WorldType.Flat; break; } case 1: { WorldGenerator.Instance.WorldType = WorldType.Standard; break; } case 2: { WorldGenerator.Instance.WorldType = WorldType.Mountain; break; } } }); generateWorldButton = GetComponentInChildren<Button>(); generateWorldButton.interactable = PhotonNetwork.PhotonServerSettings.StartInOfflineMode; generateWorldButton.onClick.AddListener(() => { if (!PhotonNetwork.InRoom) { Debug.LogError("Client is not in a room."); return; } if (!isSeedValid) { Debug.LogError("Invalid Seed entered. Only numeric Seeds are allowed."); return; } WorldGenerator.Instance.ConfirmAndUpdateProperties(); }); } #endregion #region PUN CALLBACKS /// <summary> /// Gets called when the local client has joined the room. /// Since only the MasterClient can control the WorldGenerator, /// we are checking if we have to make the UI controls available for the local client. /// </summary> public override void OnJoinedRoom() { seedInputField.interactable = PhotonNetwork.IsMasterClient; worldSizeDropdown.interactable = PhotonNetwork.IsMasterClient; clusterSizeDropdown.interactable = PhotonNetwork.IsMasterClient; worldTypeDropdown.interactable = PhotonNetwork.IsMasterClient; generateWorldButton.interactable = PhotonNetwork.IsMasterClient; } /// <summary> /// Gets called whenever the current MasterClient has left the room and a new one is selected. /// If the local client is the new MasterClient, we make the UI controls available for him. /// </summary> public override void OnMasterClientSwitched(Player newMasterClient) { seedInputField.interactable = newMasterClient.IsLocal; worldSizeDropdown.interactable = newMasterClient.IsLocal; clusterSizeDropdown.interactable = newMasterClient.IsLocal; worldTypeDropdown.interactable = newMasterClient.IsLocal; generateWorldButton.interactable = newMasterClient.IsLocal; } /// <summary> /// Gets called whenever the Custom Room Properties are updated. /// In this callback we are interested in the settings the MasterClient can apply to the WorldGenerator. /// If all possible settings are updated (and available within the updated properties), these settings are also used /// to update the Ingame Control Panel as well as the WorldGenerator on all clients. /// Afterwards the WorldGenerator creates a new world with the new settings. /// </summary> public override void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged) { if (propertiesThatChanged.ContainsKey(WorldGenerator.Instance.SeedPropertiesKey) && propertiesThatChanged.ContainsKey(WorldGenerator.Instance.WorldSizePropertiesKey) && propertiesThatChanged.ContainsKey(WorldGenerator.Instance.ClusterSizePropertiesKey) && propertiesThatChanged.ContainsKey(WorldGenerator.Instance.WorldTypePropertiesKey)) { // Updating Seed int seed = (int) propertiesThatChanged[WorldGenerator.Instance.SeedPropertiesKey]; seedInputField.text = seed.ToString(); // Updating World Size WorldSize worldSize = (WorldSize) propertiesThatChanged[WorldGenerator.Instance.WorldSizePropertiesKey]; switch (worldSize) { case WorldSize.Tiny: { worldSizeDropdown.value = 0; break; } case WorldSize.Small: { worldSizeDropdown.value = 1; break; } case WorldSize.Medium: { worldSizeDropdown.value = 2; break; } case WorldSize.Large: { worldSizeDropdown.value = 3; break; } } // Updating Cluster Size ClusterSize clusterSize = (ClusterSize) propertiesThatChanged[WorldGenerator.Instance.ClusterSizePropertiesKey]; switch (clusterSize) { case ClusterSize.Small: { clusterSizeDropdown.value = 0; break; } case ClusterSize.Medium: { clusterSizeDropdown.value = 1; break; } case ClusterSize.Large: { clusterSizeDropdown.value = 2; break; } } // Updating World Type WorldType worldType = (WorldType) propertiesThatChanged[WorldGenerator.Instance.WorldTypePropertiesKey]; switch (worldType) { case WorldType.Flat: { worldTypeDropdown.value = 0; break; } case WorldType.Standard: { worldTypeDropdown.value = 1; break; } case WorldType.Mountain: { worldTypeDropdown.value = 2; break; } } // Generating a new world WorldGenerator.Instance.CreateWorld(); } } #endregion } }
0
0.822623
1
0.822623
game-dev
MEDIA
0.77123
game-dev
0.842818
1
0.842818
lucko/helper
7,481
helper/src/main/java/me/lucko/helper/serialize/ChunkPosition.java
/* * This file is part of helper, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * 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 Software. * * THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.helper.serialize; import com.flowpowered.math.vector.Vector2i; import com.google.common.base.Preconditions; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import me.lucko.helper.Helper; import me.lucko.helper.cache.Lazy; import me.lucko.helper.gson.GsonSerializable; import me.lucko.helper.gson.JsonBuilder; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.BlockFace; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; /** * An immutable and serializable chuck location object */ public final class ChunkPosition implements GsonSerializable { public static ChunkPosition deserialize(JsonElement element) { Preconditions.checkArgument(element.isJsonObject()); JsonObject object = element.getAsJsonObject(); Preconditions.checkArgument(object.has("x")); Preconditions.checkArgument(object.has("z")); Preconditions.checkArgument(object.has("world")); int x = object.get("x").getAsInt(); int z = object.get("z").getAsInt(); String world = object.get("world").getAsString(); return of(x, z, world); } public static ChunkPosition of(int x, int z, String world) { Objects.requireNonNull(world, "world"); return new ChunkPosition(x, z, world); } public static ChunkPosition of(int x, int z, World world) { Objects.requireNonNull(world, "world"); return of(x, z, world.getName()); } public static ChunkPosition of(Vector2i vector, String world) { Objects.requireNonNull(vector, "vector"); Objects.requireNonNull(world, "world"); return of(vector.getX(), vector.getY(), world); } public static ChunkPosition of(Vector2i vector, World world) { Objects.requireNonNull(vector, "vector"); Objects.requireNonNull(world, "world"); return of(vector.getX(), vector.getY(), world); } public static ChunkPosition of(Chunk location) { Objects.requireNonNull(location, "location"); return of(location.getX(), location.getZ(), location.getWorld().getName()); } public static ChunkPosition of(long encodedLong, String world) { Objects.requireNonNull(world, "world"); return of((int) encodedLong, (int) (encodedLong >> 32), world); } public static ChunkPosition of(long encodedLong, World world) { Objects.requireNonNull(world, "world"); return of(encodedLong, world.getName()); } private final int x; private final int z; private final String world; private final Lazy<Collection<BlockPosition>> blocks = Lazy.suppliedBy(() -> { List<BlockPosition> blocks = new ArrayList<>(16 * 16 * 256); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 256; y++) { blocks.add(getBlock(x, y, z)); } } } return Collections.unmodifiableList(blocks); }); private ChunkPosition(int x, int z, String world) { this.x = x; this.z = z; this.world = world; } public int getX() { return this.x; } public int getZ() { return this.z; } public String getWorld() { return this.world; } public Vector2i toVector() { return new Vector2i(this.x, this.z); } public Chunk toChunk() { return Helper.world(this.world).get().getChunkAt(this.x, this.z); } public boolean contains(BlockPosition block) { return equals(block.toChunk()); } public boolean contains(Position position) { return equals(position.floor().toChunk()); } public BlockPosition getBlock(int x, int y, int z) { return BlockPosition.of((this.x << 4) | (x & 0xF), y, (this.z << 4) | (z & 0xF), this.world); } public Collection<BlockPosition> blocks() { return this.blocks.get(); } public ChunkPosition getRelative(BlockFace face) { Preconditions.checkArgument(face != BlockFace.UP && face != BlockFace.DOWN, "invalid face"); return ChunkPosition.of(this.x + face.getModX(), this.z + face.getModZ(), this.world); } public ChunkPosition getRelative(BlockFace face, int distance) { Preconditions.checkArgument(face != BlockFace.UP && face != BlockFace.DOWN, "invalid face"); return ChunkPosition.of(this.x + (face.getModX() * distance), this.z + (face.getModZ() * distance), this.world); } public ChunkPosition add(Vector2i vector2i) { return add(vector2i.getX(), vector2i.getY()); } public ChunkPosition add(int x, int z) { return ChunkPosition.of(this.x + x, this.z + z, this.world); } public ChunkPosition subtract(Vector2i vector2i) { return subtract(vector2i.getX(), vector2i.getY()); } public ChunkPosition subtract(int x, int z) { return add(-x, -z); } public long asEncodedLong() { return (long) this.x & 0xffffffffL | ((long) this.z & 0xffffffffL) << 32; } @Nonnull @Override public JsonObject serialize() { return JsonBuilder.object() .add("x", this.x) .add("z", this.z) .add("world", this.world) .build(); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof ChunkPosition)) return false; final ChunkPosition other = (ChunkPosition) o; return this.getX() == other.getX() && this.getZ() == other.getZ() && this.getWorld().equals(other.getWorld()); } @Override public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getX(); result = result * PRIME + this.getZ(); result = result * PRIME + this.getWorld().hashCode(); return result; } @Override public String toString() { return "ChunkPosition(x=" + this.getX() + ", z=" + this.getZ() + ", world=" + this.getWorld() + ")"; } }
0
0.840806
1
0.840806
game-dev
MEDIA
0.664562
game-dev
0.808137
1
0.808137
Illumina/Pisces
5,295
src/lib/Gemini/BinSignalCollection/SparseGroupedBins.cs
using System; using System.Collections.Generic; namespace Gemini.BinSignalCollection { public abstract class SparseGroupedBins<T> : IBins<T> { private readonly int _numBins; private readonly int _groupSize; private readonly int _numGroups; protected List<T[]> Groups; private int?[] _groupedBinsIndexes; public SparseGroupedBins(int numBins, int groupSize = 100) { _numBins = numBins; _groupSize = groupSize; Groups = new List<T[]>(); _numGroups = (numBins / groupSize) + 1; _groupedBinsIndexes = new int?[_numGroups]; } protected abstract void AddHitInternal(T[] group, int indexWithinGroup); public bool IncrementHit(int i, int count) { if (i >= _numBins || i < 0) { return false; } var groupIndex = i / _groupSize; var groupedBinIndex = _groupedBinsIndexes[groupIndex]; var indexWithinGroup = i % _groupSize; if (groupedBinIndex >= 0) { var group = Groups[groupedBinIndex.Value]; for (int j = 0; j < count; j++) { AddHitInternal(group, indexWithinGroup); } } else { var newGroupIndex = Groups.Count; Groups.Add(new T[_groupSize]); _groupedBinsIndexes[groupIndex] = newGroupIndex; for (int j = 0; j < count; j++) { AddHitInternal(Groups[newGroupIndex], indexWithinGroup); } } return true; } public bool AddHit(int i) { if (i >= _numBins || i < 0) { return false; } var groupIndex = i / _groupSize; var groupedBinIndex = _groupedBinsIndexes[groupIndex]; var indexWithinGroup = i % _groupSize; if (groupedBinIndex >= 0) { var group = Groups[groupedBinIndex.Value]; AddHitInternal(group, indexWithinGroup); } else { var newGroupIndex = Groups.Count; Groups.Add(new T[_groupSize]); _groupedBinsIndexes[groupIndex] = newGroupIndex; AddHitInternal(Groups[newGroupIndex], indexWithinGroup); } return true; } private T[] GetGroup(int i, bool strict = false) { if (i >= _numBins || i < 0) { if (strict) { throw new ArgumentException($"Requested bin number is outside of range ({i} vs {_numBins})."); } return null; } var groupIndex = i / _groupSize; if (groupIndex >= _groupedBinsIndexes.Length || groupIndex < 0) { if (strict) { throw new ArgumentException($"Requested bin number is outside of range ({i} vs {_numBins})."); } return null; } var groupedBinIndex = _groupedBinsIndexes[groupIndex]; if (groupedBinIndex >= 0 && groupedBinIndex < Groups.Count) { var group = Groups[groupedBinIndex.Value]; return group; } if (strict) { throw new ArgumentException($"Requested bin number is outside of range ({i} vs {_numBins})."); } return null; } protected abstract T ReturnDefault(); public T GetHit(int i, bool strict = false) { var group = GetGroup(i, strict); if (group == null) { return ReturnDefault(); } else { var indexWithinGroup = i % _groupSize; return group[indexWithinGroup]; } } /// <summary> /// Increment the hits of this bin with the hits from otherBins. Assumes they are on the same scale, /// and will not go past the current bins. If offset not provided, also assumes start positions are the same. /// </summary> /// <param name="otherBins"></param> /// <param name="binOffset"></param> public void Merge(IBins<T> otherBins, int binOffset, int startBinInOther, int endBinInOther) { var defaultResult = ReturnDefault(); var startBinInThis = startBinInOther - binOffset; var endBinInThis = Math.Min(_numBins, endBinInOther - binOffset); for (int i = startBinInThis; i <= endBinInThis; i++) { var binIndexInOther = i + binOffset; // Note, this keeps checking even if we've gone past the range of the other guy var otherHit = otherBins.GetHit(binIndexInOther); if (!otherHit.Equals(defaultResult)) { MergeHits(i, otherHit); } } } protected abstract void MergeHits(int i, T otherHit); } }
0
0.743145
1
0.743145
game-dev
MEDIA
0.301383
game-dev
0.903172
1
0.903172
CalamityTeam/CalamityModPublic
3,055
Projectiles/Melee/CosmicOrb.cs
using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee { public class CosmicOrb : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Melee"; public override void SetDefaults() { Projectile.extraUpdates = 0; Projectile.width = 14; Projectile.height = 14; Projectile.friendly = true; Projectile.penetrate = -1; Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 10; } public override void AI() { Lighting.AddLight(Projectile.Center, new Vector3(0.075f, 0.5f, 0.15f)); Projectile.velocity *= 0.985f; Projectile.rotation += Projectile.velocity.X * 0.2f; if (Projectile.velocity.X > 0f) { Projectile.rotation += 0.08f; } else { Projectile.rotation -= 0.08f; } Projectile.ai[1] += 1f; if (Projectile.ai[1] > 30f) { Projectile.alpha += 10; if (Projectile.alpha >= 255) { Projectile.alpha = 255; Projectile.Kill(); return; } } if (Main.rand.NextBool(2)) CalamityUtils.MagnetSphereHitscan(Projectile, 500f, 6f, 8f, 5, ModContent.ProjectileType<CosmicBolt>()); } public override void OnKill(int timeLeft) { SoundEngine.PlaySound(SoundID.Item54, Projectile.position); for (int i = 0; i < 10; i++) { int dustScale = (int)(10f * Projectile.scale); int d = Dust.NewDust(Projectile.Center - Vector2.One * (float)dustScale, dustScale * 2, dustScale * 2, DustID.PinkTorch, 0f, 0f, 0, default, 1f); Dust dust = Main.dust[d]; Vector2 offset = Vector2.Normalize(dust.position - Projectile.Center); dust.position = Projectile.Center + offset * (float)dustScale * Projectile.scale; if (i < 30) { dust.velocity = offset * dust.velocity.Length(); } else { dust.velocity = offset * Main.rand.NextFloat(4.5f, 9f); } dust.color = Main.hslToRgb(0.95f, 0.41f + Main.rand.NextFloat() * 0.2f, 0.93f); dust.color = Color.Lerp(dust.color, Color.White, 0.3f); dust.noGravity = true; dust.scale = 0.7f; } } public override Color? GetAlpha(Color lightColor) { return new Color(200 - Projectile.alpha, 200 - Projectile.alpha, 200 - Projectile.alpha, 200 - Projectile.alpha); } } }
0
0.834331
1
0.834331
game-dev
MEDIA
0.993835
game-dev
0.994156
1
0.994156
ethereum/ethereumj
4,179
ethereumj-core/src/main/java/org/ethereum/vm/trace/OpActions.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library 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. * * The ethereumJ library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import com.fasterxml.jackson.annotation.JsonInclude; import org.ethereum.vm.DataWord; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.ethereum.util.ByteUtil.toHexString; public class OpActions { @JsonInclude(JsonInclude.Include.NON_NULL) public static class Action { public enum Name { pop, push, swap, extend, write, put, remove, clear; } private Name name; private Map<String, Object> params; public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Map<String, Object> getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } Action addParam(String name, Object value) { if (value != null) { if (params == null) { params = new HashMap<>(); } params.put(name, value.toString()); } return this; } } private List<Action> stack = new ArrayList<>(); private List<Action> memory = new ArrayList<>(); private List<Action> storage = new ArrayList<>(); public List<Action> getStack() { return stack; } public void setStack(List<Action> stack) { this.stack = stack; } public List<Action> getMemory() { return memory; } public void setMemory(List<Action> memory) { this.memory = memory; } public List<Action> getStorage() { return storage; } public void setStorage(List<Action> storage) { this.storage = storage; } private static Action addAction(List<Action> container, Action.Name name) { Action action = new Action(); action.setName(name); container.add(action); return action; } public Action addStackPop() { return addAction(stack, Action.Name.pop); } public Action addStackPush(DataWord value) { return addAction(stack, Action.Name.push) .addParam("value", value); } public Action addStackSwap(int from, int to) { return addAction(stack, Action.Name.swap) .addParam("from", from) .addParam("to", to); } public Action addMemoryExtend(long delta) { return addAction(memory, Action.Name.extend) .addParam("delta", delta); } public Action addMemoryWrite(int address, byte[] data, int size) { return addAction(memory, Action.Name.write) .addParam("address", address) .addParam("data", toHexString(data).substring(0, size)); } public Action addStoragePut(DataWord key, DataWord value) { return addAction(storage, Action.Name.put) .addParam("key", key) .addParam("value", value); } public Action addStorageRemove(DataWord key) { return addAction(storage, Action.Name.remove) .addParam("key", key); } public Action addStorageClear() { return addAction(storage, Action.Name.clear); } }
0
0.679452
1
0.679452
game-dev
MEDIA
0.45177
game-dev
0.905186
1
0.905186
h33p/UNet-Controller
2,765
Assets/UnetController/Scripts/AnimationManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace GreenByteSoftware.UNetController { public class AnimationManager : MonoBehaviour { public Animator anim; public Controller controller; public float groundedMinTime = 0.2f; private float lastNotGrounded; private Results firstResult; private Results secondResult; private float callTime; private bool added; public Vector3 curSpeed; public string speedx = "SpeedX"; public string speedy = "SpeedY"; public string speedz = "SpeedZ"; public string grounded = "isGrounded"; public bool invertGrounded = false; public string crouching = "Crouching"; public string jump = "Jump"; private int t = 0; void Start () { if (!added) { controller.tickUpdate += this.TickUpdate; added = true; } } void OnEnable () { if (!added) { controller.tickUpdate += this.TickUpdate; added = true; } } void OnDisable () { if (added) { controller.tickUpdate -= this.TickUpdate; added = false; } t = 0; } void Update () { if (anim == null) { Debug.LogError ("No animator attached! Disabling."); this.enabled = false; return; } if (t < 2) return; float time = (Time.time - callTime) / (Time.fixedDeltaTime * controller.lSendUpdates); curSpeed = Vector3.Lerp (firstResult.speed, secondResult.speed, time); anim.SetFloat (speedx, curSpeed.x); anim.SetFloat (speedy, curSpeed.y); anim.SetFloat (speedz, curSpeed.z); if ((!(secondResult.flags & Flags.IS_GROUNDED) && firstResult.flags & Flags.IS_GROUNDED) || secondResult.flags & Flags.IS_GROUNDED) lastNotGrounded = Time.fixedTime; if (Time.fixedTime - lastNotGrounded > groundedMinTime) anim.SetBool (grounded, invertGrounded ? !(secondResult.flags & Flags.IS_GROUNDED) : secondResult.flags & Flags.IS_GROUNDED); else anim.SetBool (grounded, !invertGrounded); anim.SetBool (crouching, secondResult.flags & Flags.CROUCHED); } public void TickUpdate (Results res, bool inLagCompensation) { if (!this.enabled) return; if (inLagCompensation) { anim.Update(0); return; } if (controller.playbackMode) anim.speed = controller.playbackSpeed; if (t == 0) { firstResult = res; firstResult.speed = controller.myTransform.InverseTransformDirection (firstResult.speed); t++; } else { firstResult = secondResult; secondResult = res; secondResult.speed = controller.myTransform.InverseTransformDirection (secondResult.speed); t++; callTime = Time.fixedTime; if (secondResult.flags & Flags.JUMPED && firstResult.flags & Flags.IS_GROUNDED && !(firstResult.flags & Flags.JUMPED)) anim.SetTrigger (jump); } } } }
0
0.698713
1
0.698713
game-dev
MEDIA
0.978879
game-dev
0.92477
1
0.92477
bcserv/smlib
14,675
scripting/tests/test_compile-all.sp
/************************************************** * * SMLIB Testing Suite * * ************************************************ * * Warning: This plugin is only for testing if all * function stocks are compile-able without any * errors/warnings, do not load this on a production * server or it will likely crash it. * */ // enforce semicolons after each code statement #pragma semicolon 1 #include <sourcemod> #include <smlib> #define PLUGIN_VERSION "1.0" /***************************************************************** P L U G I N I N F O *****************************************************************/ public Plugin:myinfo = { name = "smlib Testing Suite", author = "Berni, Chanz", description = "Plugin by Berni", version = PLUGIN_VERSION, url = "" } /***************************************************************** G L O B A L V A R S *****************************************************************/ // ConVar Handles // Misc /***************************************************************** F O R W A R D P U B L I C S *****************************************************************/ public OnPluginStart() { new arr[1], String:arr_str[1][1], arr_4[4]; decl Float:vec[3]; decl String:buf[1], String:buf_10[10], String:twoDimStrArr[1][1]; new variable; new Handle:handle; // File: arrays.inc Array_FindValue(arr, sizeof(arr), 1); Array_FindString(arr_str, sizeof(arr_str), ""); Array_FindLowestValue(arr, sizeof(arr)); Array_FindHighestValue(arr, sizeof(arr)); Array_Fill(arr, sizeof(arr), 0); Array_Copy(arr, arr, 1); // File: clients.inc Client_SetHideHud(0, 0); Client_IsValid(0); Client_IsIngame(0); Client_IsIngameAuthorized(0); Client_FindBySteamId(""); Client_FindByName(""); Client_GetObserverMode(0); Client_SetObserverMode(0, Obs_Mode:0); Client_GetObserverLastMode(0); Client_SetObserverLastMode(0, Obs_Mode:0); Client_GetViewOffset(0, vec); Client_SetViewOffset(0, vec); Client_GetObserverTarget(0); Client_SetObserverTarget(0, 0); Client_GetFOV(0); Client_SetFOV(0, 0); Client_DrawViewModel(0); Client_SetDrawViewModel(0, true); Client_SetThirdPersonMode(0); Client_IsInThirdPersonMode(0); Client_ScreenFade(0, 0, 0); Client_GetClones(0, arr); Client_IsOnLadder(0); Client_GetWaterLevel(0); Client_GetSuitSprintPower(0); Client_SetSuitSprintPower(0, 0.0); Client_GetCount(); Client_GetFakePing(0); Client_GetClosestToClient(0); Client_GetLastPlaceName(0, buf, sizeof(buf)); Client_GetScore(0); Client_SetScore(0, 0); Client_GetDeaths(0); Client_SetDeaths(0, 0); Client_GetArmor(0); Client_SetArmor(0, 0); Client_GetSuitPower(0); Client_SetSuitPower(0, 0.0); Client_GetActiveDevices(0); Client_GetNextDecalTime(0); Client_CanSprayDecal(0); Client_GetVehicle(0); Client_IsInVehicle(0); Client_RemoveAllDecals(0); Client_ExitVehicle(0); Client_RawAudio(0, 0, ""); Client_RawAudioToAll(0, ""); Client_Impulse(0, 0); Client_GetWeaponsOffset(0); Client_GetActiveWeapon(0); Client_GetActiveWeaponName(0, buf, sizeof(buf)); Client_SetActiveWeapon(0, 0); Client_ChangeWeapon(0, ""); Client_ChangeToLastWeapon(0); Client_GetLastActiveWeapon(0); Client_GetLastActiveWeaponName(0, buf, sizeof(buf)); Client_SetLastActiveWeapon(0, 0); Client_EquipWeapon(0, 0); Client_DetachWeapon(0, 0); Client_GiveWeapon(0, ""); Client_GiveWeaponAndAmmo(0, ""); Client_RemoveWeapon(0, ""); Client_RemoveAllWeapons(0, ""); Client_HasWeapon(0, ""); Client_GetWeapon(0, ""); Client_GetWeaponBySlot(0, 0); Client_GetDefaultWeapon(0); Client_GetDefaultWeaponName(0, buf, sizeof(buf)); Client_GetFirstWeapon(0); Client_GetWeaponCount(0); Client_IsReloading(0); Client_SetWeaponClipAmmo(0, ""); Client_GetWeaponPlayerAmmo(0, ""); Client_GetWeaponPlayerAmmoEx(0, 0); Client_SetWeaponPlayerAmmo(0, ""); Client_SetWeaponPlayerAmmoEx(0, 0); Client_SetWeaponAmmo(0, ""); Client_GetNextWeapon(0, variable); Client_PrintHintText(0, ""); Client_PrintHintTextToAll(""); Client_PrintKeyHintText(0, ""); Client_PrintKeyHintTextToAll(""); Client_PrintToChatRaw(0, ""); Client_PrintToChat(0, false, ""); Client_PrintToChatAll(false, ""); Client_PrintToChatEx({ 0 }, 0, false, ""); Client_Shake(0); Client_IsAdmin(0); Client_HasAdminFlags(0); Client_IsInAdminGroup(0, ""); Client_IsLookingAtWall(0); Client_GetClass(0); Client_SetClass(0, 0); Client_GetButtons(0); Client_SetButtons(0, 0); Client_AddButtons(0, 0); Client_RemoveButtons(0, 0); Client_ClearButtons(0); Client_HasButtons(0, 0); Client_GetChangedButtons(0); Client_SetMaxSpeed(0, 0.0); Client_SetScreenOverlay(0, ""); Client_SetScreenOverlayForAll(""); Client_Mute(0); Client_UnMute(0); Client_IsMuted(0); Client_PrintToConsole(0, ""); Client_Print(0, ClientHudPrint:0, ""); Client_PrintToChatExclude(0); Client_Reply(0, ""); Client_MatchesFilter(0, 0); Client_Get({ 0 }, 0); Client_GetRandom(0); Client_GetNext(0); Client_GetMapTime(0); Client_GetMoney(0); Client_SetMoney(0, 0); Client_GetObservers(0, { 0 }); Client_GetPlayersInRadius(0, arr, 0.0); Client_GetNextObserver(0); Client_GetPlayerManager(); Client_SetPing(0, 0); Client_PrintToTopExclude(0); Client_PrintToTopRaw(0,0,0,0,0,0.0,""); Client_PrintToTop(0,0,0,0,0,0.0,""); Client_PrintToTopAll(0,0,0,0,0.0,""); Client_PrintToTopEx({ 0 },1,0,0,0,0,0.0,""); Client_ShowScoreboard(0); // File: colors.inc Color_ChatSetSubject(0); Color_ChatGetSubject(); Color_ChatClearSubject(); Color_ParseChatText("", "", 0); Color_TagToCode("", variable, buf_10); Color_StripFromChatText("", "", 0); // File: convars.inc ConCommand_HasFlags("", 0); ConCommand_AddFlags("", 0); ConCommand_RemoveFlags("", 0); // File: convars.inc Convar_HasFlags(INVALID_HANDLE, 0); Convar_AddFlags(INVALID_HANDLE, 0); Convar_RemoveFlags(INVALID_HANDLE, 0); Convar_IsValidName(""); // File: crypt.inc Crypt_Base64Encode("", buf, sizeof(buf)); Crypt_Base64Decode("", buf, sizeof(buf)); Crypt_Base64MimeToUrl("", buf, sizeof(buf)); Crypt_Base64UrlToMime("", buf, sizeof(buf)); Crypt_MD5("", buf, sizeof(buf)); Crypt_RC4Encode("", "", buf, sizeof(buf)); Crypt_RC4EncodeBinary("", 0, "", buf, sizeof(buf)); // File: debug.inc Debug_FloatArray(vec); // File: dynarrays.inc DynArray_GetBool(INVALID_HANDLE, 0); // File: edicts.inc Edict_FindByName(""); Edict_FindByHammerId(0); Edict_GetClosest(vec); Edict_GetClosestToEdict(0); // File: effects.inc Effect_DissolveEntity(0); Effect_DissolvePlayerRagDoll(0); Effect_Fade(0); Effect_FadeIn(0); Effect_FadeOut(0); Effect_DrawBeamBox(arr, 1, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawBeamBoxToAll(NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawBeamBoxToClient(0, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawBeamBoxRotatableToClient(0, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawBeamBoxRotatableToAll(NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawBeamBoxRotatable(arr, 1, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawAxisOfRotationToClient(0, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawAxisOfRotationToAll(NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_DrawAxisOfRotation(arr, 1, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR, 0, 0); Effect_EnvSprite(NULL_VECTOR,0); // File: entities.inc Entity_IsValid(0); Entity_FindByName(""); Entity_FindByHammerId(0); Entity_FindByClassName(0, ""); Entity_ClassNameMatches(0, ""); Entity_NameMatches(0, ""); Entity_GetName(0, buf, sizeof(buf)); Entity_SetName(0, ""); Entity_GetClassName(0, buf, sizeof(buf)); Entity_SetClassName(0, ""); Entity_GetTargetName(0, buf, sizeof(buf)); Entity_SetTargetName(0, ""); Entity_GetGlobalName(0, buf, sizeof(buf)); Entity_SetGlobalName(0, ""); Entity_GetParentName(0, buf, sizeof(buf)); Entity_SetParentName(0, ""); Entity_GetHammerId(0); Entity_GetRadius(0); Entity_SetRadius(0, 0.0); Entity_GetMinSize(0, vec); Entity_SetMinSize(0, vec); Entity_GetMaxSize(0, vec); Entity_SetMaxSize(0, vec); Entity_SetMinMaxSize(0, vec, vec); Entity_GetSpawnFlags(0); Entity_SetSpawnFlags(0, 0); Entity_AddSpawnFlags(0, 0); Entity_RemoveSpawnFlags(0, 0); Entity_ClearSpawnFlags(0); Entity_HasSpawnFlags(0, 0); Entity_GetEFlags(0); Entity_SetEFlags(0, Entity_Flags:0); Entity_AddEFlags(0, Entity_Flags:0); Entity_RemoveEFlags(0, Entity_Flags:0); Entity_HasEFlags(0, Entity_Flags:0); Entity_MarkSurrBoundsDirty(0); Entity_GetFlags(0); Entity_SetFlags(0, 0); Entity_AddFlags(0, 0); Entity_RemoveFlags(0, 0); Entity_ToggleFlag(0, 0); Entity_ClearFlags(0); Entity_GetSolidFlags(0); Entity_SetSolidFlags(0, SolidFlags_t:0); Entity_AddSolidFlags(0, SolidFlags_t:0); Entity_RemoveSolidFlags(0, SolidFlags_t:0); Entity_ClearSolidFlags(0); Entity_SolidFlagsSet(0, SolidFlags_t:0); Entity_GetSolidType(0); Entity_SetSolidType(0, SolidType_t:0); Entity_IsSolid(0); Entity_GetModel(0, buf, sizeof(buf)); Entity_SetModel(0, ""); Entity_GetModelIndex(0); Entity_SetModelIndex(0, 0); Entity_SetMaxSpeed(0, 0.0); Entity_GetCollisionGroup(0); Entity_SetCollisionGroup(0, Collision_Group_t:0); Entity_GetAbsOrigin(0, vec); Entity_SetAbsOrigin(0, vec); Entity_GetAbsAngles(0, vec); Entity_SetAbsAngles(0, vec); Entity_GetLocalVelocity(0, vec); Entity_SetLocalVelocity(0, vec); Entity_GetBaseVelocity(0, vec); Entity_SetBaseVelocity(0, vec); Entity_GetAbsVelocity(0, vec); Entity_SetAbsVelocity(0, vec); Entity_IsLocked(0); Entity_Lock(0); Entity_UnLock(0); Entity_GetHealth(0); Entity_SetHealth(0, 0); Entity_GetMaxHealth(0); Entity_SetMaxHealth(0, 0); Entity_AddHealth(0, 0); Entity_GetDistance(0, 0); Entity_GetDistanceOrigin(0, vec); Entity_InRange(0, 0, 0.0); Entity_EnableMotion(0); Entity_DisableMotion(0); Entity_Freeze(0); Entity_UnFreeze(0); Entity_PointAtTarget(0, 0); Entity_PointHurtAtTarget(0, 0); Entity_IsPlayer(0); Entity_Create(""); Entity_Kill(0); Entity_KillAllByClassName(""); Entity_GetOwner(0); Entity_SetOwner(0, 0); Entity_GetGroundEntity(0); Entity_Hurt(0, 0); Entity_GetParent(0); Entity_ClearParent(0); Entity_SetParent(0, 0); Entity_ChangeOverTime(0, 0.1, INVALID_FUNCTION); Entity_GetNextChild(0); Entity_GetMoveDirection(0,NULL_VECTOR); Entity_SetMoveDirection(0,NULL_VECTOR); Entity_GetForceClose(0); Entity_SetForceClose(0,true); Entity_GetSpeed(0); Entity_SetSpeed(0,0.0); Entity_GetBlockDamage(0); Entity_SetBlockDamage(0,0.0); Entity_IsDisabled(0); Entity_Disable(0); Entity_Enable(0); Entity_SetTakeDamage(0,0); Entity_GetTakeDamage(0); Entity_SetMinHealthDamage(0,0); Entity_GetMinHealthDamage(0); Entity_GetRenderColor(0, arr_4); Entity_SetRenderColor(0, 0, 0, 0, 0); Entity_AddOutput(0, ""); Entity_TakeHealth(0, 0); // File: files.inc File_GetBaseName("", buf, sizeof(buf)); File_GetDirName("", buf, sizeof(buf)); File_GetFileName("", buf, sizeof(buf)); File_GetExtension("", buf, sizeof(buf)); File_AddToDownloadsTable(""); File_ReadDownloadList(""); File_LoadTranslations(""); File_ToString("", "", 0); File_StringToFile("", ""); File_Copy("", ""); File_CopyRecursive("", ""); // File: game.inc Game_End(); Game_EndRound(); // File: general.inc PrecacheMaterial(""); IsMaterialPrecached(""); PrecacheParticleSystem(""); IsParticleSystemPrecached(""); FindStringIndexByTableName("", ""); FindStringIndex2(0, ""); LongToIP(0, buf, sizeof(buf)); IPToLong(""); IsIPLocal(0); ClearHandle(handle); // File: math.inc Math_Abs(0); Math_VectorsEqual(vec, vec); Math_Min(0, 0); Math_Max(0, 0); Math_Clamp(0, 0, 0); Math_IsInBounds(0, 0, 0); Math_GetRandomInt(0, 0); Math_GetRandomFloat(0.0, 0.0); Math_GetPercentage(0, 0); Math_GetPercentageFloat(0.0, 0.0); Math_MoveVector(vec, vec, 0.0, vec); Math_UnitsToMeters(0.0); Math_UnitsToFeet(0.0); Math_UnitsToCentimeters(0.0); Math_UnitsToKilometers(0.0); Math_UnitsToMiles(0.0); Math_RotateVector(vec, vec, vec); Math_MakeVector(0.0, 0.0, 0.0, vec); Math_Overflow(0, 0, 0); // File: menus.inc Menu_AddIntItem(INVALID_HANDLE, 0, ""); Menu_GetIntItem(INVALID_HANDLE, 0); // File: server.inc Server_GetIP(); Server_GetIPString(buf, sizeof(buf)); Server_GetPort(); Server_GetHostName(buf, sizeof(buf)); // File: sql.inc SQL_TQueryF(INVALID_HANDLE, INVALID_FUNCTION, 0, DBPrio_Normal, ""); SQL_FetchIntByName(INVALID_HANDLE, ""); SQL_FetchBoolByName(INVALID_HANDLE, ""); SQL_FetchFloatByName(INVALID_HANDLE, ""); SQL_FetchStringByName(INVALID_HANDLE, "", buf, sizeof(buf)); // File: strings.inc String_IsNumeric(""); String_Trim("", buf, sizeof(buf)); String_RemoveList(buf, twoDimStrArr, sizeof(twoDimStrArr)); String_ToLower(buf, buf, sizeof(buf)); String_ToUpper(buf, buf, sizeof(buf)); String_GetRandom(buf, sizeof(buf)); String_StartsWith("", ""); String_EndsWith("", ""); // File: teams.inc Team_HaveAllPlayers(); Team_GetClientCount(0); Team_GetClientCounts(variable, variable); Team_GetName(0, buf, sizeof(buf)); Team_SetName(0, ""); Team_GetScore(0); Team_SetScore(0, 0); Team_EdictGetNum(0); Team_IsValid(0); Team_EdictIsValid(0); Team_GetEdict(0); Team_GetAnyClient(0); // File: 0s.inc Vehicle_GetDriver(0); Vehicle_HasDriver(0); Vehicle_ExitDriver(0); Vehicle_TurnOn(0); Vehicle_TurnOff(0); Vehicle_Lock(0); Vehicle_Unlock(0); Vehicle_IsValid(0); Vehicle_GetScript(0, buf, sizeof(buf)); Vehicle_SetScript(0, ""); // File: 0s.inc Weapon_GetOwner(0); Weapon_SetOwner(0, 0); Weapon_IsValid(0); Weapon_Create("", vec, vec); Weapon_CreateForOwner(0, ""); Weapon_GetSubType(0); Weapon_IsReloading(0); Weapon_GetState(0); Weapon_FiresUnderWater(0); Weapon_SetFiresUnderWater(0); Weapon_FiresUnderWaterAlt(0); Weapon_SetFiresUnderWaterAlt(0); Weapon_GetPrimaryAmmoType(0); Weapon_GetSecondaryAmmoType(0); Weapon_SetSecondaryAmmoType(0,0); Weapon_SetPrimaryAmmoType(0,0); Weapon_GetPrimaryClip(0); Weapon_SetPrimaryClip(0, 0); Weapon_GetSecondaryClip(0); Weapon_SetSecondaryClip(0, 0); Weapon_SetClips(0, 0, 0); Weapon_GetPrimaryAmmoCount(0); Weapon_SetPrimaryAmmoCount(0, 0); Weapon_GetSecondaryAmmoCount(0); Weapon_SetSecondaryAmmoCount(0, 0); Weapon_SetAmmoCounts(0, 0, 0); Weapon_GetViewModelIndex(0); Weapon_SetViewModelIndex(0, 0); // File: world.inc World_GetMaxs(vec); } /**************************************************************** C A L L B A C K F U N C T I O N S ****************************************************************/ /***************************************************************** P L U G I N F U N C T I O N S *****************************************************************/
0
0.82439
1
0.82439
game-dev
MEDIA
0.828173
game-dev
0.504816
1
0.504816
methusalah/OpenRTS
4,990
core/src/model/builders/entity/actors/ParticleActorBuilder.java
/* * To change this template, choose Tools | Templates and open the template in the editor. */ package model.builders.entity.actors; import geometry.math.AngleUtil; import java.awt.Color; import model.battlefield.actors.Actor; import model.battlefield.actors.ParticleActor; import model.builders.entity.definitions.DefElement; import model.builders.entity.definitions.Definition; /** * @author Benoît */ public class ParticleActorBuilder extends ActorBuilder { private static final String SPRITE_PATH = "SpritePath"; private static final String NB_COL = "NbCol"; private static final String NB_ROW = "NbRow"; private static final String EMISSION_NODE = "EmissionBone"; private static final String DIRECTION_NODE = "DirectionBone"; private static final String VELOCITY = "Velocity"; private static final String FANNING = "Fanning"; private static final String MAX_COUNT = "MaxCount"; private static final String PER_SECOND = "PerSecond"; private static final String DURATION = "Duration"; private static final String START_SIZE = "StartSize"; private static final String END_SIZE = "EndSize"; private static final String START_COLOR = "StartColor"; private static final String END_COLOR = "EndColor"; private static final String MIN_LIFE = "MinLife"; private static final String MAX_LIFE = "MaxLife"; private static final String GRAVITY = "Gravity"; private static final String FACING = "Facing"; private static final String FACING_VELOCITY = "Velocity"; private static final String FACING_HORIZONTAL = "Horizontal"; private static final String ADD = "Add"; private static final String START_VARIATION = "StartVariation"; private static final String ROTATION_SPEED = "RotationSpeed"; private static final String RED = "R"; private static final String GREEN = "G"; private static final String BLUE = "B"; private static final String ALPHA = "A"; private String spritePath; private int nbCol = 1; private int nbRow = 1; private String emissionBone; private String directionBone; private double velocity = 0; private double fanning = 0; private boolean randomSprite = false; private int maxCount; private int perSecond; private double duration = Double.MAX_VALUE; private double startSize; private double endSize; private Color startColor; private Color endColor; private double minLife; private double maxLife; private boolean gravity = false; private ParticleActor.Facing facing = ParticleActor.Facing.Camera; private boolean add = true; private double startVariation = 0; private double rotationSpeed; public ParticleActorBuilder(Definition def) { super(def); for (DefElement de : def.getElements()) { switch (de.name) { case TYPE: case TRIGGER: case ACTOR_LIST: break; case SPRITE_PATH: spritePath = de.getVal(); break; case NB_COL: nbCol = de.getIntVal(); break; case NB_ROW: nbRow = de.getIntVal(); break; case EMISSION_NODE: emissionBone = de.getVal(); break; case DIRECTION_NODE: directionBone = de.getVal(); break; case VELOCITY: velocity = de.getDoubleVal(); break; case FANNING: fanning = de.getDoubleVal(); break; case MAX_COUNT: maxCount = de.getIntVal(); break; case PER_SECOND: perSecond = de.getIntVal(); break; case DURATION: duration = de.getDoubleVal(); break; case START_SIZE: startSize = de.getDoubleVal(); break; case END_SIZE: endSize = de.getDoubleVal(); break; case START_COLOR: startColor = new Color(de.getIntVal(RED), de.getIntVal(GREEN), de.getIntVal(BLUE), de.getIntVal(ALPHA)); break; case END_COLOR: endColor = new Color(de.getIntVal(RED), de.getIntVal(GREEN), de.getIntVal(BLUE), de.getIntVal(ALPHA)); break; case MIN_LIFE: minLife = de.getDoubleVal(); break; case MAX_LIFE: maxLife = de.getDoubleVal(); break; case GRAVITY: gravity = de.getBoolVal(); break; case FACING: switch (de.getVal()) { case FACING_HORIZONTAL: facing = ParticleActor.Facing.Horizontal; break; case FACING_VELOCITY: facing = ParticleActor.Facing.Velocity; break; } break; case ADD: add = de.getBoolVal(); break; case START_VARIATION: startVariation = de.getDoubleVal(); break; case ROTATION_SPEED: rotationSpeed = AngleUtil.toRadians(de.getDoubleVal()); break; default: printUnknownElement(de.name); } } } @Override public Actor build(String trigger, Actor parent) { Actor res = new ParticleActor(spritePath, nbCol, nbRow, emissionBone, directionBone, velocity, fanning, randomSprite, maxCount, perSecond, duration, startSize, endSize, startColor, endColor, minLife, maxLife, rotationSpeed, gravity, facing, add, startVariation, parent, trigger, childrenTriggers, childrenActorBuilders); res.debbug_id = getId(); return res; } }
0
0.858949
1
0.858949
game-dev
MEDIA
0.85875
game-dev
0.972918
1
0.972918
MACURD/Hearthbuddy8.7.6
964
Routines/DefaultRoutine/Silverfish/cards/1001-冰封王座的骑士/Sim_ICC_833h.cs
using System; using System.Collections.Generic; using System.Text; namespace HREngine.Bots { class Sim_ICC_833h: SimTemplate //* 冰冷触摸 Icy Touch //<b>Hero Power</b> Deal $1 damage. If this kills a minion, summon a Water Elemental. //<b>英雄技能</b>造成$1点伤害。如果该英雄技能消灭了一个随从,则召唤一个水元素。 { CardDB.Card kid = CardDB.Instance.getCardDataFromID(CardDB.cardIDEnum.CS2_033); public override void onCardPlay(Playfield p, bool ownplay, Minion target, int choice) { int dmg = (ownplay) ? p.getHeroPowerDamage(1) : p.getEnemyHeroPowerDamage(1); p.minionGetDamageOrHeal(target, dmg); int place = (ownplay) ? p.ownMinions.Count : p.enemyMinions.Count; if (target.Hp <= 0) p.callKid(kid, place, ownplay); } public override PlayReq[] GetPlayReqs() { return new PlayReq[] { new PlayReq(CardDB.ErrorType2.REQ_TARGET_TO_PLAY), }; } } }
0
0.974612
1
0.974612
game-dev
MEDIA
0.984653
game-dev
0.889541
1
0.889541
Leystryku/leysourceengineclient
8,309
deps/osw/ISteamUserStats005.h
//========================== Open Steamworks ================================ // // This file is part of the Open Steamworks project. All individuals associated // with this project do not claim ownership of the contents // // The code, comments, and all related files, projects, resources, // redistributables included with this project are Copyright Valve Corporation. // Additionally, Valve, the Valve logo, Half-Life, the Half-Life logo, the // Lambda logo, Steam, the Steam logo, Team Fortress, the Team Fortress logo, // Opposing Force, Day of Defeat, the Day of Defeat logo, Counter-Strike, the // Counter-Strike logo, Source, the Source logo, and Counter-Strike Condition // Zero are trademarks and or registered trademarks of Valve Corporation. // All other trademarks are property of their respective owners. // //============================================================================= #ifndef ISTEAMUSERSTATS005_H #define ISTEAMUSERSTATS005_H #ifdef _WIN32 #pragma once #endif #include "SteamTypes.h" #include "UserStatsCommon.h" //----------------------------------------------------------------------------- // Purpose: Functions for accessing stats, achievements, and leaderboard information //----------------------------------------------------------------------------- abstract_class ISteamUserStats005 { public: // Ask the server to send down this user's data and achievements for this game virtual bool RequestCurrentStats() = 0; // Data accessors #if !(defined(_WIN32) && defined(__GNUC__)) virtual bool GetStat( const char *pchName, int32 *pData ) = 0; virtual bool GetStat( const char *pchName, float *pData ) = 0; #else virtual bool GetStat( const char *pchName, float *pData ) = 0; virtual bool GetStat( const char *pchName, int32 *pData ) = 0; #endif // Set / update data #if !(defined(_WIN32) && defined(__GNUC__)) virtual bool SetStat( const char *pchName, int32 nData ) = 0; virtual bool SetStat( const char *pchName, float fData ) = 0; #else virtual bool SetStat( const char *pchName, float fData ) = 0; virtual bool SetStat( const char *pchName, int32 nData ) = 0; #endif virtual bool UpdateAvgRateStat( const char *pchName, float flCountThisSession, double dSessionLength ) = 0; // Achievement flag accessors virtual bool GetAchievement( const char *pchName, bool *pbAchieved ) = 0; virtual bool SetAchievement( const char *pchName ) = 0; virtual bool ClearAchievement( const char *pchName ) = 0; // Store the current data on the server, will get a callback when set // And one callback for every new achievement virtual bool StoreStats() = 0; // Achievement / GroupAchievement metadata // Gets the icon of the achievement, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set virtual int GetAchievementIcon( const char *pchName ) = 0; // Get general attributes (display name / text, etc) for an Achievement virtual const char *GetAchievementDisplayAttribute( const char *pchName, const char *pchKey ) = 0; // Achievement progress - triggers an AchievementProgress callback, that is all. // Calling this w/ N out of N progress will NOT set the achievement, the game must still do that. virtual bool IndicateAchievementProgress( const char *pchName, uint32 nCurProgress, uint32 nMaxProgress ) = 0; // Friends stats & achievements // downloads stats for the user // returns a UserStatsReceived_t received when completed // if the other user has no stats, UserStatsReceived_t.m_eResult will be set to k_EResultFail // these stats won't be auto-updated; you'll need to call RequestUserStats() again to refresh any data virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; // requests stat information for a user, usable after a successful call to RequestUserStats() #if !(defined(_WIN32) && defined(__GNUC__)) virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; #else virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; #endif virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; // Reset stats virtual bool ResetAllStats( bool bAchievementsToo ) = 0; // Leaderboard functions // asks the Steam back-end for a leaderboard by name, and will create it if it's not yet // This call is asynchronous, with the result returned in LeaderboardFindResult_t virtual SteamAPICall_t FindOrCreateLeaderboard( const char *pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType ) = 0; // as above, but won't create the leaderboard if it's not found // This call is asynchronous, with the result returned in LeaderboardFindResult_t virtual SteamAPICall_t FindLeaderboard( const char *pchLeaderboardName ) = 0; // returns the name of a leaderboard virtual const char *GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the total number of entries in a leaderboard, as of the last request virtual int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the sort method of the leaderboard virtual ELeaderboardSortMethod GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the display type of the leaderboard virtual ELeaderboardDisplayType GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) = 0; // Asks the Steam back-end for a set of rows in the leaderboard. // This call is asynchronous, with the result returned in LeaderboardScoresDownloaded_t // LeaderboardScoresDownloaded_t will contain a handle to pull the results from GetDownloadedLeaderboardEntries() (below) // You can ask for more entries than exist, and it will return as many as do exist. // k_ELeaderboardDataRequestGlobal requests rows in the leaderboard from the full table, with nRangeStart & nRangeEnd in the range [1, TotalEntries] // k_ELeaderboardDataRequestGlobalAroundUser requests rows around the current user, nRangeStart being negate // e.g. DownloadLeaderboardEntries( hLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -3, 3 ) will return 7 rows, 3 before the user, 3 after // k_ELeaderboardDataRequestFriends requests all the rows for friends of the current user virtual SteamAPICall_t DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) = 0; // Returns data about a single leaderboard entry // use a for loop from 0 to LeaderboardScoresDownloaded_t::m_cEntryCount to get all the downloaded entries // e.g. // void OnLeaderboardScoresDownloaded( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded ) // { // for ( int index = 0; index < pLeaderboardScoresDownloaded->m_cEntryCount; index++ ) // { // LeaderboardEntry_t leaderboardEntry; // int32 details[3]; // we know this is how many we've stored previously // GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries, index, &leaderboardEntry, details, 3 ); // assert( leaderboardEntry.m_cDetails == 3 ); // ... // } // once you've accessed all the entries, the data will be free'd, and the SteamLeaderboardEntries_t handle will become invalid virtual bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry001_t *pLeaderboardEntry, int32 *pDetails, int cDetailsMax ) = 0; // Uploads a user score to the Steam back-end. // This call is asynchronous, with the result returned in LeaderboardScoreUploaded_t // If the score passed in is no better than the existing score this user has in the leaderboard, then the leaderboard will not be updated. // Details are extra game-defined information regarding how the user got that score // pScoreDetails points to an array of int32's, cScoreDetailsCount is the number of int32's in the list virtual SteamAPICall_t UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, int32 nScore, int32 *pScoreDetails, int cScoreDetailsCount ) = 0; }; #endif // ISTEAMUSERSTATS005_H
0
0.914965
1
0.914965
game-dev
MEDIA
0.509599
game-dev
0.74973
1
0.74973
MergHQ/CRYENGINE
3,185
Code/CryEngine/CryAction/SharedParams/SharedParamsTypeInfo.h
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Shared parameters type information. ------------------------------------------------------------------------- History: - 15:07:2010: Created by Paul Slinger *************************************************************************/ #ifndef __SHAREDPARAMSTYPEINFO_H__ #define __SHAREDPARAMSTYPEINFO_H__ #if _MSC_VER > 1000 #pragma once #endif #include <CryString/StringUtils.h> #ifdef _DEBUG #define DEBUG_SHARED_PARAMS_TYPE_INFO 1 #else #define DEBUG_SHARED_PARAMS_TYPE_INFO 0 #endif //_DEBUG //////////////////////////////////////////////////////////////////////////////////////////////////// // Shared parameters type information class. //////////////////////////////////////////////////////////////////////////////////////////////////// class CSharedParamsTypeInfo { public: CSharedParamsTypeInfo(size_t size, const char* pName, const char* pFileName, uint32 line) : m_size(size) { if (pName) { const size_t length = strlen(pName); size_t pos = 0; if (length > sizeof(m_name) - 1) { pos = length - (sizeof(m_name) - 1); } cry_strcpy(m_name, pName + pos); } else { m_name[0] = '\0'; } if (pFileName) { const size_t length = strlen(pFileName); size_t pos = 0; if (length > sizeof(m_fileName) - 1) { pos = length - (sizeof(m_fileName) - 1); } cry_strcpy(m_fileName, pFileName + pos); } else { m_fileName[0] = '\0'; } m_line = line; CryFixedStringT<256> temp; temp.Format("%" PRISIZE_T "%s%s%u", size, m_name, m_fileName, m_line); m_uniqueId = CryStringUtils::CalculateHash(temp.c_str()); } inline size_t GetSize() const { return m_size; } inline const char* GetName() const { return m_name; } inline const char* GetFileName() const { return m_fileName; } inline uint32 GetLine() const { return m_line; } inline uint32 GetUniqueId() const { return m_uniqueId; } inline bool operator==(const CSharedParamsTypeInfo& right) const { #if DEBUG_SHARED_PARAMS_TYPE_INFO if (m_uniqueId == right.m_uniqueId) { CRY_ASSERT(m_size == right.m_size); CRY_ASSERT(!strcmp(m_name, right.m_name)); CRY_ASSERT(!strcmp(m_fileName, right.m_fileName)); CRY_ASSERT(m_line == right.m_line); } #endif //DEBUG_SHARED_PARAMS_TYPE_INFO return m_uniqueId == right.m_uniqueId; } inline bool operator!=(const CSharedParamsTypeInfo& right) const { #if DEBUG_SHARED_PARAMS_TYPE_INFO if (m_uniqueId == right.m_uniqueId) { CRY_ASSERT(m_size == right.m_size); CRY_ASSERT(!strcmp(m_name, right.m_name)); CRY_ASSERT(!strcmp(m_fileName, right.m_fileName)); CRY_ASSERT(m_line == right.m_line); } #endif //DEBUG_SHARED_PARAMS_TYPE_INFO return m_uniqueId != right.m_uniqueId; } private: size_t m_size; char m_name[64]; char m_fileName[64]; uint32 m_line; uint32 m_uniqueId; }; #undef DEBUG_SHARED_PARAMS_TYPE_INFO #endif //__SHAREDPARAMSTYPEINFO_H__
0
0.941212
1
0.941212
game-dev
MEDIA
0.360489
game-dev
0.899808
1
0.899808
dengzibiao/moba
3,164
Assets/Script/Parse/TaskRewardNode.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using Tianyu; using System; /// <summary> /// 任务奖励 (主线 日常 悬赏...) /// </summary> public class TaskRewardNode : FSDataNodeBase { private int id; private int[,] itemArr; private int taskType; private int gold; private int diamond; private int zhanduiExp; private int heroExp; private int xuanshangGold; /// <summary> /// 奖励id /// </summary> public int Id { get { return id; } set { id = value; } } /// <summary> /// 类型 /// </summary> public int TaskType { get { return taskType; } set { taskType = value; } } /// <summary> /// 金币 /// </summary> public int Gold { get { return gold; } set { gold = value; } } /// <summary> /// 钻石 /// </summary> public int Diamond { get { return diamond; } set { diamond = value; } } /// <summary> /// 战队经验 /// </summary> public int ZhanduiExp { get { return zhanduiExp; } set { zhanduiExp = value; } } /// <summary> /// 英雄经验 /// </summary> public int HeroExp { get { return heroExp; } set { heroExp = value; } } /// <summary> /// 悬赏币 /// </summary> public int XuanshangGold { get { return xuanshangGold; } set { xuanshangGold = value; } } /// <summary> /// 奖励物品 /// </summary> public int[,] ItemArr { get { return itemArr; } set { itemArr = value; } } public override void parseJson(object jd) { Dictionary<string, object> item = (Dictionary<string, object>)jd; id = int.Parse(item["id"].ToString()); if (item.ContainsKey("item") && item["item"] != null) { object[] nodeCond = (object[])item["item"]; ItemArr = new int[nodeCond.Length, 2]; if (nodeCond.Length > 0) { for (int i = 0; i < nodeCond.Length; i++) { int[] node = (int[])nodeCond[i]; for (int j = 0; j < node.Length; j++) { ItemArr[i, j] = node[j]; } } } } taskType = int.Parse(item["type"].ToString()); gold = int.Parse(item["114000100"].ToString()); diamond = int.Parse(item["114000200"].ToString()); zhanduiExp = int.Parse(item["114000300"].ToString()); heroExp = int.Parse(item["114000400"].ToString()); xuanshangGold = int.Parse(item["114000800"].ToString()); } }
0
0.535043
1
0.535043
game-dev
MEDIA
0.925701
game-dev
0.842023
1
0.842023
freeorion/freeorion
3,791
default/scripting/specials/planet/growth/growth.macros
STANDARD_INDUSTRY_BOOST '''EffectsGroup description = "GROWTH_SPECIAL_INDUSTRY_BOOST" scope = Source activation = Focus type = "FOCUS_INDUSTRY" priority = [[TARGET_AFTER_2ND_SCALING_PRIORITY]] effects = SetTargetIndustry value = Value + Target.Population * (NamedReal name = "GROWTH_SPECIAL_TARGET_INDUSTRY_PERPOP" value = 1.0 * [[INDUSTRY_PER_POP]]) ''' // argument 1 is the name of the used stacking group POPULATION_BOOST_ORGANIC ''' EffectsGroup scope = And [ Planet OwnedBy empire = Source.Owner HasTag name = "ORGANIC" ResourceSupplyConnected empire = Source.Owner condition = Source ] activation = Focus type = "FOCUS_GROWTH" stackinggroup = "@1@_STACK" accountinglabel = "GROWTH_SPECIAL_LABEL" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize EffectsGroup description = "GROWTH_SPECIAL_POPULATION_ORGANIC_INCREASE" scope = And [ Source HasTag name = "ORGANIC" ] stackinggroup = "@1@_STACK" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize // Provides the bonus locally, no matter the focus ''' // argument 1 is the name of the used stacking group POPULATION_BOOST_ROBOTIC ''' EffectsGroup scope = And [ Planet OwnedBy empire = Source.Owner HasTag name = "ROBOTIC" ResourceSupplyConnected empire = Source.Owner condition = Source ] activation = Focus type = "FOCUS_GROWTH" stackinggroup = "@1@_STACK" accountinglabel = "GROWTH_SPECIAL_LABEL" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize EffectsGroup description = "GROWTH_SPECIAL_POPULATION_ROBOTIC_INCREASE" scope = And [ Source HasTag name = "ROBOTIC" ] stackinggroup = "@1@_STACK" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize // Provides the bonus locally, no matter the focus ''' // argument 1 is the name of the used stacking group POPULATION_BOOST_LITHIC ''' EffectsGroup scope = And [ Planet OwnedBy empire = Source.Owner HasTag name = "LITHIC" ResourceSupplyConnected empire = Source.Owner condition = Source ] activation = Focus type = "FOCUS_GROWTH" stackinggroup = "@1@_STACK" accountinglabel = "GROWTH_SPECIAL_LABEL" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize EffectsGroup description = "GROWTH_SPECIAL_POPULATION_LITHIC_INCREASE" scope = And [ Source HasTag name = "LITHIC" ] stackinggroup = "@1@_STACK" priority = [[TARGET_POPULATION_AFTER_SCALING_PRIORITY]] effects = SetTargetPopulation value = Value + 1 * Target.HabitableSize // Provides the bonus locally, no matter the focus ''' #include "/scripting/macros/base_prod.macros" #include "/scripting/macros/priorities.macros"
0
0.822315
1
0.822315
game-dev
MEDIA
0.835894
game-dev
0.72848
1
0.72848
Citadel-Station-13/Citadel-Station-13
2,952
code/modules/surgery/cavity_implant.dm
/datum/surgery/cavity_implant name = "Cavity implant" steps = list(/datum/surgery_step/incise, /datum/surgery_step/clamp_bleeders, /datum/surgery_step/retract_skin, /datum/surgery_step/incise, /datum/surgery_step/handle_cavity, /datum/surgery_step/close) target_mobtypes = list(/mob/living/carbon/human, /mob/living/carbon/monkey) possible_locs = list(BODY_ZONE_CHEST) //handle cavity /datum/surgery_step/handle_cavity name = "implant item" accept_hand = 1 accept_any_item = 1 implements = list(/obj/item = 100) repeatable = TRUE time = 32 preop_sound = 'sound/surgery/organ1.ogg' success_sound = 'sound/surgery/organ2.ogg' var/obj/item/IC = null /datum/surgery_step/handle_cavity/tool_check(mob/user, obj/item/tool) if(istype(tool, /obj/item/cautery) || istype(tool, /obj/item/gun/energy/laser)) return FALSE return !tool.get_temperature() /datum/surgery_step/handle_cavity/preop(mob/user, mob/living/carbon/human/target, target_zone, obj/item/tool, datum/surgery/surgery) var/obj/item/bodypart/chest/CH = target.get_bodypart(BODY_ZONE_CHEST) IC = CH.cavity_item if(tool) display_results(user, target, "<span class='notice'>You begin to insert [tool] into [target]'s [target_zone]...</span>", "[user] begins to insert [tool] into [target]'s [target_zone].", "[user] begins to insert [tool.w_class > WEIGHT_CLASS_SMALL ? tool : "something"] into [target]'s [target_zone].") else display_results(user, target, "<span class='notice'>You check for items in [target]'s [target_zone]...</span>", "[user] checks for items in [target]'s [target_zone].", "[user] looks for something in [target]'s [target_zone].") /datum/surgery_step/handle_cavity/success(mob/user, mob/living/carbon/human/target, target_zone, obj/item/tool, datum/surgery/surgery) var/obj/item/bodypart/chest/CH = target.get_bodypart(BODY_ZONE_CHEST) if(tool) if(IC || tool.w_class > WEIGHT_CLASS_NORMAL || HAS_TRAIT(tool, TRAIT_NODROP) || istype(tool, /obj/item/organ)) to_chat(user, "<span class='warning'>You can't seem to fit [tool] in [target]'s [target_zone]!</span>") return FALSE else display_results(user, target, "<span class='notice'>You stuff [tool] into [target]'s [target_zone].</span>", "[user] stuffs [tool] into [target]'s [target_zone]!", "[user] stuffs [tool.w_class > WEIGHT_CLASS_SMALL ? tool : "something"] into [target]'s [target_zone].") user.transferItemToLoc(tool, target, TRUE) CH.cavity_item = tool return TRUE else if(IC) display_results(user, target, "<span class='notice'>You pull [IC] out of [target]'s [target_zone].</span>", "[user] pulls [IC] out of [target]'s [target_zone]!", "[user] pulls [IC.w_class > WEIGHT_CLASS_SMALL ? IC : "something"] out of [target]'s [target_zone].") user.put_in_hands(IC) CH.cavity_item = null return TRUE else to_chat(user, "<span class='warning'>You don't find anything in [target]'s [target_zone].</span>") return FALSE
0
0.897738
1
0.897738
game-dev
MEDIA
0.808714
game-dev
0.742991
1
0.742991
Alex-Rachel/GameFramework-Next
4,534
UnityProject/Assets/UnityGameFramework/Scripts/Editor/Localization/Localization/LocalizationEditor_Tools_MergeTerms.cs
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace GameFramework.Localization { public partial class LocalizationEditor { #region Variables #endregion #region GUI void OnGUI_Tools_MergeTerms() { OnGUI_ScenesList(true); GUI.backgroundColor = Color.Lerp (Color.gray, Color.white, 0.2f); GUILayout.BeginVertical(LocalizeInspector.GUIStyle_OldTextArea, GUILayout.Height(1)); GUI.backgroundColor = Color.white; GUILayout.Space (5); EditorGUILayout.HelpBox("This option replace all occurrences of this key in the selected scenes", MessageType.Info); GUILayout.Space (5); GUITools.CloseHeader(); OnGUI_Tools_Categorize_Terms(); OnGUI_NewOrExistingTerm(); } void OnGUI_NewOrExistingTerm() { if (mKeyToExplore==null) mKeyToExplore = string.Empty; GUI.backgroundColor = Color.Lerp (Color.gray, Color.white, 0.2f); GUILayout.BeginVertical(LocalizeInspector.GUIStyle_OldTextArea, GUILayout.Height(1)); GUI.backgroundColor = Color.white; GUILayout.Space(5); GUILayout.Label("Replace By:"); GUILayout.EndVertical(); //--[ Create Term ]------------------------ GUILayout.BeginHorizontal(); mKeyToExplore = GUILayout.TextField(mKeyToExplore, EditorStyles.toolbarTextField, GUILayout.ExpandWidth(true)); if (GUILayout.Button("Create", "toolbarbutton", GUILayout.Width(60))) { LanguageSourceData.ValidateFullTerm( ref mKeyToExplore ); EditorApplication.update += ReplaceSelectedTerms; } GUILayout.EndHorizontal(); //--[ Existing Term ]------------------------ int Index = 0; List<string> Terms = mLanguageSource.GetTermsList(); for (int i=0, imax=Terms.Count; i<imax; ++i) if (Terms[i].ToLower().Contains(mKeyToExplore.ToLower())) { Index = i; break; } GUILayout.BeginHorizontal(); int NewIndex = EditorGUILayout.Popup(Index, Terms.ToArray(), EditorStyles.toolbarPopup, GUILayout.ExpandWidth(true)); if (NewIndex != Index) { SelectTerm (Terms [NewIndex]); ClearErrors(); } if (GUILayout.Button("Use", "toolbarbutton", GUILayout.Width(60))) { SelectTerm( Terms[ NewIndex ] ); EditorApplication.update += ReplaceSelectedTerms; } GUILayout.EndHorizontal(); } #endregion #region Merge Terms void ReplaceSelectedTerms() { EditorApplication.update -= ReplaceSelectedTerms; if (string.IsNullOrEmpty(mKeyToExplore)) return; mIsParsing = true; string sNewKey = mKeyToExplore; //--[ Create new Term ]----------------------- if (mLanguageSource.GetTermData(sNewKey)==null) { TermData termData = AddLocalTerm(sNewKey); //--[ Copy the values from any existing term if the target is a new term TermData oldTerm = null; for (int i=0, imax=mSelectedKeys.Count; i<imax; ++i) { oldTerm = mLanguageSource.GetTermData(mSelectedKeys[i]); if (oldTerm!=null) break; } if (oldTerm!=null) { termData.TermType = oldTerm.TermType; termData.Description = oldTerm.Description; Array.Copy(oldTerm.Languages, termData.Languages, oldTerm.Languages.Length); } } //--[ Delete the selected Terms from the source ]----------------- TermReplacements = new Dictionary<string, string>(StringComparer.Ordinal); for (int i=mSelectedKeys.Count-1; i>=0; --i) { string OldTerm = mSelectedKeys[i]; if (OldTerm == sNewKey) continue; TermReplacements[ OldTerm ] = mKeyToExplore; DeleteTerm(OldTerm); } ExecuteActionOnSelectedScenes( ReplaceTermsInCurrentScene ); DoParseTermsInCurrentScene(); //--[ Update Selected Categories ]------------- string mNewCategory = LanguageSourceData.GetCategoryFromFullTerm(sNewKey); if (mNewCategory == string.Empty) mNewCategory = LanguageSourceData.EmptyCategory; if (!mSelectedCategories.Contains(mNewCategory)) mSelectedCategories.Add (mNewCategory); //RemoveUnusedCategoriesFromSelected(); ScheduleUpdateTermsToShowInList(); TermReplacements = null; mIsParsing = false; } void RemoveUnusedCategoriesFromSelected() { List<string> Categories = LocalizationManager.GetCategories(); for (int i=mSelectedCategories.Count-1; i>=0; --i) if (!Categories.Contains( mSelectedCategories[i] )) mSelectedCategories.RemoveAt(i); if (mSelectedCategories.Count == 0) mSelectedCategories.AddRange(Categories); ScheduleUpdateTermsToShowInList(); } #endregion } }
0
0.871335
1
0.871335
game-dev
MEDIA
0.514618
game-dev,desktop-app
0.970468
1
0.970468
aszczepanski/2048
2,302
src/main/MainApplication.cpp
#include "main/MainApplication.h" #include <cstdlib> #include <iostream> #include <memory> #include <string> #include <thread> #include <atomic> #include <mutex> #include <random> #include "main/Game.h" #include "common/GameState.h" #include "common/GameStats.h" #include "common/ProgramOptions.h" #include "io/CProgramOptionsReader.h" #include "common/TuplesDescriptor.h" #include "io/IInputFileReader.h" #include "io/BinaryInputFileReader.h" #include "io/TextInputFileReader.h" using namespace std; MainApplication::MainApplication() { } int MainApplication::run(int argc, char** argv) { programOptions = programOptionsReader.read(argc, argv); if (programOptions == nullptr) return EXIT_SUCCESS; initializeInputFileReader(); tuplesDescriptor = inputFileReader->read( programOptions->strategy, programOptions->unzip); if (tuplesDescriptor == nullptr) return EXIT_SUCCESS; GameState::initializeTables(); randomEngine = move(unique_ptr<default_random_engine>( new default_random_engine(programOptions->randomSeed))); playGamesAndPrintStats(); return EXIT_SUCCESS; } void MainApplication::initializeInputFileReader() { string fn = programOptions->strategy; if (fn.substr(fn.find_last_of(".") + 1) == "txt") { inputFileReader = make_shared<TextInputFileReader>(); } else { inputFileReader = make_shared<BinaryInputFileReader>(); } } void MainApplication::playGamesAndPrintStats() { cout << GameStats::header() << endl; atomic_int gamesCounter(programOptions->games); vector<thread> gameWorkers(programOptions->gameThreads); for (size_t i=0; i<gameWorkers.size(); i++) { gameWorkers[i] = thread([&](){ unsigned seed1, seed2; int gc; while ((gc = --gamesCounter) >= 0) { { lock_guard<mutex> lock(randomEngineMutex); seed1 = uniformDist(*randomEngine); seed2 = uniformDist(*randomEngine); } Game game(programOptions, tuplesDescriptor, seed1, seed2); unique_ptr<GameStats> gameStats = move(game.play()); lock_guard<mutex> lock(gameStatsContainerMutex); cout << *gameStats << endl; // cout << gc << ": " << *gameStats << endl; gameStatsContainer.addGameStats(gameStats.get()); } }); } for (size_t i=0; i<gameWorkers.size(); i++) { gameWorkers[i].join(); } cout << gameStatsContainer << endl; }
0
0.579816
1
0.579816
game-dev
MEDIA
0.295407
game-dev
0.648882
1
0.648882
guilhermeferreira/spikepp
3,450
SPIKE/src/generic_send_udp.c
/* halflife.c - the beginings of a halflife fuzzer */ #include <stdio.h> #include <stdlib.h> #include <string.h> /*for memset*/ #include <sys/types.h> #include <sys/socket.h> #include <ctype.h> /*isalpha*/ #include "spike.h" #include "hdebug.h" #include "tcpstuff.h" #include "udpstuff.h" #include "dlrpc.h" #define TOTALTOSEND 10 struct spike * our_spike; void usage() { printf("Usage: ./gsu target port file.spk startvariable startfuzzstring startvariable startstring totaltosend\r\n"); printf("./gsu 192.168.1.104 80 file.spk 0 0 5000\n"); exit(-1); } int main (int argc, char ** argv) { char * target; int port; char * spkfile; /*change these to skip over variables*/ int SKIPFUZZSTR=0; int SKIPVARIABLES=0; int fuzzvarnum; int fuzzstrnum; int firstfuzz; int totalsent,totaltosend; int i; if (argc!=7) { printf("argc=%d\n",argc); usage(); } target=argv[1]; printf("Target is %s\r\n",argv[1]); port=atoi(argv[2]); spkfile=(argv[3]); SKIPVARIABLES=atoi(argv[4]); SKIPFUZZSTR=atoi(argv[5]); totalsent=1; totaltosend=atoi(argv[6]); our_spike=new_spike(); s_init_fuzzing(); if (SKIPFUZZSTR>s_get_max_fuzzstring()) { printf("Your start fuzzstring is greater than %d, which is the maximum\n",s_get_max_fuzzstring()); exit(1); } if (our_spike==NULL) { fprintf(stderr,"Malloc failed trying to allocate a spike.\r\n"); exit(-1); } setspike(our_spike); if (spike_connect_udp(target,port)<0) { printf("Couldn't connect!\n"); exit(-1); } printf("fd=%d\n",our_spike->fd); /*zeroth fuzz variable is first variable*/ s_resetfuzzvariable(); fuzzvarnum=0; fuzzstrnum=0; firstfuzz=1; while (!s_didlastvariable()) { s_resetfuzzstring(); /*zeroth fuzz string is no change*/ if (firstfuzz) { /*zeroth fuzz string is no change*/ /*see below for why we have this if statement and loop*/ if (fuzzvarnum<SKIPVARIABLES ) { for (fuzzvarnum=0; fuzzvarnum<SKIPVARIABLES; fuzzvarnum++) { s_incrementfuzzvariable(); } } /*here is another part of where we implement the ability to jump to a particular place in the fuzzing*/ if (fuzzstrnum<SKIPFUZZSTR) { for (fuzzstrnum=0; fuzzstrnum<SKIPFUZZSTR; fuzzstrnum++) { s_incrementfuzzstring(); } } firstfuzz=0; } else { /*we reset this here so every new variable gets a new count*/ fuzzstrnum=0; } while(!s_didlastfuzzstring()) { printf("Fuzzing Variable %d:%d\n",fuzzvarnum,fuzzstrnum); spike_clear(); s_parse(spkfile); /* printf("spike size is 0x%x\n",(unsigned int)our_spike->datasize); for (i=0; i<our_spike->datasize; i++) { printf("0x%2.2x ",our_spike->databuf[i]); } */ if (spike_send()<0) { printf("Couldn't send data!\r\n"); exit(-1); } //s_read_packet(); // if (totalsent==totaltosend) { printf("\nReached maximum packets to send (%d).\n",totaltosend); exit(0); } totalsent++; fuzzstrnum++; s_incrementfuzzstring(); //spike_close_tcp(); /*Use this for testing against netcat*/ /* sleep(1); */ }/*end for each fuzz string*/ fuzzvarnum++; s_incrementfuzzvariable(); }/*end for each variable*/ printf ("\nDone fuzzing!\n"); return 0; }
0
0.647321
1
0.647321
game-dev
MEDIA
0.303014
game-dev
0.878434
1
0.878434
followingthefasciaplane/source-engine-diff-check
62,203
misc/game/shared/hl2mp/weapon_rpg.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "npcevent.h" #include "in_buttons.h" #include "weapon_rpg.h" #ifdef CLIENT_DLL #include "c_hl2mp_player.h" #include "model_types.h" #include "beamdraw.h" #include "fx_line.h" #include "view.h" #else #include "basecombatcharacter.h" #include "movie_explosion.h" #include "soundent.h" #include "player.h" #include "rope.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "explode.h" #include "util.h" #include "in_buttons.h" #include "shake.h" #include "te_effect_dispatch.h" #include "triggers.h" #include "smoke_trail.h" #include "collisionutils.h" #include "hl2_shareddefs.h" #endif #include "debugoverlay_shared.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define RPG_SPEED 1500 #ifndef CLIENT_DLL const char *g_pLaserDotThink = "LaserThinkContext"; static ConVar sk_apc_missile_damage("sk_apc_missile_damage", "15"); #define APC_MISSILE_DAMAGE sk_apc_missile_damage.GetFloat() #endif #ifdef CLIENT_DLL #define CLaserDot C_LaserDot #endif //----------------------------------------------------------------------------- // Laser Dot //----------------------------------------------------------------------------- class CLaserDot : public CBaseEntity { DECLARE_CLASS( CLaserDot, CBaseEntity ); public: CLaserDot( void ); ~CLaserDot( void ); static CLaserDot *Create( const Vector &origin, CBaseEntity *pOwner = NULL, bool bVisibleDot = true ); void SetTargetEntity( CBaseEntity *pTarget ) { m_hTargetEnt = pTarget; } CBaseEntity *GetTargetEntity( void ) { return m_hTargetEnt; } void SetLaserPosition( const Vector &origin, const Vector &normal ); Vector GetChasePosition(); void TurnOn( void ); void TurnOff( void ); bool IsOn() const { return m_bIsOn; } void Toggle( void ); int ObjectCaps() { return (BaseClass::ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_DONT_SAVE; } void MakeInvisible( void ); #ifdef CLIENT_DLL virtual bool IsTransparent( void ) { return true; } virtual RenderGroup_t GetRenderGroup( void ) { return RENDER_GROUP_TRANSLUCENT_ENTITY; } virtual int DrawModel( int flags ); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual bool ShouldDraw( void ) { return (IsEffectActive(EF_NODRAW)==false); } CMaterialReference m_hSpriteMaterial; #endif protected: Vector m_vecSurfaceNormal; EHANDLE m_hTargetEnt; bool m_bVisibleLaserDot; bool m_bIsOn; DECLARE_NETWORKCLASS(); DECLARE_DATADESC(); public: CLaserDot *m_pNext; }; IMPLEMENT_NETWORKCLASS_ALIASED( LaserDot, DT_LaserDot ) BEGIN_NETWORK_TABLE( CLaserDot, DT_LaserDot ) END_NETWORK_TABLE() #ifndef CLIENT_DLL // a list of laser dots to search quickly CEntityClassList<CLaserDot> g_LaserDotList; template <> CLaserDot *CEntityClassList<CLaserDot>::m_pClassList = NULL; CLaserDot *GetLaserDotList() { return g_LaserDotList.m_pClassList; } BEGIN_DATADESC( CMissile ) DEFINE_FIELD( m_hOwner, FIELD_EHANDLE ), DEFINE_FIELD( m_hRocketTrail, FIELD_EHANDLE ), DEFINE_FIELD( m_flAugerTime, FIELD_TIME ), DEFINE_FIELD( m_flMarkDeadTime, FIELD_TIME ), DEFINE_FIELD( m_flGracePeriodEndsAt, FIELD_TIME ), DEFINE_FIELD( m_flDamage, FIELD_FLOAT ), // Function Pointers DEFINE_FUNCTION( MissileTouch ), DEFINE_FUNCTION( AccelerateThink ), DEFINE_FUNCTION( AugerThink ), DEFINE_FUNCTION( IgniteThink ), DEFINE_FUNCTION( SeekThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( rpg_missile, CMissile ); class CWeaponRPG; //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CMissile::CMissile() { m_hRocketTrail = NULL; } CMissile::~CMissile() { } //----------------------------------------------------------------------------- // Purpose: // // //----------------------------------------------------------------------------- void CMissile::Precache( void ) { PrecacheModel( "models/weapons/w_missile.mdl" ); PrecacheModel( "models/weapons/w_missile_launch.mdl" ); PrecacheModel( "models/weapons/w_missile_closed.mdl" ); } //----------------------------------------------------------------------------- // Purpose: // // //----------------------------------------------------------------------------- void CMissile::Spawn( void ) { Precache(); SetSolid( SOLID_BBOX ); SetModel("models/weapons/w_missile_launch.mdl"); UTIL_SetSize( this, -Vector(4,4,4), Vector(4,4,4) ); SetTouch( &CMissile::MissileTouch ); SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_BOUNCE ); SetThink( &CMissile::IgniteThink ); SetNextThink( gpGlobals->curtime + 0.3f ); m_takedamage = DAMAGE_YES; m_iHealth = m_iMaxHealth = 100; m_bloodColor = DONT_BLEED; m_flGracePeriodEndsAt = 0; AddFlag( FL_OBJECT ); } //--------------------------------------------------------- //--------------------------------------------------------- void CMissile::Event_Killed( const CTakeDamageInfo &info ) { m_takedamage = DAMAGE_NO; ShotDown(); } unsigned int CMissile::PhysicsSolidMaskForEntity( void ) const { return BaseClass::PhysicsSolidMaskForEntity() | CONTENTS_HITBOX; } //--------------------------------------------------------- //--------------------------------------------------------- int CMissile::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { if ( ( info.GetDamageType() & (DMG_MISSILEDEFENSE | DMG_AIRBOAT) ) == false ) return 0; bool bIsDamaged; if( m_iHealth <= AugerHealth() ) { // This missile is already damaged (i.e., already running AugerThink) bIsDamaged = true; } else { // This missile isn't damaged enough to wobble in flight yet bIsDamaged = false; } int nRetVal = BaseClass::OnTakeDamage_Alive( info ); if( !bIsDamaged ) { if ( m_iHealth <= AugerHealth() ) { ShotDown(); } } return nRetVal; } //----------------------------------------------------------------------------- // Purpose: Stops any kind of tracking and shoots dumb //----------------------------------------------------------------------------- void CMissile::DumbFire( void ) { SetThink( NULL ); SetMoveType( MOVETYPE_FLY ); SetModel("models/weapons/w_missile.mdl"); UTIL_SetSize( this, vec3_origin, vec3_origin ); EmitSound( "Missile.Ignite" ); // Smoke trail. CreateSmokeTrail(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissile::SetGracePeriod( float flGracePeriod ) { m_flGracePeriodEndsAt = gpGlobals->curtime + flGracePeriod; // Go non-solid until the grace period ends AddSolidFlags( FSOLID_NOT_SOLID ); } //--------------------------------------------------------- //--------------------------------------------------------- void CMissile::AccelerateThink( void ) { Vector vecForward; // !!!UNDONE - make this work exactly the same as HL1 RPG, lest we have looping sound bugs again! EmitSound( "Missile.Accelerate" ); // SetEffects( EF_LIGHT ); AngleVectors( GetLocalAngles(), &vecForward ); SetAbsVelocity( vecForward * RPG_SPEED ); SetThink( &CMissile::SeekThink ); SetNextThink( gpGlobals->curtime + 0.1f ); } #define AUGER_YDEVIANCE 20.0f #define AUGER_XDEVIANCEUP 8.0f #define AUGER_XDEVIANCEDOWN 1.0f //--------------------------------------------------------- //--------------------------------------------------------- void CMissile::AugerThink( void ) { // If we've augered long enough, then just explode if ( m_flAugerTime < gpGlobals->curtime ) { Explode(); return; } if ( m_flMarkDeadTime < gpGlobals->curtime ) { m_lifeState = LIFE_DYING; } QAngle angles = GetLocalAngles(); angles.y += random->RandomFloat( -AUGER_YDEVIANCE, AUGER_YDEVIANCE ); angles.x += random->RandomFloat( -AUGER_XDEVIANCEDOWN, AUGER_XDEVIANCEUP ); SetLocalAngles( angles ); Vector vecForward; AngleVectors( GetLocalAngles(), &vecForward ); SetAbsVelocity( vecForward * 1000.0f ); SetNextThink( gpGlobals->curtime + 0.05f ); } //----------------------------------------------------------------------------- // Purpose: Causes the missile to spiral to the ground and explode, due to damage //----------------------------------------------------------------------------- void CMissile::ShotDown( void ) { CEffectData data; data.m_vOrigin = GetAbsOrigin(); DispatchEffect( "RPGShotDown", data ); if ( m_hRocketTrail != NULL ) { m_hRocketTrail->m_bDamaged = true; } SetThink( &CMissile::AugerThink ); SetNextThink( gpGlobals->curtime ); m_flAugerTime = gpGlobals->curtime + 1.5f; m_flMarkDeadTime = gpGlobals->curtime + 0.75; // Let the RPG start reloading immediately if ( m_hOwner != NULL ) { m_hOwner->NotifyRocketDied(); m_hOwner = NULL; } } //----------------------------------------------------------------------------- // The actual explosion //----------------------------------------------------------------------------- void CMissile::DoExplosion( void ) { // Explode ExplosionCreate( GetAbsOrigin(), GetAbsAngles(), GetOwnerEntity(), GetDamage(), GetDamage() * 2, SF_ENVEXPLOSION_NOSPARKS | SF_ENVEXPLOSION_NODLIGHTS | SF_ENVEXPLOSION_NOSMOKE, 0.0f, this); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissile::Explode( void ) { // Don't explode against the skybox. Just pretend that // the missile flies off into the distance. Vector forward; GetVectors( &forward, NULL, NULL ); trace_t tr; UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + forward * 16, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); m_takedamage = DAMAGE_NO; SetSolid( SOLID_NONE ); if( tr.fraction == 1.0 || !(tr.surface.flags & SURF_SKY) ) { DoExplosion(); } if( m_hRocketTrail ) { m_hRocketTrail->SetLifetime(0.1f); m_hRocketTrail = NULL; } if ( m_hOwner != NULL ) { m_hOwner->NotifyRocketDied(); m_hOwner = NULL; } StopSound( "Missile.Ignite" ); UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pOther - //----------------------------------------------------------------------------- void CMissile::MissileTouch( CBaseEntity *pOther ) { Assert( pOther ); // Don't touch triggers (but DO hit weapons) if ( pOther->IsSolidFlagSet(FSOLID_TRIGGER|FSOLID_VOLUME_CONTENTS) && pOther->GetCollisionGroup() != COLLISION_GROUP_WEAPON ) return; Explode(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissile::CreateSmokeTrail( void ) { if ( m_hRocketTrail ) return; // Smoke trail. if ( (m_hRocketTrail = RocketTrail::CreateRocketTrail()) != NULL ) { m_hRocketTrail->m_Opacity = 0.2f; m_hRocketTrail->m_SpawnRate = 100; m_hRocketTrail->m_ParticleLifetime = 0.5f; m_hRocketTrail->m_StartColor.Init( 0.65f, 0.65f , 0.65f ); m_hRocketTrail->m_EndColor.Init( 0.0, 0.0, 0.0 ); m_hRocketTrail->m_StartSize = 8; m_hRocketTrail->m_EndSize = 32; m_hRocketTrail->m_SpawnRadius = 4; m_hRocketTrail->m_MinSpeed = 2; m_hRocketTrail->m_MaxSpeed = 16; m_hRocketTrail->SetLifetime( 999 ); m_hRocketTrail->FollowEntity( this, "0" ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissile::IgniteThink( void ) { SetMoveType( MOVETYPE_FLY ); SetModel("models/weapons/w_missile.mdl"); UTIL_SetSize( this, vec3_origin, vec3_origin ); RemoveSolidFlags( FSOLID_NOT_SOLID ); //TODO: Play opening sound Vector vecForward; EmitSound( "Missile.Ignite" ); AngleVectors( GetLocalAngles(), &vecForward ); SetAbsVelocity( vecForward * RPG_SPEED ); SetThink( &CMissile::SeekThink ); SetNextThink( gpGlobals->curtime ); if ( m_hOwner && m_hOwner->GetOwner() ) { CBasePlayer *pPlayer = ToBasePlayer( m_hOwner->GetOwner() ); color32 white = { 255,225,205,64 }; UTIL_ScreenFade( pPlayer, white, 0.1f, 0.0f, FFADE_IN ); } CreateSmokeTrail(); } //----------------------------------------------------------------------------- // Gets the shooting position //----------------------------------------------------------------------------- void CMissile::GetShootPosition( CLaserDot *pLaserDot, Vector *pShootPosition ) { if ( pLaserDot->GetOwnerEntity() != NULL ) { //FIXME: Do we care this isn't exactly the muzzle position? *pShootPosition = pLaserDot->GetOwnerEntity()->WorldSpaceCenter(); } else { *pShootPosition = pLaserDot->GetChasePosition(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- #define RPG_HOMING_SPEED 0.125f void CMissile::ComputeActualDotPosition( CLaserDot *pLaserDot, Vector *pActualDotPosition, float *pHomingSpeed ) { *pHomingSpeed = RPG_HOMING_SPEED; if ( pLaserDot->GetTargetEntity() ) { *pActualDotPosition = pLaserDot->GetChasePosition(); return; } Vector vLaserStart; GetShootPosition( pLaserDot, &vLaserStart ); //Get the laser's vector Vector vLaserDir; VectorSubtract( pLaserDot->GetChasePosition(), vLaserStart, vLaserDir ); //Find the length of the current laser float flLaserLength = VectorNormalize( vLaserDir ); //Find the length from the missile to the laser's owner float flMissileLength = GetAbsOrigin().DistTo( vLaserStart ); //Find the length from the missile to the laser's position Vector vecTargetToMissile; VectorSubtract( GetAbsOrigin(), pLaserDot->GetChasePosition(), vecTargetToMissile ); float flTargetLength = VectorNormalize( vecTargetToMissile ); // See if we should chase the line segment nearest us if ( ( flMissileLength < flLaserLength ) || ( flTargetLength <= 512.0f ) ) { *pActualDotPosition = UTIL_PointOnLineNearestPoint( vLaserStart, pLaserDot->GetChasePosition(), GetAbsOrigin() ); *pActualDotPosition += ( vLaserDir * 256.0f ); } else { // Otherwise chase the dot *pActualDotPosition = pLaserDot->GetChasePosition(); } // NDebugOverlay::Line( pLaserDot->GetChasePosition(), vLaserStart, 0, 255, 0, true, 0.05f ); // NDebugOverlay::Line( GetAbsOrigin(), *pActualDotPosition, 255, 0, 0, true, 0.05f ); // NDebugOverlay::Cross3D( *pActualDotPosition, -Vector(4,4,4), Vector(4,4,4), 255, 0, 0, true, 0.05f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissile::SeekThink( void ) { CBaseEntity *pBestDot = NULL; float flBestDist = MAX_TRACE_LENGTH; float dotDist; // If we have a grace period, go solid when it ends if ( m_flGracePeriodEndsAt ) { if ( m_flGracePeriodEndsAt < gpGlobals->curtime ) { RemoveSolidFlags( FSOLID_NOT_SOLID ); m_flGracePeriodEndsAt = 0; } } //Search for all dots relevant to us for( CLaserDot *pEnt = GetLaserDotList(); pEnt != NULL; pEnt = pEnt->m_pNext ) { if ( !pEnt->IsOn() ) continue; if ( pEnt->GetOwnerEntity() != GetOwnerEntity() ) continue; dotDist = (GetAbsOrigin() - pEnt->GetAbsOrigin()).Length(); //Find closest if ( dotDist < flBestDist ) { pBestDot = pEnt; flBestDist = dotDist; } } //If we have a dot target if ( pBestDot == NULL ) { //Think as soon as possible SetNextThink( gpGlobals->curtime ); return; } CLaserDot *pLaserDot = (CLaserDot *)pBestDot; Vector targetPos; float flHomingSpeed; Vector vecLaserDotPosition; ComputeActualDotPosition( pLaserDot, &targetPos, &flHomingSpeed ); if ( IsSimulatingOnAlternateTicks() ) flHomingSpeed *= 2; Vector vTargetDir; VectorSubtract( targetPos, GetAbsOrigin(), vTargetDir ); float flDist = VectorNormalize( vTargetDir ); Vector vDir = GetAbsVelocity(); float flSpeed = VectorNormalize( vDir ); Vector vNewVelocity = vDir; if ( gpGlobals->frametime > 0.0f ) { if ( flSpeed != 0 ) { vNewVelocity = ( flHomingSpeed * vTargetDir ) + ( ( 1 - flHomingSpeed ) * vDir ); // This computation may happen to cancel itself out exactly. If so, slam to targetdir. if ( VectorNormalize( vNewVelocity ) < 1e-3 ) { vNewVelocity = (flDist != 0) ? vTargetDir : vDir; } } else { vNewVelocity = vTargetDir; } } QAngle finalAngles; VectorAngles( vNewVelocity, finalAngles ); SetAbsAngles( finalAngles ); vNewVelocity *= flSpeed; SetAbsVelocity( vNewVelocity ); if( GetAbsVelocity() == vec3_origin ) { // Strange circumstances have brought this missile to halt. Just blow it up. Explode(); return; } // Think as soon as possible SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: // // Input : &vecOrigin - // &vecAngles - // NULL - // // Output : CMissile //----------------------------------------------------------------------------- CMissile *CMissile::Create( const Vector &vecOrigin, const QAngle &vecAngles, edict_t *pentOwner = NULL ) { //CMissile *pMissile = (CMissile *)CreateEntityByName("rpg_missile" ); CMissile *pMissile = (CMissile *) CBaseEntity::Create( "rpg_missile", vecOrigin, vecAngles, CBaseEntity::Instance( pentOwner ) ); pMissile->SetOwnerEntity( Instance( pentOwner ) ); pMissile->Spawn(); pMissile->AddEffects( EF_NOSHADOW ); Vector vecForward; AngleVectors( vecAngles, &vecForward ); pMissile->SetAbsVelocity( vecForward * 300 + Vector( 0,0, 128 ) ); return pMissile; } //----------------------------------------------------------------------------- // This entity is used to create little force boxes that the helicopter // should avoid. //----------------------------------------------------------------------------- class CInfoAPCMissileHint : public CBaseEntity { DECLARE_DATADESC(); public: DECLARE_CLASS( CInfoAPCMissileHint, CBaseEntity ); virtual void Spawn( ); virtual void Activate(); virtual void UpdateOnRemove(); static CBaseEntity *FindAimTarget( CBaseEntity *pMissile, const char *pTargetName, const Vector &vecCurrentTargetPos, const Vector &vecCurrentTargetVel ); private: EHANDLE m_hTarget; typedef CHandle<CInfoAPCMissileHint> APCMissileHintHandle_t; static CUtlVector< APCMissileHintHandle_t > s_APCMissileHints; }; //----------------------------------------------------------------------------- // // This entity is used to create little force boxes that the helicopters should avoid. // //----------------------------------------------------------------------------- CUtlVector< CInfoAPCMissileHint::APCMissileHintHandle_t > CInfoAPCMissileHint::s_APCMissileHints; LINK_ENTITY_TO_CLASS( info_apc_missile_hint, CInfoAPCMissileHint ); BEGIN_DATADESC( CInfoAPCMissileHint ) DEFINE_FIELD( m_hTarget, FIELD_EHANDLE ), END_DATADESC() //----------------------------------------------------------------------------- // Spawn, remove //----------------------------------------------------------------------------- void CInfoAPCMissileHint::Spawn( ) { SetModel( STRING( GetModelName() ) ); SetSolid( SOLID_BSP ); AddSolidFlags( FSOLID_NOT_SOLID ); AddEffects( EF_NODRAW ); } void CInfoAPCMissileHint::Activate( ) { BaseClass::Activate(); m_hTarget = gEntList.FindEntityByName( NULL, m_target ); if ( m_hTarget == NULL ) { DevWarning( "%s: Could not find target '%s'!\n", GetClassname(), STRING( m_target ) ); } else { s_APCMissileHints.AddToTail( this ); } } void CInfoAPCMissileHint::UpdateOnRemove( ) { s_APCMissileHints.FindAndRemove( this ); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Where are how should we avoid? //----------------------------------------------------------------------------- #define HINT_PREDICTION_TIME 3.0f CBaseEntity *CInfoAPCMissileHint::FindAimTarget( CBaseEntity *pMissile, const char *pTargetName, const Vector &vecCurrentEnemyPos, const Vector &vecCurrentEnemyVel ) { if ( !pTargetName ) return NULL; float flOOSpeed = pMissile->GetAbsVelocity().Length(); if ( flOOSpeed != 0.0f ) { flOOSpeed = 1.0f / flOOSpeed; } for ( int i = s_APCMissileHints.Count(); --i >= 0; ) { CInfoAPCMissileHint *pHint = s_APCMissileHints[i]; if ( !pHint->NameMatches( pTargetName ) ) continue; if ( !pHint->m_hTarget ) continue; Vector vecMissileToHint, vecMissileToEnemy; VectorSubtract( pHint->m_hTarget->WorldSpaceCenter(), pMissile->GetAbsOrigin(), vecMissileToHint ); VectorSubtract( vecCurrentEnemyPos, pMissile->GetAbsOrigin(), vecMissileToEnemy ); float flDistMissileToHint = VectorNormalize( vecMissileToHint ); VectorNormalize( vecMissileToEnemy ); if ( DotProduct( vecMissileToHint, vecMissileToEnemy ) < 0.866f ) continue; // Determine when the target will be inside the volume. // Project at most 3 seconds in advance Vector vecRayDelta; VectorMultiply( vecCurrentEnemyVel, HINT_PREDICTION_TIME, vecRayDelta ); BoxTraceInfo_t trace; if ( !IntersectRayWithOBB( vecCurrentEnemyPos, vecRayDelta, pHint->CollisionProp()->CollisionToWorldTransform(), pHint->CollisionProp()->OBBMins(), pHint->CollisionProp()->OBBMaxs(), 0.0f, &trace )) { continue; } // Determine the amount of time it would take the missile to reach the target // If we can reach the target within the time it takes for the enemy to reach the float tSqr = flDistMissileToHint * flOOSpeed / HINT_PREDICTION_TIME; if ( (tSqr < (trace.t1 * trace.t1)) || (tSqr > (trace.t2 * trace.t2)) ) continue; return pHint->m_hTarget; } return NULL; } //----------------------------------------------------------------------------- // a list of missiles to search quickly //----------------------------------------------------------------------------- CEntityClassList<CAPCMissile> g_APCMissileList; template <> CAPCMissile *CEntityClassList<CAPCMissile>::m_pClassList = NULL; CAPCMissile *GetAPCMissileList() { return g_APCMissileList.m_pClassList; } //----------------------------------------------------------------------------- // Finds apc missiles in cone //----------------------------------------------------------------------------- CAPCMissile *FindAPCMissileInCone( const Vector &vecOrigin, const Vector &vecDirection, float flAngle ) { float flCosAngle = cos( DEG2RAD( flAngle ) ); for( CAPCMissile *pEnt = GetAPCMissileList(); pEnt != NULL; pEnt = pEnt->m_pNext ) { if ( !pEnt->IsSolid() ) continue; Vector vecDelta; VectorSubtract( pEnt->GetAbsOrigin(), vecOrigin, vecDelta ); VectorNormalize( vecDelta ); float flDot = DotProduct( vecDelta, vecDirection ); if ( flDot > flCosAngle ) return pEnt; } return NULL; } //----------------------------------------------------------------------------- // // Specialized version of the missile // //----------------------------------------------------------------------------- #define MAX_HOMING_DISTANCE 2250.0f #define MIN_HOMING_DISTANCE 1250.0f #define MAX_NEAR_HOMING_DISTANCE 1750.0f #define MIN_NEAR_HOMING_DISTANCE 1000.0f #define DOWNWARD_BLEND_TIME_START 0.2f #define MIN_HEIGHT_DIFFERENCE 250.0f #define MAX_HEIGHT_DIFFERENCE 550.0f #define CORRECTION_TIME 0.2f #define APC_LAUNCH_HOMING_SPEED 0.1f #define APC_HOMING_SPEED 0.025f #define HOMING_SPEED_ACCEL 0.01f BEGIN_DATADESC( CAPCMissile ) DEFINE_FIELD( m_flReachedTargetTime, FIELD_TIME ), DEFINE_FIELD( m_flIgnitionTime, FIELD_TIME ), DEFINE_FIELD( m_bGuidingDisabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_hSpecificTarget, FIELD_EHANDLE ), DEFINE_FIELD( m_strHint, FIELD_STRING ), DEFINE_FIELD( m_flLastHomingSpeed, FIELD_FLOAT ), // DEFINE_FIELD( m_pNext, FIELD_CLASSPTR ), DEFINE_THINKFUNC( BeginSeekThink ), DEFINE_THINKFUNC( AugerStartThink ), DEFINE_THINKFUNC( ExplodeThink ), DEFINE_FUNCTION( APCMissileTouch ), END_DATADESC() LINK_ENTITY_TO_CLASS( apc_missile, CAPCMissile ); CAPCMissile *CAPCMissile::Create( const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseEntity *pOwner ) { CAPCMissile *pMissile = (CAPCMissile *)CBaseEntity::Create( "apc_missile", vecOrigin, vecAngles, pOwner ); pMissile->SetOwnerEntity( pOwner ); pMissile->Spawn(); pMissile->SetAbsVelocity( vecVelocity ); pMissile->AddFlag( FL_NOTARGET ); pMissile->AddEffects( EF_NOSHADOW ); return pMissile; } //----------------------------------------------------------------------------- // Constructor, destructor //----------------------------------------------------------------------------- CAPCMissile::CAPCMissile() { g_APCMissileList.Insert( this ); } CAPCMissile::~CAPCMissile() { g_APCMissileList.Remove( this ); } //----------------------------------------------------------------------------- // Shared initialization code //----------------------------------------------------------------------------- void CAPCMissile::Init() { SetMoveType( MOVETYPE_FLY ); SetModel("models/weapons/w_missile.mdl"); UTIL_SetSize( this, vec3_origin, vec3_origin ); CreateSmokeTrail(); SetTouch( &CAPCMissile::APCMissileTouch ); m_flLastHomingSpeed = APC_HOMING_SPEED; } //----------------------------------------------------------------------------- // For hitting a specific target //----------------------------------------------------------------------------- void CAPCMissile::AimAtSpecificTarget( CBaseEntity *pTarget ) { m_hSpecificTarget = pTarget; } //----------------------------------------------------------------------------- // Purpose: // Input : *pOther - //----------------------------------------------------------------------------- void CAPCMissile::APCMissileTouch( CBaseEntity *pOther ) { Assert( pOther ); if ( !pOther->IsSolid() && !pOther->IsSolidFlagSet(FSOLID_VOLUME_CONTENTS) ) return; Explode(); } //----------------------------------------------------------------------------- // Specialized version of the missile //----------------------------------------------------------------------------- void CAPCMissile::IgniteDelay( void ) { m_flIgnitionTime = gpGlobals->curtime + 0.3f; SetThink( &CAPCMissile::BeginSeekThink ); SetNextThink( m_flIgnitionTime ); Init(); AddSolidFlags( FSOLID_NOT_SOLID ); } void CAPCMissile::AugerDelay( float flDelay ) { m_flIgnitionTime = gpGlobals->curtime; SetThink( &CAPCMissile::AugerStartThink ); SetNextThink( gpGlobals->curtime + flDelay ); Init(); DisableGuiding(); } void CAPCMissile::AugerStartThink() { if ( m_hRocketTrail != NULL ) { m_hRocketTrail->m_bDamaged = true; } m_flAugerTime = gpGlobals->curtime + random->RandomFloat( 1.0f, 2.0f ); SetThink( &CAPCMissile::AugerThink ); SetNextThink( gpGlobals->curtime ); } void CAPCMissile::ExplodeDelay( float flDelay ) { m_flIgnitionTime = gpGlobals->curtime; SetThink( &CAPCMissile::ExplodeThink ); SetNextThink( gpGlobals->curtime + flDelay ); Init(); DisableGuiding(); } void CAPCMissile::BeginSeekThink( void ) { RemoveSolidFlags( FSOLID_NOT_SOLID ); SetThink( &CAPCMissile::SeekThink ); SetNextThink( gpGlobals->curtime ); } void CAPCMissile::ExplodeThink() { DoExplosion(); } //----------------------------------------------------------------------------- // Health lost at which augering starts //----------------------------------------------------------------------------- int CAPCMissile::AugerHealth() { return m_iMaxHealth - 25; } //----------------------------------------------------------------------------- // Health lost at which augering starts //----------------------------------------------------------------------------- void CAPCMissile::DisableGuiding() { m_bGuidingDisabled = true; } //----------------------------------------------------------------------------- // Guidance hints //----------------------------------------------------------------------------- void CAPCMissile::SetGuidanceHint( const char *pHintName ) { m_strHint = MAKE_STRING( pHintName ); } //----------------------------------------------------------------------------- // The actual explosion //----------------------------------------------------------------------------- void CAPCMissile::DoExplosion( void ) { if ( GetWaterLevel() != 0 ) { CEffectData data; data.m_vOrigin = WorldSpaceCenter(); data.m_flMagnitude = 128; data.m_flScale = 128; data.m_fFlags = 0; DispatchEffect( "WaterSurfaceExplosion", data ); } else { ExplosionCreate( GetAbsOrigin(), GetAbsAngles(), GetOwnerEntity(), APC_MISSILE_DAMAGE, 100, true, 20000 ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAPCMissile::ComputeLeadingPosition( const Vector &vecShootPosition, CBaseEntity *pTarget, Vector *pLeadPosition ) { Vector vecTarget = pTarget->BodyTarget( vecShootPosition, false ); float flShotSpeed = GetAbsVelocity().Length(); if ( flShotSpeed == 0 ) { *pLeadPosition = vecTarget; return; } Vector vecVelocity = pTarget->GetSmoothedVelocity(); vecVelocity.z = 0.0f; float flTargetSpeed = VectorNormalize( vecVelocity ); Vector vecDelta; VectorSubtract( vecShootPosition, vecTarget, vecDelta ); float flTargetToShooter = VectorNormalize( vecDelta ); float flCosTheta = DotProduct( vecDelta, vecVelocity ); // Law of cosines... z^2 = x^2 + y^2 - 2xy cos Theta // where z = flShooterToPredictedTargetPosition = flShotSpeed * predicted time // x = flTargetSpeed * predicted time // y = flTargetToShooter // solve for predicted time using at^2 + bt + c = 0, t = (-b +/- sqrt( b^2 - 4ac )) / 2a float a = flTargetSpeed * flTargetSpeed - flShotSpeed * flShotSpeed; float b = -2.0f * flTargetToShooter * flCosTheta * flTargetSpeed; float c = flTargetToShooter * flTargetToShooter; float flDiscrim = b*b - 4*a*c; if (flDiscrim < 0) { *pLeadPosition = vecTarget; return; } flDiscrim = sqrt(flDiscrim); float t = (-b + flDiscrim) / (2.0f * a); float t2 = (-b - flDiscrim) / (2.0f * a); if ( t < t2 ) { t = t2; } if ( t <= 0.0f ) { *pLeadPosition = vecTarget; return; } VectorMA( vecTarget, flTargetSpeed * t, vecVelocity, *pLeadPosition ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAPCMissile::ComputeActualDotPosition( CLaserDot *pLaserDot, Vector *pActualDotPosition, float *pHomingSpeed ) { if ( m_bGuidingDisabled ) { *pActualDotPosition = GetAbsOrigin(); *pHomingSpeed = 0.0f; m_flLastHomingSpeed = *pHomingSpeed; return; } if ( ( m_strHint != NULL_STRING ) && (!m_hSpecificTarget) ) { Vector vecOrigin, vecVelocity; CBaseEntity *pTarget = pLaserDot->GetTargetEntity(); if ( pTarget ) { vecOrigin = pTarget->BodyTarget( GetAbsOrigin(), false ); vecVelocity = pTarget->GetSmoothedVelocity(); } else { vecOrigin = pLaserDot->GetChasePosition(); vecVelocity = vec3_origin; } m_hSpecificTarget = CInfoAPCMissileHint::FindAimTarget( this, STRING( m_strHint ), vecOrigin, vecVelocity ); } CBaseEntity *pLaserTarget = m_hSpecificTarget ? m_hSpecificTarget.Get() : pLaserDot->GetTargetEntity(); if ( !pLaserTarget ) { BaseClass::ComputeActualDotPosition( pLaserDot, pActualDotPosition, pHomingSpeed ); m_flLastHomingSpeed = *pHomingSpeed; return; } if ( pLaserTarget->ClassMatches( "npc_bullseye" ) ) { if ( m_flLastHomingSpeed != RPG_HOMING_SPEED ) { if (m_flLastHomingSpeed > RPG_HOMING_SPEED) { m_flLastHomingSpeed -= HOMING_SPEED_ACCEL * UTIL_GetSimulationInterval(); if ( m_flLastHomingSpeed < RPG_HOMING_SPEED ) { m_flLastHomingSpeed = RPG_HOMING_SPEED; } } else { m_flLastHomingSpeed += HOMING_SPEED_ACCEL * UTIL_GetSimulationInterval(); if ( m_flLastHomingSpeed > RPG_HOMING_SPEED ) { m_flLastHomingSpeed = RPG_HOMING_SPEED; } } } *pHomingSpeed = m_flLastHomingSpeed; *pActualDotPosition = pLaserTarget->WorldSpaceCenter(); return; } Vector vLaserStart; GetShootPosition( pLaserDot, &vLaserStart ); *pHomingSpeed = APC_LAUNCH_HOMING_SPEED; //Get the laser's vector Vector vecTargetPosition = pLaserTarget->BodyTarget( GetAbsOrigin(), false ); // Compute leading position Vector vecLeadPosition; ComputeLeadingPosition( GetAbsOrigin(), pLaserTarget, &vecLeadPosition ); Vector vecTargetToMissile, vecTargetToShooter; VectorSubtract( GetAbsOrigin(), vecTargetPosition, vecTargetToMissile ); VectorSubtract( vLaserStart, vecTargetPosition, vecTargetToShooter ); *pActualDotPosition = vecLeadPosition; float flMinHomingDistance = MIN_HOMING_DISTANCE; float flMaxHomingDistance = MAX_HOMING_DISTANCE; float flBlendTime = gpGlobals->curtime - m_flIgnitionTime; if ( flBlendTime > DOWNWARD_BLEND_TIME_START ) { if ( m_flReachedTargetTime != 0.0f ) { *pHomingSpeed = APC_HOMING_SPEED; float flDeltaTime = clamp( gpGlobals->curtime - m_flReachedTargetTime, 0.0f, CORRECTION_TIME ); *pHomingSpeed = SimpleSplineRemapVal( flDeltaTime, 0.0f, CORRECTION_TIME, 0.2f, *pHomingSpeed ); flMinHomingDistance = SimpleSplineRemapVal( flDeltaTime, 0.0f, CORRECTION_TIME, MIN_NEAR_HOMING_DISTANCE, flMinHomingDistance ); flMaxHomingDistance = SimpleSplineRemapVal( flDeltaTime, 0.0f, CORRECTION_TIME, MAX_NEAR_HOMING_DISTANCE, flMaxHomingDistance ); } else { flMinHomingDistance = MIN_NEAR_HOMING_DISTANCE; flMaxHomingDistance = MAX_NEAR_HOMING_DISTANCE; Vector vecDelta; VectorSubtract( GetAbsOrigin(), *pActualDotPosition, vecDelta ); if ( vecDelta.z > MIN_HEIGHT_DIFFERENCE ) { float flClampedHeight = clamp( vecDelta.z, MIN_HEIGHT_DIFFERENCE, MAX_HEIGHT_DIFFERENCE ); float flHeightAdjustFactor = SimpleSplineRemapVal( flClampedHeight, MIN_HEIGHT_DIFFERENCE, MAX_HEIGHT_DIFFERENCE, 0.0f, 1.0f ); vecDelta.z = 0.0f; float flDist = VectorNormalize( vecDelta ); float flForwardOffset = 2000.0f; if ( flDist > flForwardOffset ) { Vector vecNewPosition; VectorMA( GetAbsOrigin(), -flForwardOffset, vecDelta, vecNewPosition ); vecNewPosition.z = pActualDotPosition->z; VectorLerp( *pActualDotPosition, vecNewPosition, flHeightAdjustFactor, *pActualDotPosition ); } } else { m_flReachedTargetTime = gpGlobals->curtime; } } // Allows for players right at the edge of rocket range to be threatened if ( flBlendTime > 0.6f ) { float flTargetLength = GetAbsOrigin().DistTo( pLaserTarget->WorldSpaceCenter() ); flTargetLength = clamp( flTargetLength, flMinHomingDistance, flMaxHomingDistance ); *pHomingSpeed = SimpleSplineRemapVal( flTargetLength, flMaxHomingDistance, flMinHomingDistance, *pHomingSpeed, 0.01f ); } } float flDot = DotProduct2D( vecTargetToShooter.AsVector2D(), vecTargetToMissile.AsVector2D() ); if ( ( flDot < 0 ) || m_bGuidingDisabled ) { *pHomingSpeed = 0.0f; } m_flLastHomingSpeed = *pHomingSpeed; // NDebugOverlay::Line( vecLeadPosition, GetAbsOrigin(), 0, 255, 0, true, 0.05f ); // NDebugOverlay::Line( GetAbsOrigin(), *pActualDotPosition, 255, 0, 0, true, 0.05f ); // NDebugOverlay::Cross3D( *pActualDotPosition, -Vector(4,4,4), Vector(4,4,4), 255, 0, 0, true, 0.05f ); } #endif #define RPG_BEAM_SPRITE "effects/laser1.vmt" #define RPG_BEAM_SPRITE_NOZ "effects/laser1_noz.vmt" #define RPG_LASER_SPRITE "sprites/redglow1" //============================================================================= // RPG //============================================================================= LINK_ENTITY_TO_CLASS( weapon_rpg, CWeaponRPG ); PRECACHE_WEAPON_REGISTER(weapon_rpg); IMPLEMENT_NETWORKCLASS_ALIASED( WeaponRPG, DT_WeaponRPG ) #ifdef CLIENT_DLL void RecvProxy_MissileDied( const CRecvProxyData *pData, void *pStruct, void *pOut ) { CWeaponRPG *pRPG = ((CWeaponRPG*)pStruct); RecvProxy_IntToEHandle( pData, pStruct, pOut ); CBaseEntity *pNewMissile = pRPG->GetMissile(); if ( pNewMissile == NULL ) { if ( pRPG->GetOwner() && pRPG->GetOwner()->GetActiveWeapon() == pRPG ) { pRPG->NotifyRocketDied(); } } } #endif BEGIN_NETWORK_TABLE( CWeaponRPG, DT_WeaponRPG ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bInitialStateUpdate ) ), RecvPropBool( RECVINFO( m_bGuiding ) ), RecvPropBool( RECVINFO( m_bHideGuiding ) ), RecvPropEHandle( RECVINFO( m_hMissile ), RecvProxy_MissileDied ), RecvPropVector( RECVINFO( m_vecLaserDot ) ), #else SendPropBool( SENDINFO( m_bInitialStateUpdate ) ), SendPropBool( SENDINFO( m_bGuiding ) ), SendPropBool( SENDINFO( m_bHideGuiding ) ), SendPropEHandle( SENDINFO( m_hMissile ) ), SendPropVector( SENDINFO( m_vecLaserDot ) ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CWeaponRPG ) DEFINE_PRED_FIELD( m_bInitialStateUpdate, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_bGuiding, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_bHideGuiding, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), END_PREDICTION_DATA() #endif #ifndef CLIENT_DLL acttable_t CWeaponRPG::m_acttable[] = { { ACT_HL2MP_IDLE, ACT_HL2MP_IDLE_RPG, false }, { ACT_HL2MP_RUN, ACT_HL2MP_RUN_RPG, false }, { ACT_HL2MP_IDLE_CROUCH, ACT_HL2MP_IDLE_CROUCH_RPG, false }, { ACT_HL2MP_WALK_CROUCH, ACT_HL2MP_WALK_CROUCH_RPG, false }, { ACT_HL2MP_GESTURE_RANGE_ATTACK, ACT_HL2MP_GESTURE_RANGE_ATTACK_RPG, false }, { ACT_HL2MP_GESTURE_RELOAD, ACT_HL2MP_GESTURE_RELOAD_RPG, false }, { ACT_HL2MP_JUMP, ACT_HL2MP_JUMP_RPG, false }, { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_RPG, false }, }; IMPLEMENT_ACTTABLE(CWeaponRPG); #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWeaponRPG::CWeaponRPG() { m_bReloadsSingly = true; m_bInitialStateUpdate= false; m_bHideGuiding = false; m_bGuiding = false; m_fMinRange1 = m_fMinRange2 = 40*12; m_fMaxRange1 = m_fMaxRange2 = 500*12; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWeaponRPG::~CWeaponRPG() { #ifndef CLIENT_DLL if ( m_hLaserDot != NULL ) { UTIL_Remove( m_hLaserDot ); m_hLaserDot = NULL; } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::Precache( void ) { BaseClass::Precache(); PrecacheScriptSound( "Missile.Ignite" ); PrecacheScriptSound( "Missile.Accelerate" ); // Laser dot... PrecacheModel( "sprites/redglow1.vmt" ); PrecacheModel( RPG_LASER_SPRITE ); PrecacheModel( RPG_BEAM_SPRITE ); PrecacheModel( RPG_BEAM_SPRITE_NOZ ); #ifndef CLIENT_DLL UTIL_PrecacheOther( "rpg_missile" ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::Activate( void ) { BaseClass::Activate(); // Restore the laser pointer after transition if ( m_bGuiding ) { CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner == NULL ) return; if ( pOwner->GetActiveWeapon() == this ) { StartGuiding(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponRPG::HasAnyAmmo( void ) { if ( m_hMissile != NULL ) return true; return BaseClass::HasAnyAmmo(); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponRPG::WeaponShouldBeLowered( void ) { // Lower us if we're out of ammo if ( !HasAnyAmmo() ) return true; return BaseClass::WeaponShouldBeLowered(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::PrimaryAttack( void ) { // Only the player fires this way so we can cast CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if (!pPlayer) return; // Can't have an active missile out if ( m_hMissile != NULL ) return; // Can't be reloading if ( GetActivity() == ACT_VM_RELOAD ) return; Vector vecOrigin; Vector vecForward; m_flNextPrimaryAttack = gpGlobals->curtime + 0.5f; CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner == NULL ) return; Vector vForward, vRight, vUp; pOwner->EyeVectors( &vForward, &vRight, &vUp ); Vector muzzlePoint = pOwner->Weapon_ShootPosition() + vForward * 12.0f + vRight * 6.0f + vUp * -3.0f; #ifndef CLIENT_DLL QAngle vecAngles; VectorAngles( vForward, vecAngles ); CMissile *pMissile = CMissile::Create( muzzlePoint, vecAngles, GetOwner()->edict() ); pMissile->m_hOwner = this; // If the shot is clear to the player, give the missile a grace period trace_t tr; Vector vecEye = pOwner->EyePosition(); UTIL_TraceLine( vecEye, vecEye + vForward * 128, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction == 1.0 ) { pMissile->SetGracePeriod( 0.3 ); } pMissile->SetDamage( GetHL2MPWpnData().m_iPlayerDamage ); m_hMissile = pMissile; #endif DecrementAmmo( GetOwner() ); SendWeaponAnim( ACT_VM_PRIMARYATTACK ); WeaponSound( SINGLE ); // player "shoot" animation pPlayer->SetAnimation( PLAYER_ATTACK1 ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pOwner - //----------------------------------------------------------------------------- void CWeaponRPG::DecrementAmmo( CBaseCombatCharacter *pOwner ) { // Take away our primary ammo type pOwner->RemoveAmmo( 1, m_iPrimaryAmmoType ); } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- void CWeaponRPG::SuppressGuiding( bool state ) { m_bHideGuiding = state; #ifndef CLIENT_DLL if ( m_hLaserDot == NULL ) { StartGuiding(); //STILL!? if ( m_hLaserDot == NULL ) return; } if ( state ) { m_hLaserDot->TurnOff(); } else { m_hLaserDot->TurnOn(); } #endif } //----------------------------------------------------------------------------- // Purpose: Override this if we're guiding a missile currently // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponRPG::Lower( void ) { if ( m_hMissile != NULL ) return false; return BaseClass::Lower(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::ItemPostFrame( void ) { BaseClass::ItemPostFrame(); CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer == NULL ) return; //If we're pulling the weapon out for the first time, wait to draw the laser if ( ( m_bInitialStateUpdate ) && ( GetActivity() != ACT_VM_DRAW ) ) { StartGuiding(); m_bInitialStateUpdate = false; } // Supress our guiding effects if we're lowered if ( GetIdealActivity() == ACT_VM_IDLE_LOWERED ) { SuppressGuiding(); } else { SuppressGuiding( false ); } //Move the laser UpdateLaserPosition(); if ( pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0 && m_hMissile == NULL ) { StopGuiding(); } } //----------------------------------------------------------------------------- // Purpose: // Output : Vector //----------------------------------------------------------------------------- Vector CWeaponRPG::GetLaserPosition( void ) { #ifndef CLIENT_DLL CreateLaserPointer(); if ( m_hLaserDot != NULL ) return m_hLaserDot->GetAbsOrigin(); //FIXME: The laser dot sprite is not active, this code should not be allowed! assert(0); #endif return vec3_origin; } //----------------------------------------------------------------------------- // Purpose: NPC RPG users cheat and directly set the laser pointer's origin // Input : &vecTarget - //----------------------------------------------------------------------------- void CWeaponRPG::UpdateNPCLaserPosition( const Vector &vecTarget ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::SetNPCLaserPosition( const Vector &vecTarget ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const Vector &CWeaponRPG::GetNPCLaserPosition( void ) { return vec3_origin; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true if the rocket is being guided, false if it's dumb //----------------------------------------------------------------------------- bool CWeaponRPG::IsGuiding( void ) { return m_bGuiding; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponRPG::Deploy( void ) { m_bInitialStateUpdate = true; return BaseClass::Deploy(); } bool CWeaponRPG::CanHolster( void ) { //Can't have an active missile out if ( m_hMissile != NULL ) return false; return BaseClass::CanHolster(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponRPG::Holster( CBaseCombatWeapon *pSwitchingTo ) { StopGuiding(); return BaseClass::Holster( pSwitchingTo ); } //----------------------------------------------------------------------------- // Purpose: Turn on the guiding laser //----------------------------------------------------------------------------- void CWeaponRPG::StartGuiding( void ) { // Don't start back up if we're overriding this if ( m_bHideGuiding ) return; m_bGuiding = true; #ifndef CLIENT_DLL WeaponSound(SPECIAL1); CreateLaserPointer(); #endif } //----------------------------------------------------------------------------- // Purpose: Turn off the guiding laser //----------------------------------------------------------------------------- void CWeaponRPG::StopGuiding( void ) { m_bGuiding = false; #ifndef CLIENT_DLL WeaponSound( SPECIAL2 ); // Kill the dot completely if ( m_hLaserDot != NULL ) { m_hLaserDot->TurnOff(); UTIL_Remove( m_hLaserDot ); m_hLaserDot = NULL; } #else if ( m_pBeam ) { //Tell it to die right away and let the beam code free it. m_pBeam->brightness = 0.0f; m_pBeam->flags &= ~FBEAM_FOREVER; m_pBeam->die = gpGlobals->curtime - 0.1; m_pBeam = NULL; } #endif } //----------------------------------------------------------------------------- // Purpose: Toggle the guiding laser //----------------------------------------------------------------------------- void CWeaponRPG::ToggleGuiding( void ) { if ( IsGuiding() ) { StopGuiding(); } else { StartGuiding(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::Drop( const Vector &vecVelocity ) { StopGuiding(); BaseClass::Drop( vecVelocity ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::UpdateLaserPosition( Vector vecMuzzlePos, Vector vecEndPos ) { #ifndef CLIENT_DLL if ( vecMuzzlePos == vec3_origin || vecEndPos == vec3_origin ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) return; vecMuzzlePos = pPlayer->Weapon_ShootPosition(); Vector forward; pPlayer->EyeVectors( &forward ); vecEndPos = vecMuzzlePos + ( forward * MAX_TRACE_LENGTH ); } //Move the laser dot, if active trace_t tr; // Trace out for the endpoint UTIL_TraceLine( vecMuzzlePos, vecEndPos, (MASK_SHOT & ~CONTENTS_WINDOW), GetOwner(), COLLISION_GROUP_NONE, &tr ); // Move the laser sprite if ( m_hLaserDot != NULL ) { Vector laserPos = tr.endpos; m_hLaserDot->SetLaserPosition( laserPos, tr.plane.normal ); if ( tr.DidHitNonWorldEntity() ) { CBaseEntity *pHit = tr.m_pEnt; if ( ( pHit != NULL ) && ( pHit->m_takedamage ) ) { m_hLaserDot->SetTargetEntity( pHit ); } else { m_hLaserDot->SetTargetEntity( NULL ); } } else { m_hLaserDot->SetTargetEntity( NULL ); } } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::CreateLaserPointer( void ) { #ifndef CLIENT_DLL if ( m_hLaserDot != NULL ) return; CBaseCombatCharacter *pOwner = GetOwner(); if ( pOwner == NULL ) return; if ( pOwner->GetAmmoCount(m_iPrimaryAmmoType) <= 0 ) return; m_hLaserDot = CLaserDot::Create( GetAbsOrigin(), GetOwner() ); m_hLaserDot->TurnOff(); UpdateLaserPosition(); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponRPG::NotifyRocketDied( void ) { m_hMissile = NULL; if ( GetActivity() == ACT_VM_RELOAD ) return; Reload(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponRPG::Reload( void ) { CBaseCombatCharacter *pOwner = GetOwner(); if ( pOwner == NULL ) return false; if ( pOwner->GetAmmoCount(m_iPrimaryAmmoType) <= 0 ) return false; WeaponSound( RELOAD ); SendWeaponAnim( ACT_VM_RELOAD ); return true; } #ifdef CLIENT_DLL #define RPG_MUZZLE_ATTACHMENT 1 #define RPG_GUIDE_ATTACHMENT 2 #define RPG_GUIDE_TARGET_ATTACHMENT 3 #define RPG_GUIDE_ATTACHMENT_3RD 4 #define RPG_GUIDE_TARGET_ATTACHMENT_3RD 5 #define RPG_LASER_BEAM_LENGTH 128 extern void FormatViewModelAttachment( Vector &vOrigin, bool bInverse ); //----------------------------------------------------------------------------- // Purpose: Returns the attachment point on either the world or viewmodel // This should really be worked into the CBaseCombatWeapon class! //----------------------------------------------------------------------------- void CWeaponRPG::GetWeaponAttachment( int attachmentId, Vector &outVector, Vector *dir /*= NULL*/ ) { QAngle angles; if ( ShouldDrawUsingViewModel() ) { CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner != NULL ) { pOwner->GetViewModel()->GetAttachment( attachmentId, outVector, angles ); ::FormatViewModelAttachment( outVector, true ); } } else { // We offset the IDs to make them correct for our world model BaseClass::GetAttachment( attachmentId, outVector, angles ); } // Supply the direction, if requested if ( dir != NULL ) { AngleVectors( angles, dir, NULL, NULL ); } } //----------------------------------------------------------------------------- // Purpose: Setup our laser beam //----------------------------------------------------------------------------- void CWeaponRPG::InitBeam( void ) { if ( m_pBeam != NULL ) return; CBaseCombatCharacter *pOwner = GetOwner(); if ( pOwner == NULL ) return; if ( pOwner->GetAmmoCount(m_iPrimaryAmmoType) <= 0 ) return; BeamInfo_t beamInfo; CBaseEntity *pEntity = NULL; if ( ShouldDrawUsingViewModel() ) { CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner != NULL ) { pEntity = pOwner->GetViewModel(); } } else { pEntity = this; } beamInfo.m_pStartEnt = pEntity; beamInfo.m_pEndEnt = pEntity; beamInfo.m_nType = TE_BEAMPOINTS; beamInfo.m_vecStart = vec3_origin; beamInfo.m_vecEnd = vec3_origin; beamInfo.m_pszModelName = ( ShouldDrawUsingViewModel() ) ? RPG_BEAM_SPRITE_NOZ : RPG_BEAM_SPRITE; beamInfo.m_flHaloScale = 0.0f; beamInfo.m_flLife = 0.0f; if ( ShouldDrawUsingViewModel() ) { beamInfo.m_flWidth = 2.0f; beamInfo.m_flEndWidth = 2.0f; beamInfo.m_nStartAttachment = RPG_GUIDE_ATTACHMENT; beamInfo.m_nEndAttachment = RPG_GUIDE_TARGET_ATTACHMENT; } else { beamInfo.m_flWidth = 1.0f; beamInfo.m_flEndWidth = 1.0f; beamInfo.m_nStartAttachment = RPG_GUIDE_ATTACHMENT_3RD; beamInfo.m_nEndAttachment = RPG_GUIDE_TARGET_ATTACHMENT_3RD; } beamInfo.m_flFadeLength = 0.0f; beamInfo.m_flAmplitude = 0; beamInfo.m_flBrightness = 255.0; beamInfo.m_flSpeed = 1.0f; beamInfo.m_nStartFrame = 0.0; beamInfo.m_flFrameRate = 30.0; beamInfo.m_flRed = 255.0; beamInfo.m_flGreen = 0.0; beamInfo.m_flBlue = 0.0; beamInfo.m_nSegments = 4; beamInfo.m_bRenderable = true; beamInfo.m_nFlags = (FBEAM_FOREVER|FBEAM_SHADEOUT); m_pBeam = beams->CreateBeamEntPoint( beamInfo ); } //----------------------------------------------------------------------------- // Purpose: Draw effects for our weapon //----------------------------------------------------------------------------- void CWeaponRPG::DrawEffects( void ) { // Must be guiding and not hidden if ( !m_bGuiding || m_bHideGuiding ) { if ( m_pBeam != NULL ) { m_pBeam->brightness = 0; } return; } // Setup our sprite if ( m_hSpriteMaterial == NULL ) { m_hSpriteMaterial.Init( RPG_LASER_SPRITE, TEXTURE_GROUP_CLIENT_EFFECTS ); } // Setup our beam if ( m_hBeamMaterial == NULL ) { m_hBeamMaterial.Init( RPG_BEAM_SPRITE, TEXTURE_GROUP_CLIENT_EFFECTS ); } color32 color={255,255,255,255}; Vector vecAttachment, vecDir; QAngle angles; float scale = 8.0f + random->RandomFloat( -2.0f, 2.0f ); int attachmentID = ( ShouldDrawUsingViewModel() ) ? RPG_GUIDE_ATTACHMENT : RPG_GUIDE_ATTACHMENT_3RD; GetWeaponAttachment( attachmentID, vecAttachment, &vecDir ); // Draw the sprite CMatRenderContextPtr pRenderContext( materials ); pRenderContext->Bind( m_hSpriteMaterial, this ); DrawSprite( vecAttachment, scale, scale, color ); // Get the beam's run trace_t tr; UTIL_TraceLine( vecAttachment, vecAttachment + ( vecDir * RPG_LASER_BEAM_LENGTH ), MASK_SHOT, GetOwner(), COLLISION_GROUP_NONE, &tr ); InitBeam(); if ( m_pBeam != NULL ) { m_pBeam->fadeLength = RPG_LASER_BEAM_LENGTH * tr.fraction; m_pBeam->brightness = random->RandomInt( 128, 200 ); } } //----------------------------------------------------------------------------- // Purpose: Called on third-person weapon drawing //----------------------------------------------------------------------------- int CWeaponRPG::DrawModel( int flags ) { // Only render these on the transparent pass if ( flags & STUDIO_TRANSPARENCY ) { DrawEffects(); return 1; } // Draw the model as normal return BaseClass::DrawModel( flags ); } //----------------------------------------------------------------------------- // Purpose: Called after first-person viewmodel is drawn //----------------------------------------------------------------------------- void CWeaponRPG::ViewModelDrawn( C_BaseViewModel *pBaseViewModel ) { // Draw our laser effects DrawEffects(); BaseClass::ViewModelDrawn( pBaseViewModel ); } //----------------------------------------------------------------------------- // Purpose: Used to determine sorting of model when drawn //----------------------------------------------------------------------------- bool CWeaponRPG::IsTranslucent( void ) { // Must be guiding and not hidden if ( m_bGuiding && !m_bHideGuiding ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: Turns off effects when leaving the PVS //----------------------------------------------------------------------------- void CWeaponRPG::NotifyShouldTransmit( ShouldTransmitState_t state ) { BaseClass::NotifyShouldTransmit(state); if ( state == SHOULDTRANSMIT_END ) { if ( m_pBeam != NULL ) { m_pBeam->brightness = 0.0f; } } } #endif //CLIENT_DLL //============================================================================= // Laser Dot //============================================================================= LINK_ENTITY_TO_CLASS( env_laserdot, CLaserDot ); BEGIN_DATADESC( CLaserDot ) DEFINE_FIELD( m_vecSurfaceNormal, FIELD_VECTOR ), DEFINE_FIELD( m_hTargetEnt, FIELD_EHANDLE ), DEFINE_FIELD( m_bVisibleLaserDot, FIELD_BOOLEAN ), DEFINE_FIELD( m_bIsOn, FIELD_BOOLEAN ), //DEFINE_FIELD( m_pNext, FIELD_CLASSPTR ), // don't save - regenerated by constructor END_DATADESC() //----------------------------------------------------------------------------- // Finds missiles in cone //----------------------------------------------------------------------------- CBaseEntity *CreateLaserDot( const Vector &origin, CBaseEntity *pOwner, bool bVisibleDot ) { return CLaserDot::Create( origin, pOwner, bVisibleDot ); } void SetLaserDotTarget( CBaseEntity *pLaserDot, CBaseEntity *pTarget ) { CLaserDot *pDot = assert_cast< CLaserDot* >(pLaserDot ); pDot->SetTargetEntity( pTarget ); } void EnableLaserDot( CBaseEntity *pLaserDot, bool bEnable ) { CLaserDot *pDot = assert_cast< CLaserDot* >(pLaserDot ); if ( bEnable ) { pDot->TurnOn(); } else { pDot->TurnOff(); } } CLaserDot::CLaserDot( void ) { m_hTargetEnt = NULL; m_bIsOn = true; #ifndef CLIENT_DLL g_LaserDotList.Insert( this ); #endif } CLaserDot::~CLaserDot( void ) { #ifndef CLIENT_DLL g_LaserDotList.Remove( this ); #endif } //----------------------------------------------------------------------------- // Purpose: // Input : &origin - // Output : CLaserDot //----------------------------------------------------------------------------- CLaserDot *CLaserDot::Create( const Vector &origin, CBaseEntity *pOwner, bool bVisibleDot ) { #ifndef CLIENT_DLL CLaserDot *pLaserDot = (CLaserDot *) CBaseEntity::Create( "env_laserdot", origin, QAngle(0,0,0) ); if ( pLaserDot == NULL ) return NULL; pLaserDot->m_bVisibleLaserDot = bVisibleDot; pLaserDot->SetMoveType( MOVETYPE_NONE ); pLaserDot->AddSolidFlags( FSOLID_NOT_SOLID ); pLaserDot->AddEffects( EF_NOSHADOW ); UTIL_SetSize( pLaserDot, -Vector(4,4,4), Vector(4,4,4) ); pLaserDot->SetOwnerEntity( pOwner ); pLaserDot->AddEFlags( EFL_FORCE_CHECK_TRANSMIT ); if ( !bVisibleDot ) { pLaserDot->MakeInvisible(); } return pLaserDot; #else return NULL; #endif } void CLaserDot::SetLaserPosition( const Vector &origin, const Vector &normal ) { SetAbsOrigin( origin ); m_vecSurfaceNormal = normal; } Vector CLaserDot::GetChasePosition() { return GetAbsOrigin() - m_vecSurfaceNormal * 10; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLaserDot::TurnOn( void ) { m_bIsOn = true; if ( m_bVisibleLaserDot ) { //BaseClass::TurnOn(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLaserDot::TurnOff( void ) { m_bIsOn = false; if ( m_bVisibleLaserDot ) { //BaseClass::TurnOff(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CLaserDot::MakeInvisible( void ) { } #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: Draw our sprite //----------------------------------------------------------------------------- int CLaserDot::DrawModel( int flags ) { color32 color={255,255,255,255}; Vector vecAttachment, vecDir; QAngle angles; float scale; Vector endPos; C_HL2MP_Player *pOwner = ToHL2MPPlayer( GetOwnerEntity() ); if ( pOwner != NULL && pOwner->IsDormant() == false ) { // Always draw the dot in front of our faces when in first-person if ( pOwner->IsLocalPlayer() ) { // Take our view position and orientation vecAttachment = CurrentViewOrigin(); vecDir = CurrentViewForward(); } else { // Take the eye position and direction vecAttachment = pOwner->EyePosition(); QAngle angles = pOwner->GetAnimEyeAngles(); AngleVectors( angles, &vecDir ); } trace_t tr; UTIL_TraceLine( vecAttachment, vecAttachment + ( vecDir * MAX_TRACE_LENGTH ), MASK_SHOT, pOwner, COLLISION_GROUP_NONE, &tr ); // Backup off the hit plane endPos = tr.endpos + ( tr.plane.normal * 4.0f ); } else { // Just use our position if we can't predict it otherwise endPos = GetAbsOrigin(); } // Randomly flutter scale = 16.0f + random->RandomFloat( -4.0f, 4.0f ); // Draw our laser dot in space CMatRenderContextPtr pRenderContext( materials ); pRenderContext->Bind( m_hSpriteMaterial, this ); DrawSprite( endPos, scale, scale, color ); return 1; } //----------------------------------------------------------------------------- // Purpose: Setup our sprite reference //----------------------------------------------------------------------------- void CLaserDot::OnDataChanged( DataUpdateType_t updateType ) { if ( updateType == DATA_UPDATE_CREATED ) { m_hSpriteMaterial.Init( RPG_LASER_SPRITE, TEXTURE_GROUP_CLIENT_EFFECTS ); } } #endif //CLIENT_DLL
0
0.960941
1
0.960941
game-dev
MEDIA
0.985935
game-dev
0.694009
1
0.694009
cbhust8025/ChromiumBase
2,821
src/Chromium/Base/android/build_info.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/android/build_info.h" #include <string> #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/scoped_java_ref.h" #include "base/base_jni_headers/BuildInfo_jni.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/strings/string_number_conversions.h" namespace base { namespace android { namespace { // We are leaking these strings. const char* StrDupParam(const std::vector<std::string>& params, int index) { return strdup(params[index].c_str()); } int GetIntParam(const std::vector<std::string>& params, int index) { int ret = 0; bool success = StringToInt(params[index], &ret); DCHECK(success); return ret; } } // namespace struct BuildInfoSingletonTraits { static BuildInfo* New() { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobjectArray> params_objs = Java_BuildInfo_getAll(env); std::vector<std::string> params; AppendJavaStringArrayToStringVector(env, params_objs, &params); return new BuildInfo(params); } static void Delete(BuildInfo* x) { // We're leaking this type, see kRegisterAtExit. NOTREACHED(); } static const bool kRegisterAtExit = false; #if DCHECK_IS_ON() static const bool kAllowedToAccessOnNonjoinableThread = true; #endif }; BuildInfo::BuildInfo(const std::vector<std::string>& params) : brand_(StrDupParam(params, 0)), device_(StrDupParam(params, 1)), android_build_id_(StrDupParam(params, 2)), manufacturer_(StrDupParam(params, 3)), model_(StrDupParam(params, 4)), sdk_int_(GetIntParam(params, 5)), build_type_(StrDupParam(params, 6)), board_(StrDupParam(params, 7)), host_package_name_(StrDupParam(params, 8)), host_version_code_(StrDupParam(params, 9)), host_package_label_(StrDupParam(params, 10)), package_name_(StrDupParam(params, 11)), package_version_code_(StrDupParam(params, 12)), package_version_name_(StrDupParam(params, 13)), android_build_fp_(StrDupParam(params, 14)), gms_version_code_(StrDupParam(params, 15)), installer_package_name_(StrDupParam(params, 16)), abi_name_(StrDupParam(params, 17)), firebase_app_id_(StrDupParam(params, 18)), custom_themes_(StrDupParam(params, 19)), resources_version_(StrDupParam(params, 20)), extracted_file_suffix_(params[21]), is_at_least_q_(GetIntParam(params, 22)), is_debug_android_(GetIntParam(params, 23)) {} // static BuildInfo* BuildInfo::GetInstance() { return Singleton<BuildInfo, BuildInfoSingletonTraits >::get(); } } // namespace android } // namespace base
0
0.819722
1
0.819722
game-dev
MEDIA
0.081585
game-dev
0.680183
1
0.680183
MCreator-Examples/Tale-of-Biomes
4,752
src/main/java/net/nwtg/taleofbiomes/block/entity/LowCapacityCableLBlockEntity.java
package net.nwtg.taleofbiomes.block.entity; import net.nwtg.taleofbiomes.init.TaleOfBiomesModBlockEntities; import net.neoforged.neoforge.items.wrapper.SidedInvWrapper; import net.neoforged.neoforge.energy.EnergyStorage; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.ContainerHelper; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.chat.Component; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.CompoundTag; import net.minecraft.core.NonNullList; import net.minecraft.core.HolderLookup; import net.minecraft.core.Direction; import net.minecraft.core.BlockPos; import javax.annotation.Nullable; import java.util.stream.IntStream; public class LowCapacityCableLBlockEntity extends RandomizableContainerBlockEntity implements WorldlyContainer { private NonNullList<ItemStack> stacks = NonNullList.<ItemStack>withSize(0, ItemStack.EMPTY); private final SidedInvWrapper handler = new SidedInvWrapper(this, null); public LowCapacityCableLBlockEntity(BlockPos position, BlockState state) { super(TaleOfBiomesModBlockEntities.LOW_CAPACITY_CABLE_L.get(), position, state); } @Override public void loadAdditional(CompoundTag compound, HolderLookup.Provider lookupProvider) { super.loadAdditional(compound, lookupProvider); if (!this.tryLoadLootTable(compound)) this.stacks = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); ContainerHelper.loadAllItems(compound, this.stacks, lookupProvider); if (compound.get("energyStorage") instanceof IntTag intTag) energyStorage.deserializeNBT(lookupProvider, intTag); } @Override public void saveAdditional(CompoundTag compound, HolderLookup.Provider lookupProvider) { super.saveAdditional(compound, lookupProvider); if (!this.trySaveLootTable(compound)) { ContainerHelper.saveAllItems(compound, this.stacks, lookupProvider); } compound.put("energyStorage", energyStorage.serializeNBT(lookupProvider)); } @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } @Override public CompoundTag getUpdateTag(HolderLookup.Provider lookupProvider) { return this.saveWithFullMetadata(lookupProvider); } @Override public int getContainerSize() { return stacks.size(); } @Override public boolean isEmpty() { for (ItemStack itemstack : this.stacks) if (!itemstack.isEmpty()) return false; return true; } @Override public Component getDefaultName() { return Component.literal("low_capacity_cable_l"); } @Override public int getMaxStackSize() { return 64; } @Override public AbstractContainerMenu createMenu(int id, Inventory inventory) { return ChestMenu.threeRows(id, inventory); } @Override public Component getDisplayName() { return Component.literal("Low Capacity Cable"); } @Override protected NonNullList<ItemStack> getItems() { return this.stacks; } @Override protected void setItems(NonNullList<ItemStack> stacks) { this.stacks = stacks; } @Override public boolean canPlaceItem(int index, ItemStack stack) { return true; } @Override public int[] getSlotsForFace(Direction side) { return IntStream.range(0, this.getContainerSize()).toArray(); } @Override public boolean canPlaceItemThroughFace(int index, ItemStack stack, @Nullable Direction direction) { return this.canPlaceItem(index, stack); } @Override public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction) { return true; } public SidedInvWrapper getItemHandler() { return handler; } private final EnergyStorage energyStorage = new EnergyStorage(64, 64, 64, 0) { @Override public int receiveEnergy(int maxReceive, boolean simulate) { int retval = super.receiveEnergy(maxReceive, simulate); if (!simulate) { setChanged(); level.sendBlockUpdated(worldPosition, level.getBlockState(worldPosition), level.getBlockState(worldPosition), 2); } return retval; } @Override public int extractEnergy(int maxExtract, boolean simulate) { int retval = super.extractEnergy(maxExtract, simulate); if (!simulate) { setChanged(); level.sendBlockUpdated(worldPosition, level.getBlockState(worldPosition), level.getBlockState(worldPosition), 2); } return retval; } }; public EnergyStorage getEnergyStorage() { return energyStorage; } }
0
0.927553
1
0.927553
game-dev
MEDIA
0.997974
game-dev
0.957858
1
0.957858
MothCocoon/FlowGraph
3,542
Source/Flow/Private/Types/FlowInjectComponentsHelper.cpp
// Copyright https://github.com/MothCocoon/FlowGraph/graphs/contributors #include "Types/FlowInjectComponentsHelper.h" #include "Components/ActorComponent.h" #include "GameFramework/Actor.h" #include "FlowLogChannels.h" #include UE_INLINE_GENERATED_CPP_BY_NAME(FlowInjectComponentsHelper) TArray<UActorComponent*> FFlowInjectComponentsHelper::CreateComponentInstancesForActor(AActor& Actor) { TArray<UActorComponent*> ComponentInstances; if (ComponentTemplates.IsEmpty() && ComponentClasses.IsEmpty()) { return ComponentInstances; } // If the desired component does not already exist, add it to the ActorOwner for (UActorComponent* ComponentTemplate : ComponentTemplates) { if (!IsValid(ComponentTemplate)) { UE_LOG(LogFlow, Warning, TEXT("Cannot inject a null component!")); continue; } if (UActorComponent* ComponentInstance = TryCreateComponentInstanceForActorFromTemplate(Actor, *ComponentTemplate)) { ComponentInstances.Add(ComponentInstance); } } for (TSubclassOf<UActorComponent> ComponentClass : ComponentClasses) { if (!IsValid(ComponentClass)) { UE_LOG(LogFlow, Warning, TEXT("Cannot inject a null component class!")); continue; } const FName InstanceBaseName = ComponentClass->GetFName(); if (UActorComponent* ComponentInstance = TryCreateComponentInstanceForActorFromClass(Actor, ComponentClass, InstanceBaseName)) { ComponentInstances.Add(ComponentInstance); } } return ComponentInstances; } UActorComponent* FFlowInjectComponentsHelper::TryCreateComponentInstanceForActorFromTemplate(AActor& Actor, UActorComponent& ComponentTemplate) { // Following pattern from UGameFrameworkComponentManager::CreateComponentOnInstance() UClass* ComponentClass = ComponentTemplate.GetClass(); if (!ComponentClass->GetDefaultObject<UActorComponent>()->GetIsReplicated() || Actor.GetLocalRole() == ROLE_Authority) { const EObjectFlags InstanceFlags = ComponentTemplate.GetFlags() | RF_Transient; UActorComponent* ComponentInstance = NewObject<UActorComponent>(&Actor, ComponentTemplate.GetClass(), ComponentTemplate.GetFName(), InstanceFlags, &ComponentTemplate); return ComponentInstance; } return nullptr; } UActorComponent* FFlowInjectComponentsHelper::TryCreateComponentInstanceForActorFromClass(AActor& Actor, TSubclassOf<UActorComponent> ComponentClass, const FName& InstanceBaseName) { // Following pattern from UGameFrameworkComponentManager::CreateComponentOnInstance() if (ComponentClass && (!ComponentClass->GetDefaultObject<UActorComponent>()->GetIsReplicated() || Actor.GetLocalRole() == ROLE_Authority)) { const FName UniqueName = MakeUniqueObjectName(&Actor, ComponentClass, InstanceBaseName); UActorComponent* ComponentInstance = NewObject<UActorComponent>(&Actor, ComponentClass, UniqueName); return ComponentInstance; } return nullptr; } void FFlowInjectComponentsHelper::InjectCreatedComponent(AActor& Actor, UActorComponent& ComponentInstance) { // Following pattern from UGameFrameworkComponentManager::CreateComponentOnInstance() if (USceneComponent* SceneComponentInstance = Cast<USceneComponent>(&ComponentInstance)) { SceneComponentInstance->SetupAttachment(Actor.GetRootComponent()); } ComponentInstance.RegisterComponent(); } void FFlowInjectComponentsHelper::DestroyInjectedComponent(AActor& Actor, UActorComponent& ComponentInstance) { // Following pattern from UGameFrameworkComponentManager::DestroyInstancedComponent() ComponentInstance.DestroyComponent(); ComponentInstance.SetFlags(RF_Transient); }
0
0.711718
1
0.711718
game-dev
MEDIA
0.916824
game-dev
0.58453
1
0.58453
demilich1/metastone
3,153
app/src/main/java/net/demilich/metastone/gui/deckbuilder/DeckBuilderMediator.java
package net.demilich.metastone.gui.deckbuilder; import java.util.ArrayList; import java.util.List; import net.demilich.nittygrittymvc.Mediator; import net.demilich.nittygrittymvc.interfaces.INotification; import net.demilich.metastone.GameNotification; import net.demilich.metastone.game.cards.Card; import net.demilich.metastone.game.decks.Deck; import net.demilich.metastone.game.decks.DeckFormat; import net.demilich.metastone.game.decks.validation.DefaultDeckValidator; import net.demilich.metastone.gui.dialog.DialogNotification; import net.demilich.metastone.gui.dialog.DialogType; public class DeckBuilderMediator extends Mediator<GameNotification> { public static final String NAME = "DeckBuilderMediator"; private final DeckBuilderView view; public DeckBuilderMediator() { super(NAME); view = new DeckBuilderView(); } @SuppressWarnings("unchecked") @Override public void handleNotification(final INotification<GameNotification> notification) { switch (notification.getId()) { case CREATE_NEW_DECK: DeckProxy deckProxy = (DeckProxy) getFacade().retrieveProxy(DeckProxy.NAME); deckProxy.setActiveDeckValidator(new DefaultDeckValidator()); view.createNewDeck(); break; case EDIT_DECK: view.editDeck((Deck) notification.getBody()); break; case ACTIVE_DECK_CHANGED: view.activeDeckChanged((Deck) notification.getBody()); break; case FILTERED_CARDS: view.filteredCards((List<Card>) notification.getBody()); break; case DECKS_LOADED: view.displayDecks((List<Deck>) notification.getBody()); break; case INVALID_DECK_NAME: DialogNotification dialogNotification = new DialogNotification("Name your deck", "Please enter a valid name for this deck.", DialogType.WARNING); getFacade().notifyObservers(dialogNotification); break; case DECK_FORMATS_LOADED: List<DeckFormat> deckFormats = (List<DeckFormat>) notification.getBody(); view.injectDeckFormats(deckFormats); break; case DUPLICATE_DECK_NAME: getFacade().notifyObservers(new DialogNotification("Duplicate deck name", "This deck name was already used for another deck. Please choose another name", DialogType.WARNING)); break; default: break; } } @Override public List<GameNotification> listNotificationInterests() { List<GameNotification> notificationInterests = new ArrayList<GameNotification>(); notificationInterests.add(GameNotification.CREATE_NEW_DECK); notificationInterests.add(GameNotification.EDIT_DECK); notificationInterests.add(GameNotification.FILTERED_CARDS); notificationInterests.add(GameNotification.ACTIVE_DECK_CHANGED); notificationInterests.add(GameNotification.DECKS_LOADED); notificationInterests.add(GameNotification.DECK_FORMATS_LOADED); notificationInterests.add(GameNotification.INVALID_DECK_NAME); notificationInterests.add(GameNotification.DUPLICATE_DECK_NAME); return notificationInterests; } @Override public void onRegister() { getFacade().sendNotification(GameNotification.SHOW_VIEW, view); getFacade().sendNotification(GameNotification.LOAD_DECKS); getFacade().sendNotification(GameNotification.LOAD_DECK_FORMATS); } }
0
0.893736
1
0.893736
game-dev
MEDIA
0.450513
game-dev,desktop-app
0.794442
1
0.794442
chrislo27/RhythmHeavenRemixEditor
3,896
core/src/main/kotlin/io/github/chrislo27/rhre3/playalong/PlayalongControls.kt
package io.github.chrislo27.rhre3.playalong import com.badlogic.gdx.Input import java.util.* data class PlayalongControls(var buttonA: Int = Input.Keys.J, var buttonB: Int = Input.Keys.K, var buttonLeft: Int = Input.Keys.A, var buttonRight: Int = Input.Keys.D, var buttonUp: Int = Input.Keys.W, var buttonDown: Int = Input.Keys.S) { companion object { val QWERTY_WASD_JK = PlayalongControls() val AZERTY_ZSQD_JK = PlayalongControls(buttonLeft = Input.Keys.Q, buttonRight = Input.Keys.D, buttonUp = Input.Keys.Z, buttonDown = Input.Keys.S) val ARROW_KEYS_ZX = PlayalongControls(Input.Keys.Z, Input.Keys.X, Input.Keys.LEFT, Input.Keys.RIGHT, Input.Keys.UP, Input.Keys.DOWN) val ARROW_KEYS_WX = PlayalongControls(Input.Keys.W, Input.Keys.X, Input.Keys.LEFT, Input.Keys.RIGHT, Input.Keys.UP, Input.Keys.DOWN) val QWERTY_IJKL = PlayalongControls(Input.Keys.Z, Input.Keys.X, Input.Keys.J, Input.Keys.L, Input.Keys.I, Input.Keys.K) val AZERTY_IJKL = PlayalongControls(Input.Keys.W, Input.Keys.X, Input.Keys.J, Input.Keys.L, Input.Keys.I, Input.Keys.K) val QWERTY_WASD_JN = PlayalongControls(buttonB = Input.Keys.N) val AZERTY_ZSQD_JN = PlayalongControls(buttonB = Input.Keys.N, buttonLeft = Input.Keys.Q, buttonRight = Input.Keys.D, buttonUp = Input.Keys.Z, buttonDown = Input.Keys.S) val INVALID = PlayalongControls(-1, -1, -1, -1, -1, -1) val strCustom = "Custom" val standardControls: Map<String, PlayalongControls> = mapOf( "QWERTY WASD/JK" to QWERTY_WASD_JK, "QWERTY Arrow Keys/ZX" to ARROW_KEYS_ZX, "QWERTY IJKL/ZX" to QWERTY_IJKL, "QWERTY WASD/JN" to QWERTY_WASD_JN, "AZERTY ZSQD/JK" to AZERTY_ZSQD_JK, "AZERTY Arrow Keys/WX" to ARROW_KEYS_WX, "AZERTY IJKL/WX" to AZERTY_IJKL, "AZERTY ZSQD/JN" to AZERTY_ZSQD_JN ) } fun toInputMap(): Map<PlayalongInput, Set<Int>> { return linkedMapOf(PlayalongInput.BUTTON_A to setOf(buttonA), PlayalongInput.BUTTON_B to setOf(buttonB), PlayalongInput.BUTTON_DPAD_UP to setOf(buttonUp), PlayalongInput.BUTTON_DPAD_DOWN to setOf(buttonDown), PlayalongInput.BUTTON_DPAD_LEFT to setOf(buttonLeft), PlayalongInput.BUTTON_DPAD_RIGHT to setOf(buttonRight), PlayalongInput.BUTTON_A_OR_DPAD to setOf(buttonA, buttonUp, buttonDown, buttonLeft, buttonRight), PlayalongInput.BUTTON_DPAD to setOf(buttonUp, buttonDown, buttonLeft, buttonRight) ) } fun toInputString(selected: EnumSet<PlayalongInput>? = null): String { val inputMap = linkedMapOf(PlayalongInput.BUTTON_A to setOf(buttonA), PlayalongInput.BUTTON_B to setOf(buttonB), PlayalongInput.BUTTON_DPAD_UP to setOf(buttonUp), PlayalongInput.BUTTON_DPAD_DOWN to setOf(buttonDown), PlayalongInput.BUTTON_DPAD_LEFT to setOf(buttonLeft), PlayalongInput.BUTTON_DPAD_RIGHT to setOf(buttonRight) ) return inputMap.entries.joinToString(separator = " [GRAY]|[] ") { (k, v) -> val isSelected = selected?.contains(k) == true "${if (isSelected) "[CYAN]" else ""}${k.longDisplayText}${if (isSelected) "[]" else ""} - ${v.joinToString(separator = ", ") { Input.Keys.toString(it) }}" } } }
0
0.76361
1
0.76361
game-dev
MEDIA
0.856382
game-dev
0.814521
1
0.814521
Froser/gamemachine
72,851
src/demo/premiere/timeline.cpp
#include "stdafx.h" #include "timeline.h" #include <gmimagebuffer.h> #include <gmimage.h> #include <gmgameobject.h> #include <gmlight.h> #include <gmmodelreader.h> #include <gmutilities.h> #include <gmparticle.h> #include <gmm.h> #include "helper.h" #include <gmphysicsshape.h> #include "handler.h" #define NoCameraComponent 0 #define PositionComponent 0x01 #define DirectionComponent 0x02 #define FocusAtComponent 0x04 #define PerspectiveComponent 0x01 #define CameraLookAtComponent 0x02 #define OrthoComponent 0x04 template <typename T> struct AssetCast_ { typedef AutoReleasePtr<T>* Type; }; template <typename T> auto asset_cast(void* obj) { return static_cast<typename AssetCast_<T>::Type>(obj); } template <> auto asset_cast<GMCamera>(void* obj) { return static_cast<GMCamera*>(obj); } template <> auto asset_cast<GMShadowSourceDesc>(void* obj) { return static_cast<GMShadowSourceDesc*>(obj); } struct CameraParams { union { struct { GMfloat left, right, top, bottom; }; struct { GMfloat fovy, aspect; }; }; GMfloat n, f; }; template<class T> struct Nullable { T value; bool isNull; Nullable() : isNull(true) {} Nullable(const T& val) : value(val), isNull(false) {} Nullable& operator=(T&& val) { isNull = false; value = std::forward<T>(val); return *this; } operator T&() { return value; } operator const T&() const { return value; } }; namespace { template <typename First> bool isAny(First first) { return !!first; } template <typename First, typename... Others> bool isAny(First first, Others... other) { return !!first || isAny(other...); } template <typename P, typename First, typename... Others> void callEvery_1(P&& param, First first) { if (first) first(std::forward<P>(param)); } template <typename P, typename First, typename... Others> void callEvery_1(P&& param, First first, Others... other) { if (first) first(std::forward<P>(param)); callEvery_1(std::forward<P>(param), other...); } template <AssetType Type, typename Container> bool getAssetAndType(Container& container, const GMString& objectName, REF AssetType& result, OUT void** out) { result = AssetType::NotFound; decltype(container.end()) iter; if ((iter = container.find(objectName)) != container.end()) { result = Type; if (out) (*out) = &(iter->second); return true; } return false; } bool toBool(const GMString& str) { if (str == L"true") return true; if (str == L"false") return false; gm_warning(gm_dbg_wrap("Unrecognized boolean string '{0}', treats as false."), str); return false; } GMS_BlendFunc toBlendFunc(const GMString& str) { GMS_BlendFunc result = GMS_BlendFunc::One; if (str == L"Zero") result = GMS_BlendFunc::Zero; else if (str == L"One") result = GMS_BlendFunc::One; else if (str == L"SourceColor") result = GMS_BlendFunc::SourceColor; else if (str == L"DestColor") result = GMS_BlendFunc::DestColor; else if (str == L"SourceAlpha") result = GMS_BlendFunc::SourceAlpha; else if (str == L"DestAlpha") result = GMS_BlendFunc::DestAlpha; else if (str == L"OneMinusSourceAlpha") result = GMS_BlendFunc::OneMinusSourceAlpha; else if (str == L"OneMinusDestAlpha") result = GMS_BlendFunc::OneMinusDestAlpha; else if (str == L"OneMinusSourceColor") result = GMS_BlendFunc::OneMinusSourceColor; else if (str == L"OneMinusDestColor") result = GMS_BlendFunc::OneMinusDestColor; else gm_warning(gm_dbg_wrap("Unrecognized blend function string '{0}', treats as One."), str); return result; } } enum Animation { Camera, Light, GameObject, EndOfAnimation, }; AnimationContainer::AnimationContainer() : m_playingAnimationIndex(0) , m_editingAnimationIndex(-1) { } void AnimationContainer::newAnimation() { m_animations.resize(m_animations.size() + 1); } void AnimationContainer::playAnimation() { m_animations[m_playingAnimationIndex].play(); } void AnimationContainer::pauseAnimation() { m_animations[m_playingAnimationIndex].pause(); } void AnimationContainer::updateAnimation(GMfloat dt) { m_animations[m_playingAnimationIndex].update(dt); } GMAnimation& AnimationContainer::currentEditingAnimation() { return m_animations[m_editingAnimationIndex]; } void AnimationContainer::nextEditAnimation() { ++m_editingAnimationIndex; if (gm_sizet_to_int(m_animations.size()) >= m_editingAnimationIndex) newAnimation(); } void AnimationContainer::nextPlayingAnimation() { ++m_playingAnimationIndex; if (gm_sizet_to_int(m_animations.size()) >= m_playingAnimationIndex) newAnimation(); } Timeline::Timeline(const IRenderContext* context, GMGameWorld* world) : m_context(context) , m_world(world) , m_timeline(0) , m_playing(false) , m_finished(false) , m_lastTime(0) , m_checkpointTime(0) , m_audioPlayer(gmm::GMMFactory::getAudioPlayer()) , m_audioReader(gmm::GMMFactory::getAudioReader()) { GM_ASSERT(m_context && m_world); m_animations.resize(EndOfAnimation); m_world->setParticleSystemManager(new GMParticleSystemManager(m_context)); } Timeline::~Timeline() { } bool Timeline::parse(const GMString& timelineContent) { initPresetConstants(); GMXMLDocument doc; std::string content = timelineContent.toStdString(); if (GMXMLError::XML_SUCCESS == doc.Parse(content.c_str())) { auto root = doc.RootElement(); if (GMString::stringEquals(root->Name(), "timeline")) { auto firstElement = root->FirstChildElement(); parseElements(firstElement); return true; } } else { gm_warning(gm_dbg_wrap("Parse timeline file error: {0}, {1}, {2}"), GMString(doc.ErrorLineNum()), GMString(doc.ErrorName()), GMString(doc.ErrorStr())); } return false; } bool Timeline::parseComponent(const GMString& componentContent) { GMXMLDocument doc; std::string content = componentContent.toStdString(); if (GMXMLError::XML_SUCCESS == doc.Parse(content.c_str())) { auto root = doc.RootElement(); if (GMString::stringEquals(root->Name(), "component")) { auto firstElement = root->FirstChildElement(); parseElements(firstElement); return true; } } else { gm_warning(gm_dbg_wrap("Parse component file error: {0}, {1}, {2}"), GMString(doc.ErrorLineNum()), GMString(doc.ErrorName()), GMString(doc.ErrorStr())); } return false; } void Timeline::update(GMDuration dt) { if (m_playing) { if (m_timeline == 0) runImmediateActions(); else runActions(); m_timeline += dt; } for (auto& animationList : m_animations) { for (auto& animation : animationList) { animation.second.updateAnimation(dt); } } } void Timeline::play() { m_currentAction = m_deferredActions.begin(); m_playing = true; } GMString Timeline::getValueFromDefines(GMString id) { GMString sign; if (id.startsWith("+") || id.startsWith("-")) { sign = id[0]; id = id.substr(1, id.length() - 1); } if (id.startsWith("$")) { GMString key = id.substr(1, id.length() - 1); auto replacementIter = m_defines.find(key); if (replacementIter != m_defines.end()) return sign + replacementIter->second; replacementIter = m_presetConstants.find(key); if (replacementIter != m_presetConstants.end()) return sign + replacementIter->second; } else if (id.startsWith("@")) { GMString key = id.substr(1, id.length() - 1); GMString result; if (m_slots.getSlotByName(key, result)) return sign + result; } return sign + id; } void Timeline::pause() { m_playing = false; for (auto& animationList : m_animations) { for (auto& animation : animationList) { animation.second.pauseAnimation(); } } } void Timeline::initPresetConstants() { // 写入一些常量 const GMRect& winRc = m_context->getWindow()->getRenderRect(); m_presetConstants["GM_screenWidth"] = GMString(winRc.width); m_presetConstants["GM_screenHeight"] = GMString(winRc.height); } void Timeline::parseElements(GMXMLElement* e) { while (e) { GMString name = e->Name(); if (name == L"defines") { parseDefines(e->FirstChildElement()); } else if (name == L"assets") { parseAssets(e->FirstChildElement()); } else if (name == L"objects") { parseObjects(e->FirstChildElement()); } else if (name == L"actions") { parseActions(e->FirstChildElement()); } e = e->NextSiblingElement(); } } void Timeline::parseDefines(GMXMLElement* e) { while (e) { GMString text = getValueFromDefines(e->GetText()); auto result = m_defines.insert(std::make_pair(e->Name(), text)); if (!result.second) gm_warning(gm_dbg_wrap("The define name '{0}' has been already taken."), e->Name()); e = e->NextSiblingElement(); } } void Timeline::parseAssets(GMXMLElement* e) { auto package = GM.getGamePackageManager(); while (e) { GMString id = e->Attribute("id"); GMString name = e->Name(); if (name == L"cubemap") { GMBuffer l, r, u, d, f, b; package->readFile(GMPackageIndex::Textures, e->Attribute("left"), &l); package->readFile(GMPackageIndex::Textures, e->Attribute("right"), &r); package->readFile(GMPackageIndex::Textures, e->Attribute("up"), &u); package->readFile(GMPackageIndex::Textures, e->Attribute("down"), &d); package->readFile(GMPackageIndex::Textures, e->Attribute("front"), &f); package->readFile(GMPackageIndex::Textures, e->Attribute("back"), &b); if (l.getSize() > 0 && r.getSize() > 0 && f.getSize() > 0 && b.getSize() > 0 && u.getSize() > 0 && d.getSize() > 0) { GMImage *imgl, *imgr, *imgu, *imgd, *imgf, *imgb; if (GMImageReader::load(l.getData(), l.getSize(), &imgl) && GMImageReader::load(r.getData(), r.getSize(), &imgr) && GMImageReader::load(u.getData(), u.getSize(), &imgu) && GMImageReader::load(d.getData(), d.getSize(), &imgd) && GMImageReader::load(f.getData(), f.getSize(), &imgf) && GMImageReader::load(b.getData(), b.getSize(), &imgb)) { GMCubeMapBuffer cubeMap(*imgr, *imgl, *imgu, *imgd, *imgf, *imgb); GMTextureAsset cubeMapTex; GM.getFactory()->createTexture(m_context, &cubeMap, cubeMapTex); GM_delete(imgl); GM_delete(imgr); GM_delete(imgu); GM_delete(imgd); GM_delete(imgf); GM_delete(imgb); m_assets[id] = cubeMapTex; } else { gm_warning(gm_dbg_wrap("Load image failed. Id: {0}"), id); } } else { gm_warning(gm_dbg_wrap("Load asset failed. Id: {0}"), id); } } else if (name == L"texture") { GMString file = e->Attribute("file"); GMTextureAsset asset = GMToolUtil::createTexture(m_context, file); if (asset.isEmpty()) { gm_warning(gm_dbg_wrap("Load asset failed. Id: {0}"), id); } else { m_assets[id] = asset; } } else if (name == L"pbr") { GMString albedo = e->Attribute("albedo"); GMString metallic = e->Attribute("metallic"); GMString roughness = e->Attribute("roughness"); GMString ao = e->Attribute("ao"); GMString normal = e->Attribute("normal"); PBR pbr; bool b = GMToolUtil::createPBRTextures( m_context, albedo, metallic, roughness, ao, normal, pbr.albedo, pbr.metallicRoughnessAO, pbr.normal ); if (!b) { gm_warning(gm_dbg_wrap("Create PBR texture failed: {0}"), id); } else { m_pbrs[id] = pbr; } } else if (name == L"object") { GMString file = e->Attribute("file"); GMModelLoadSettings loadSettings( file, m_context ); GMSceneAsset asset; if (GMModelReader::load(loadSettings, asset)) { m_assets[id] = asset; } else { gm_warning(gm_dbg_wrap("Load asset failed: {0}"), loadSettings.filename); } } else if (name == L"buffer") { GMString file = e->Attribute("file"); GMBuffer buffer; package->readFile(GMPackageIndex::Root, file, &buffer); if (buffer.getSize() > 0) { m_buffers[id] = buffer; } else { gm_warning(gm_dbg_wrap("Cannot get file: {0}"), file); } } else if (name == L"audio") { GMString file = e->Attribute("file"); GMBuffer buffer; package->readFile(GMPackageIndex::Audio, file, &buffer); IAudioFile* f = nullptr; m_audioReader->load(buffer, &f); if (!f) { gm_warning(gm_dbg_wrap("Cannot read audio file {0}."), file); } else { m_audioFiles[id] = AutoReleasePtr<IAudioFile>(f); } } else if (name == L"particles") { parseParticlesAsset(e); } e = e->NextSiblingElement(); } } void Timeline::parseObjects(GMXMLElement* e) { while (e) { GMString id = e->Attribute("id"); if (id.isEmpty()) gm_warning(gm_dbg_wrap("Each object must have an ID")); GMString name = e->Name(); if (name == L"light") { GMString typeStr = e->Attribute("type"); GMLightType type = GMLightType::PointLight; if (typeStr == L"point") type = GMLightType::PointLight; else if (typeStr == L"directional") type = GMLightType::DirectionalLight; else if (typeStr == L"spotlight") type = GMLightType::Spotlight; else gm_warning(gm_dbg_wrap("Wrong light type: {0}"), typeStr); ILight* light = nullptr; GM.getFactory()->createLight(type, &light); GM_ASSERT(light); GMString posStr = e->Attribute("position"); if (!posStr.isEmpty()) { Scanner scanner(posStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); GMfloat value[] = { x, y, z }; light->setLightAttribute3(GMLight::Position, value); } GMString ambientStr = e->Attribute("ambient"); if (!ambientStr.isEmpty()) { Scanner scanner(ambientStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); GMfloat value[] = { x, y, z }; light->setLightAttribute3(GMLight::AmbientIntensity, value); } GMString diffuseStr = e->Attribute("diffuse"); if (!diffuseStr.isEmpty()) { Scanner scanner(diffuseStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); GMfloat value[] = { x, y, z }; light->setLightAttribute3(GMLight::DiffuseIntensity, value); } GMString specularStr = e->Attribute("specular"); if (!specularStr.isEmpty()) { GMfloat specular = 0; Scanner scanner(specularStr, *this); scanner.nextFloat(specular); bool bSuc = light->setLightAttribute(GMLight::SpecularIntensity, specular); GM_ASSERT(bSuc); } GMString cutOffStr = e->Attribute("cutoff"); if (!cutOffStr.isEmpty()) { GMfloat cutOff = 0; Scanner scanner(cutOffStr, *this); scanner.nextFloat(cutOff); bool bSuc = light->setLightAttribute(GMLight::CutOff, cutOff); GM_ASSERT(bSuc); } m_lights[id] = AutoReleasePtr<ILight>(light); } else if (name == L"cubemap") { GMGameObject* obj = nullptr; GMString assetName = e->Attribute("asset"); GMAsset asset = findAsset(assetName); if (!asset.isEmpty()) { obj = new GMCubeMapGameObject(asset); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); } else { gm_warning(gm_dbg_wrap("Cannot find asset: {0}"), assetName); } parseTransform(obj, e); } else if (name == L"object") { if (objectExists(id)) return; GMGameObject* obj = nullptr; GMString assetName = e->Attribute("asset"); GMAsset asset = findAsset(assetName); if (!asset.isEmpty()) { obj = new GMGameObject(asset); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); } else { gm_warning(gm_dbg_wrap("Cannot find asset: {0}"), assetName); } parseTextures(obj, e); parseMaterial(obj, e); parseTransform(obj, e); parseBlend(obj, e); parsePhysics(obj, e); } else if (name == L"bsp") { if (objectExists(id)) return; BSPGameObject* bsp = nullptr; GMString assetName = e->Attribute("asset"); GMBuffer asset = findBuffer(assetName); if (asset.getSize() > 0) { bsp = new BSPGameObject(m_context); bsp->load(asset); m_objects[id] = AutoReleasePtr<GMGameObject>(bsp); } else { gm_warning(gm_dbg_wrap("Invalid asset buffer: {0}"), assetName); } } else if (name == L"quad") { if (objectExists(id)) return; GMString lengthStr = e->Attribute("length"); GMString widthStr = e->Attribute("width"); GMfloat length = 0, width = 0; length = parseFloat(lengthStr); width = parseFloat(widthStr); GMString sliceStr = e->Attribute("slice"); GMint32 sliceX = 1, sliceY = 1; if (!sliceStr.isEmpty()) { Scanner scanner(sliceStr, *this); scanner.nextInt(sliceX); scanner.nextInt(sliceY); } GMSceneAsset scene; GMPrimitiveCreator::createQuadrangle(GMVec2(length / 2, width / 2), 0, scene, sliceX, sliceY); GMGameObject* obj = new GMGameObject(scene); GM_ASSERT(obj->getModel()); obj->getModel()->getShader().setCull(GMS_Cull::NoCull); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); GMString type = e->Attribute("type"); if (!type.isEmpty()) { if (type == "2d") obj->getModel()->setType(GMModelType::Model2D); else gm_warning(gm_dbg_wrap("Cannot recognize type '{0}' of object '{1}"), type, id); } parsePrimitiveAttributes(obj, e); parseTextures(obj, e); parseMaterial(obj, e); parseTransform(obj, e); parseBlend(obj, e); parsePhysics(obj, e); } else if (name == L"cube") { if (objectExists(id)) return; GMString sizeStr = e->Attribute("size"); Scanner scanner(sizeStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); GMString sliceStr = e->Attribute("slice"); GMint32 sliceX = 1, sliceY = 1; if (!sliceStr.isEmpty()) { Scanner scanner(sliceStr, *this); scanner.nextInt(sliceX); scanner.nextInt(sliceY); } GMSceneAsset scene; GMPrimitiveCreator::createCube(GMVec3(x * .5f, y * .5f, z * .5f), scene, sliceX, sliceY); GMGameObject* obj = new GMGameObject(scene); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); parsePrimitiveAttributes(obj, e); parseTextures(obj, e); parseMaterial(obj, e); parseTransform(obj, e); parseBlend(obj, e); parsePhysics(obj, e); } else if (name == L"wave") { if (objectExists(id)) return; GMWaveGameObjectDescription objDesc; parseWaveObjectAttributes(objDesc, e); Vector<GMWaveDescription> wds; GMXMLElement* waveDescriptionPtr = e->FirstChildElement("attribute"); while (waveDescriptionPtr) { GMWaveDescription desc; parseWaveAttributes(desc, waveDescriptionPtr); wds.push_back(std::move(desc)); waveDescriptionPtr = waveDescriptionPtr->NextSiblingElement("attribute"); } GMWaveGameObject* obj = GMWaveGameObject::create(objDesc); obj->setWaveDescriptions(std::move(wds)); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); parseTextures(obj, e); parseMaterial(obj, e); parseTransform(obj, e); parseBlend(obj, e); } else if (name == L"terrain") { if (objectExists(id)) return; GMfloat terrainX = 0, terrainZ = 0; GMfloat width = 1, height = 1, heightScaling = 10.f; GMint32 sliceX = 10, sliceY = 10; GMfloat texLen = 10, texHeight = 10; terrainX = parseFloat(e->Attribute("terrainX")); terrainZ = parseFloat(e->Attribute("terrainZ")); width = parseFloat(e->Attribute("width")); height = parseFloat(e->Attribute("height")); heightScaling = parseFloat(e->Attribute("heightScaling")); GMString sliceStr = e->Attribute("slice"); if (!sliceStr.isEmpty()) { Scanner scanner(sliceStr, *this); scanner.nextInt(sliceX); scanner.nextInt(sliceY); } GMString texSizeStr = e->Attribute("textureSize"); if (!texSizeStr.isEmpty()) { Scanner scanner(texSizeStr, *this); scanner.nextFloat(texLen); scanner.nextFloat(texHeight); } GMString terrainName = e->Attribute("terrain"); GMBuffer terrainBuffer = findBuffer(terrainName); GMImage* imgMap = nullptr; GMSceneAsset scene; if (GMImageReader::load(terrainBuffer.getData(), terrainBuffer.getSize(), &imgMap)) { GMTerrainDescription desc = { imgMap->getData().mip[0].data, imgMap->getData().channels, imgMap->getWidth(), imgMap->getHeight(), terrainX, terrainZ, width, height, heightScaling, (GMsize_t)sliceX, (GMsize_t)sliceY, texLen, texHeight, false }; GMPrimitiveCreator::createTerrain(desc, scene); imgMap->destroy(); } else { GMTerrainDescription desc = { nullptr, 0, 0, 0, terrainX, terrainZ, width, height, heightScaling, (GMsize_t)sliceX, (GMsize_t)sliceY, texLen, texHeight, false }; GMPrimitiveCreator::createTerrain(desc, scene); } GMGameObject* obj = new GMGameObject(scene); m_objects[id] = AutoReleasePtr<GMGameObject>(obj); parseTextures(obj, e); parseMaterial(obj, e); parseTransform(obj, e); parseBlend(obj, e); } else if (name == L"shadow") { GMRect rc = m_context->getWindow()->getRenderRect(); GMfloat width = rc.width, height = rc.height; { GMString str = e->Attribute("width"); if (!str.isEmpty()) width = parseFloat(str); } { GMString str = e->Attribute("height"); if (!str.isEmpty()) height = parseFloat(str); } GMfloat cascades = 1; { GMString str = e->Attribute("cascades"); if (!str.isEmpty()) cascades = parseFloat(str); } GMfloat bias = .005f; { GMString str = e->Attribute("bias"); if (!str.isEmpty()) bias = parseFloat(str); } Nullable<GMfloat> pcf; { GMString str = e->Attribute("pcf"); if (!str.isEmpty()) pcf = parseInt(str); } Vector<GMfloat> partitions; if (cascades > 1) { partitions.resize(cascades); GMString str = e->Attribute("partitions"); if (!str.isEmpty()) { Scanner scanner(str, *this); for (GMint32 i = 0; i < cascades; ++i) { GMfloat p = 0; scanner.nextFloat(p); partitions[i] = p; } } else { GMfloat p = 1.f / cascades; for (GMint32 i = 0; i < cascades - 1; ++i) { partitions[i] = (i + 1) * p; } partitions[cascades - 1] = 1.f; } } CameraParams cp; GMCameraLookAt lookAt; GMint32 component = parseCameraAction(e, cp, lookAt); GMShadowSourceDesc desc; desc.type = GMShadowSourceDesc::CSMShadow; GMCamera camera; if (component & PerspectiveComponent) camera.setPerspective(cp.fovy, cp.aspect, cp.n, cp.f); else if (component & OrthoComponent) camera.setOrtho(cp.left, cp.right, cp.bottom, cp.top, cp.n, cp.f); if (component & CameraLookAtComponent) camera.lookAt(lookAt); desc.position = GMVec4(lookAt.position, 1); desc.camera = camera; if (cascades > 1) { for (GMint32 i = 0; i < cascades; ++i) { desc.cascadePartitions[i] = partitions[i]; } } desc.width = width; desc.height = height; desc.cascades = cascades; desc.biasMax = desc.biasMin = bias; if (!pcf.isNull) desc.pcfRowCount = pcf; m_shadows[id] = desc; } else if (name == L"source") { GMString assetName = e->Attribute("asset"); auto asset = m_audioFiles[assetName].get(); if (asset) { auto exists = m_audioSources.find(id); if (exists == m_audioSources.end()) { IAudioSource* s = nullptr; m_audioPlayer->createPlayerSource(asset, &s); if (s) m_audioSources[id] = AutoReleasePtr<IAudioSource>(s); else gm_warning(gm_dbg_wrap("Create source failed: {0}"), id); } else { gm_warning(gm_dbg_wrap("Source id {0} is already existed."), id); } } else { gm_warning(gm_dbg_wrap("Cannot find asset for source: {0}"), assetName); } } else if (name == L"particles") { parseParticlesObject(e); } else if (name == L"physics") { GMDiscreteDynamicsWorld* ddw = new GMDiscreteDynamicsWorld(nullptr); m_physicsWorld[id] = AutoReleasePtr<GMPhysicsWorld>(ddw); parsePhysics(ddw, e); } else if (name == L"screen") { // 类似于电影尾声那样的滚屏 parseScreen(e); } e = e->NextSiblingElement(); } } void Timeline::interpolateCamera(GMXMLElement* e, GMfloat timePoint) { GMint32 component = NoCameraComponent; GMVec3 pos, dir, focus; GMString str = e->Attribute("position"); if (!str.isEmpty()) { Scanner scanner(str, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); pos = GMVec3(x, y, z); component |= PositionComponent; } str = e->Attribute("direction"); if (!str.isEmpty()) { Scanner scanner(str, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); dir = Normalize(GMVec3(x, y, z)); component |= DirectionComponent; } str = e->Attribute("focus"); if (!str.isEmpty()) { Scanner scanner(str, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); focus = GMVec3(x, y, z); component |= FocusAtComponent; } if ((component & DirectionComponent) && (component & FocusAtComponent)) { gm_warning(gm_dbg_wrap("You cannot specify both 'direction' and 'focus'. In this camera action, 'direction' won't work.")); } if (!(component & DirectionComponent) && !(component & FocusAtComponent)) { gm_warning(gm_dbg_wrap("You must specify at least 'direction' or 'focus'. In this camera action, 'direction' won't work.")); } if (component != NoCameraComponent) { GMInterpolationFunctors f; CurveType curve = parseCurve(e, f); GMCamera& camera = m_context->getEngine()->getCamera(); AnimationContainer& animationContainer = m_animations[Camera][&camera]; GMAnimation& animation = animationContainer.currentEditingAnimation(); const GMCameraLookAt& lookAt = camera.getLookAt(); animation.setTargetObjects(&camera); GMVec3 posCandidate = (component & PositionComponent) ? pos : lookAt.position; GMVec3 dirCandidate = (component & DirectionComponent) ? dir : lookAt.lookDirection; GMVec3 focusCandidate = (component & FocusAtComponent) ? focus : lookAt.position + lookAt.lookDirection; GMCameraKeyframe* keyframe = nullptr; if (component & DirectionComponent) keyframe = new GMCameraKeyframe(GMCameraKeyframeComponent::LookAtDirection, posCandidate, dirCandidate, timePoint); else // 默认是按照focusAt调整视觉 keyframe = new GMCameraKeyframe(GMCameraKeyframeComponent::FocusAt, posCandidate, focusCandidate, timePoint); if (curve != CurveType::NoCurve) keyframe->setFunctors(f); animation.addKeyFrame(keyframe); } } void Timeline::interpolateLight(GMXMLElement* e, ILight* light, GMfloat timePoint) { GMint32 component = GMLightKeyframeComponent::NoComponent; GMVec3 position, ambient, diffuse; GMfloat specular = 0, cutOff = 10.f; GMString ambientStr = e->Attribute("ambient"); if (!ambientStr.isEmpty()) { Scanner scanner(ambientStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); ambient = GMVec3(x, y, z); component |= GMLightKeyframeComponent::Ambient; } GMString diffuseStr = e->Attribute("diffuse"); if (!diffuseStr.isEmpty()) { Scanner scanner(diffuseStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); diffuse = GMVec3(x, y, z); component |= GMLightKeyframeComponent::Diffuse; } GMString specularStr = e->Attribute("specular"); if (!specularStr.isEmpty()) { Scanner scanner(specularStr, *this); scanner.nextFloat(specular); component |= GMLightKeyframeComponent::Specular; } GMString cutOffStr = e->Attribute("cutoff"); if (!cutOffStr.isEmpty()) { Scanner scanner(specularStr, *this); scanner.nextFloat(cutOff); component |= GMLightKeyframeComponent::CutOff; } GMString posStr = e->Attribute("position"); if (!posStr.isEmpty()) { Scanner scanner(posStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); position = GMVec3(x, y, z); component |= GMLightKeyframeComponent::Position; } if (component != GMLightKeyframeComponent::NoComponent) { GMInterpolationFunctors f; CurveType curve = parseCurve(e, f); AnimationContainer& animationContainer = m_animations[Light][light]; GMAnimation& animation = animationContainer.currentEditingAnimation(); animation.setTargetObjects(light); GMAnimationKeyframe* keyframe = new GMLightKeyframe(m_context, component, ambient, diffuse, specular, position, cutOff, timePoint); if (curve != CurveType::NoCurve) keyframe->setFunctors(f); animation.addKeyFrame(keyframe); } } void Timeline::interpolateObject(GMXMLElement* e, GMGameObject* obj, GMfloat timePoint) { GMint32 component = GMGameObjectKeyframeComponent::NoComponent; GMVec4 translation, scaling; GMQuat rotation; GMString str = e->Attribute("translate"); if (!str.isEmpty()) { Scanner scanner(str, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); component |= GMGameObjectKeyframeComponent::Translate; translation = GMVec4(x, y, z, 1); } str = e->Attribute("scale"); if (!str.isEmpty()) { Scanner scanner(str, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); component |= GMGameObjectKeyframeComponent::Scale; scaling = GMVec4(x, y, z, 1); } str = e->Attribute("rotate"); if (!str.isEmpty()) { GMfloat x, y, z, degree; Scanner scanner(str, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); scanner.nextFloat(degree); component |= GMGameObjectKeyframeComponent::Rotate; GMVec3 axis(x, y, z); if (!FuzzyCompare(Length(axis), 0.f)) rotation = Rotate(Radians(degree), axis); else gm_warning(gm_dbg_wrap("Wrong rotation axis")); } if (component != GMGameObjectKeyframeComponent::NoComponent) { GMInterpolationFunctors f; CurveType curve = parseCurve(e, f); AnimationContainer& animationContainer = m_animations[GameObject][obj]; GMAnimation& animation = animationContainer.currentEditingAnimation(); animation.setTargetObjects(obj); GMAnimationKeyframe* keyframe = new GMGameObjectKeyframe(component, translation, scaling, rotation, timePoint); if (curve != CurveType::NoCurve) keyframe->setFunctors(f); animation.addKeyFrame(keyframe); } str = e->Attribute("color"); if (!str.isEmpty()) { GMInterpolationFunctors f; CurveType curve = parseCurve(e, f); AnimationContainer& animationContainer = m_animations[GameObject][obj]; GMAnimation& animation = animationContainer.currentEditingAnimation(); animation.setTargetObjects(obj); Scanner scanner(str, *this); Array<float, 4> color; scanner.nextFloat(color[0]); scanner.nextFloat(color[1]); scanner.nextFloat(color[2]); scanner.nextFloat(color[3]); GMAnimationKeyframe* keyframe = new GameObjectColorKeyframe(m_verticesCache, color, timePoint); if (curve != CurveType::NoCurve) keyframe->setFunctors(f); animation.addKeyFrame(keyframe); } } AnimationContainer& Timeline::getAnimationFromObject(AssetType at, void* o) { if (at == AssetType::NotFound) throw std::logic_error("Asset not found"); if (at == AssetType::Light) return m_animations[Light][asset_cast<ILight>(o)->get()]; if (at == AssetType::GameObject) return m_animations[GameObject][asset_cast<GMGameObject>(o)->get()]; if (at == AssetType::Camera) return m_animations[Camera][asset_cast<GMCamera>(o)]; throw std::logic_error("Asset wrong type."); } void Timeline::parseActions(GMXMLElement* e) { GM_ASSERT(m_world); while (e) { GMString name = e->Name(); if (name == L"include") { parseInclude(e); } else if (name == L"component") { parseComponent(e); } else if (name == L"action") { Action action = { Action::Immediate }; GMString time = e->Attribute("time"); if (!time.isEmpty()) { action.runType = Action::Deferred; if (time[0] == '+' || time[0] == '-') { // 相对时间 if (!time.isEmpty()) { action.timePoint = m_lastTime + parseFloat(time); if (action.timePoint > m_lastTime) m_lastTime = action.timePoint; } else { action.runType = Action::Immediate; gm_warning(gm_dbg_wrap("Wrong action time: {0}"), time); } } else { action.timePoint = parseFloat(time); if (action.timePoint > m_lastTime) m_lastTime = action.timePoint; } } if (action.timePoint == 0) action.runType = Action::Immediate; GMString type = e->Attribute("type"); if (type == L"camera") { CameraParams p; GMCameraLookAt lookAt; GMint32 component = parseCameraAction(e, p, lookAt); GMsize_t lookAtIndex = m_cameraLookAtCache.put(lookAt); if (component & PerspectiveComponent) { action.action = [p, this]() { auto& camera = m_context->getEngine()->getCamera(); camera.setPerspective(p.fovy, p.aspect, p.n, p.f); }; } else if (component & OrthoComponent) { action.action = [p, this]() { auto& camera = m_context->getEngine()->getCamera(); camera.setOrtho(p.left, p.right, p.bottom, p.top, p.n, p.f); }; } if (component & CameraLookAtComponent) { action.action = [p, action, lookAtIndex, this]() { if (action.action) action.action(); auto& camera = m_context->getEngine()->getCamera(); camera.lookAt(m_cameraLookAtCache[lookAtIndex]); }; } bindAction(action); } else if (type == L"addObject") { GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); if (assetType == AssetType::GameObject) addObject(asset_cast<GMGameObject>(targetObject), e, action); else if (assetType == AssetType::Light) addObject(asset_cast<ILight>(targetObject), e, action); else if (assetType == AssetType::Particles) addObject(asset_cast<IParticleSystem>(targetObject), e, action); else if (assetType == AssetType::Shadow) addObject(asset_cast<GMShadowSourceDesc>(targetObject), e, action); else if (assetType == AssetType::PhysicsWorld) addObject(asset_cast<GMPhysicsWorld>(targetObject), e, action); else gm_warning(gm_dbg_wrap("Cannot find object: {0}"), object); bindAction(action); } else if (type == L"animate") // 或者是其它插值变换 { GMString actionStr = e->Attribute("action"); GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); if (assetType == AssetType::NotFound) gm_warning(gm_dbg_wrap("Cannot find object: {0}"), object); if (actionStr == L"play") { if (targetObject) { AnimationContainer& animationContainer = getAnimationFromObject(assetType, targetObject); animationContainer.nextEditAnimation(); GMfloat timePoint = action.timePoint; action.action = [&animationContainer, timePoint]() { animationContainer.playAnimation(); }; bindAction(action); } } else if (actionStr == L"stop") { if (targetObject) { AnimationContainer& animationContainer = getAnimationFromObject(assetType, targetObject); action.action = [&animationContainer]() { animationContainer.pauseAnimation(); animationContainer.nextPlayingAnimation(); }; bindAction(action); } } else { GMString endTimeStr = e->Attribute("endtime"); GMfloat endTime = 0; bool ok = false; endTime = parseFloat(endTimeStr, &ok); if (ok) { action.timePoint = 0; action.runType = Action::Immediate; // 插值动作的添加是立即的 if (assetType == AssetType::Camera) interpolateCamera(e, endTime); else if (assetType == AssetType::Light) interpolateLight(e, asset_cast<ILight>(targetObject)->get(), endTime); else if (assetType == AssetType::GameObject) interpolateObject(e, asset_cast<GMGameObject>(targetObject)->get(), endTime); } else { gm_warning(gm_dbg_wrap("Attribute 'endtime' must be specified in animation interpolation. Object: '{0}'"), object); } } } else if (type == L"attribute") { GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); if (assetType == AssetType::GameObject) parseAttributes(asset_cast<GMGameObject>(targetObject)->get(), e, action); else if (assetType == AssetType::NotFound) gm_warning(gm_dbg_wrap("Object '{0}' not found."), object); else gm_warning(gm_dbg_wrap("Object '{0}' doesn't support 'attribute' type."), object); bindAction(action); } else if (type == L"removeObject") { GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); GMString deleteFromMemoryStr = e->Attribute("delete"); bool deleteFromMemory = deleteFromMemoryStr.isEmpty() ? false : toBool(deleteFromMemoryStr); if (assetType == AssetType::Light) removeObject(asset_cast<ILight>(targetObject)->get(), e, action); else if (assetType == AssetType::GameObject) removeObject(asset_cast<GMGameObject>(targetObject)->get(), e, action, deleteFromMemory); else if (assetType == AssetType::NotFound) gm_warning(gm_dbg_wrap("Object '{0}' not found."), object); else gm_warning(gm_dbg_wrap("Object '{0}' doesn't support 'removeObject' type."), object); bindAction(action); } else if (type == L"removeShadow") { action.action = [this]() { GMShadowSourceDesc desc; desc.type = GMShadowSourceDesc::NoShadow; m_context->getEngine()->setShadowSource(desc); }; bindAction(action); } else if (type == L"removePhysics") { action.action = [this]() { m_world->setPhysicsWorld(nullptr); }; bindAction(action); } else if (type == L"play") { GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); if (assetType == AssetType::AudioSource) { action.action = [this, targetObject]() { playAudio(asset_cast<IAudioSource>(targetObject)->get()); }; bindAction(action); } else if (assetType == AssetType::GameObject) { GMString n = e->Attribute("name"); action.action = [this, targetObject, n](){ play(asset_cast<GMGameObject>(targetObject)->get(), n); }; bindAction(action); } else { gm_warning(gm_dbg_wrap("Cannot find source: {0}"), object); } } else if (type == L"emit") { GMString object = e->Attribute("object"); void* targetObject = nullptr; AssetType assetType = getAssetType(object, &targetObject); if (assetType == AssetType::Particles) { auto particleSystemPtr = asset_cast<IParticleSystem>(targetObject); GM_ASSERT(particleSystemPtr); IParticleSystem* particleSystem = particleSystemPtr->get(); action.action = [particleSystem](){ particleSystem->getEmitter()->emitOnce(); particleSystem->getEmitter()->startEmit(); }; bindAction(action); } else { gm_warning(gm_dbg_wrap("object '{0}' is not a particle system object."), object); } } else if (type == L"filter") { GMString name = e->Attribute("name"); if (name == L"blend") { GMString valueStr = e->Attribute("value"); GMfloat r = 1, g = 1, b = 1; Scanner scanner(valueStr, *this); scanner.nextFloat(r); scanner.nextFloat(g); scanner.nextFloat(b); action.action = [this, r, g, b]() { auto renderContext = m_context->getEngine()->getConfigs().getConfig(GMConfigs::Render).asRenderConfig(); renderContext.set(GMRenderConfigs::FilterMode, GMFilterMode::Blend); renderContext.set(GMRenderConfigs::BlendFactor_Vec3, GMVec3(r, g, b)); }; } bindAction(action); } else if (type == L"removeFilter") { action.action = [this]() { auto renderContext = m_context->getEngine()->getConfigs().getConfig(GMConfigs::Render).asRenderConfig(); renderContext.set(GMRenderConfigs::FilterMode, GMFilterMode::None); }; bindAction(action); } else { gm_warning(gm_dbg_wrap("action type cannot be recognized: {0}"), type); } } else if (name == L"checkpoint") { GMString type = e->Attribute("type"); if (type == L"save") { m_checkpointTime = m_lastTime; } else if (type == L"load") { m_lastTime = m_checkpointTime; } else if (type == L"time") { GMString timeStr = e->Attribute("time"); if (!timeStr.isEmpty()) { GMfloat time = 0; bool ok = false; time = parseFloat(timeStr, &ok); if (ok) { m_lastTime += time; m_checkpointTime = m_lastTime; } else { gm_warning(gm_dbg_wrap("'time' is not a number: {0}"), timeStr); } } else { gm_warning(gm_dbg_wrap("checkpoint 'time' type missing 'time' attribute.")); } } else { gm_warning(gm_dbg_wrap("checkpoint type cannot be recognized: {0}"), type); } } else { gm_warning(gm_dbg_wrap("tag name cannot be recognized: {0}"), e->Name()); } e = e->NextSiblingElement(); } } void Timeline::parseInclude(GMXMLElement* e) { GMString filename = e->Attribute("file"); if (filename.isEmpty()) { gm_warning(gm_dbg_wrap("Include file name cannot be empty.")); } else { GMBuffer buffer; GM.getGamePackageManager()->readFile(GMPackageIndex::Scripts, filename, &buffer); if (buffer.getSize() > 0) { buffer.convertToStringBuffer(); GMString content((const char*)buffer.getData()); parse(content); } else { gm_warning(gm_dbg_wrap("File is empty with filename: {0}"), filename); } } } void Timeline::parseComponent(GMXMLElement* e) { // component和include大体一致。只不过component的对象只会添加一次,并且可以接受槽作为参数。 GMString filename = e->Attribute("file"); if (filename.isEmpty()) { gm_warning(gm_dbg_wrap("Component file name cannot be empty.")); } else { // 解析Component下所有槽,再解析内容 m_supressedWarnings.set(Warning_ObjectExistsWarning); m_slots.pushSlots(); { GMXMLElement* el = e->FirstChildElement(); while (el) { if (GMString::stringEquals(el->Name(), "slot")) m_slots.addSlot(el->Attribute("name"), getValueFromDefines(el->GetText())); el = el->NextSiblingElement(); } } GMBuffer buffer; GM.getGamePackageManager()->readFile(GMPackageIndex::Scripts, filename, &buffer); if (buffer.getSize() > 0) { buffer.convertToStringBuffer(); GMString content((const char*)buffer.getData()); parseComponent(content); } else { gm_warning(gm_dbg_wrap("File is empty with filename: {0}"), filename); } m_slots.popSlots(); m_supressedWarnings.clear(Warning_ObjectExistsWarning); } } GMint32 Timeline::parseCameraAction(GMXMLElement* e, CameraParams& cp, GMCameraLookAt& lookAt) { GMint32 component = NoCameraComponent; GMString view = e->Attribute("view"); if (view == L"perspective") { GMString fovyStr, aspectStr, nStr, fStr; GMfloat fovy, aspect, n, f; fovyStr = e->Attribute("fovy"); if (fovyStr.isEmpty()) fovy = Radians(75.f); else fovy = Radians(parseFloat(fovyStr)); aspectStr = e->Attribute("aspect"); if (aspectStr.isEmpty()) { GMRect rc = m_context->getWindow()->getRenderRect(); aspect = static_cast<GMfloat>(rc.width) / rc.height; } else { aspect = 1.33f; } nStr = e->Attribute("near"); if (nStr.isEmpty()) n = .1f; else n = parseFloat(nStr); fStr = e->Attribute("far"); if (fStr.isEmpty()) f = 3200; else f = parseFloat(fStr); cp.fovy = fovy; cp.aspect = aspect; cp.n = n; cp.f = f; component |= PerspectiveComponent; } else if (view == L"ortho") { GMfloat left = 0, right = 0, top = 0, bottom = 0; GMfloat n = 0, f = 0; left = parseInt(e->Attribute("left")); right = parseInt(e->Attribute("right")); top = parseInt(e->Attribute("top")); bottom = parseInt(e->Attribute("bottom")); n = parseInt(e->Attribute("near")); f = parseInt(e->Attribute("far")); cp.left = left; cp.right = right; cp.top = top; cp.bottom = bottom; cp.n = n; cp.f = f; component |= OrthoComponent; } else if (!view.isEmpty()) { gm_warning(gm_dbg_wrap("Camera view only supports 'perspective' and 'ortho'")); } // 设置位置 GMString dirStr, posStr, focusStr; GMVec3 direction = Zero<GMVec3>(), position = Zero<GMVec3>(), focus = Zero<GMVec3>(); dirStr = e->Attribute("direction"); posStr = e->Attribute("position"); focusStr = e->Attribute("focus"); if (!posStr.isEmpty()) { GMfloat x = 0, y = 0, z = 0; Scanner scanner(posStr, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); position = GMVec3(x, y, z); } if (!dirStr.isEmpty()) { GMfloat x = 0, y = 0, z = 0; Scanner scanner(dirStr, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); direction = GMVec3(x, y, z); } if (!focusStr.isEmpty()) { GMfloat x = 0, y = 0, z = 0; Scanner scanner(focusStr, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); focus = GMVec3(x, y, z); } if (!dirStr.isEmpty() && !focusStr.isEmpty()) { gm_warning(gm_dbg_wrap("You cannot specify both 'direction' and 'focus'. 'direction' won't work.")); } if (!focusStr.isEmpty()) { // focus lookAt = GMCameraLookAt::makeLookAt(position, focus); component |= CameraLookAtComponent; } else if (!dirStr.isEmpty()) { // direction lookAt = GMCameraLookAt(direction, position); component |= CameraLookAtComponent; } return component; } void Timeline::parseParticlesAsset(GMXMLElement* e) { GMString id = e->Attribute("id"); GMString filename = e->Attribute("file"); if (!id.isEmpty()) { GMBuffer& buf = m_buffers[id]; GM.getGamePackageManager()->readFile(GMPackageIndex::Particle, filename, &buf); buf.convertToStringBuffer(); } else { gm_warning(gm_dbg_wrap("ID is empty while parsing particles asset.")); } } void Timeline::parseParticlesObject(GMXMLElement* e) { GMString id = e->Attribute("id"); GMString assetName = e->Attribute("asset"); const auto& buf = m_buffers[assetName]; if (buf.getSize() > 0) { GMString type = e->Attribute("type"); if (type == L"cocos2d") { IParticleSystem* ps = nullptr; GMParticleSystem_Cocos2D* cocos2DPs = nullptr; GMParticleSystem_Cocos2D::createCocos2DParticleSystem(m_context, buf, GMParticleModelType::Particle3D, &cocos2DPs); ps = cocos2DPs; if (ps) { ps->getEmitter()->stopEmit(); m_particleSystems[id] = AutoReleasePtr<IParticleSystem>(ps); } else { gm_warning(gm_dbg_wrap("Create particle system failed for id '{1}'."), id); } parseCocos2DParticleAttributes(ps, e); } else { gm_warning(gm_dbg_wrap("Unrecognized type {0} for id '{1}'."), type, id); } } else { gm_warning(gm_dbg_wrap("Cannot find particles for source: {0}"), assetName); } } void Timeline::parseCocos2DParticleAttributes(IParticleSystem* ps, GMXMLElement* e) { GMParticleEmitter_Cocos2D* emitter = gm_cast<GMParticleEmitter_Cocos2D*>(ps->getEmitter()); GMString translateStr = e->Attribute("translate"); if (!translateStr.isEmpty()) { GMfloat x = 0, y = 0, z = 0; Scanner scanner(translateStr, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); emitter->setEmitPosition(GMVec3(x, y, z)); } } void Timeline::parseScreen(GMXMLElement* e) { GMString id = e->Attribute("id"); bool hasChild = false; ScreenObject* obj = new ScreenObject(m_context); GMString spacingStr = e->Attribute("spacing"); if (!spacingStr.isEmpty()) { obj->setSpacing(parseFloat(spacingStr)); } GMString speedStr = e->Attribute("speed"); if (!speedStr.isEmpty()) { obj->setSpeed(parseFloat(speedStr)); } GMFontHandle font = m_context->getEngine()->getGlyphManager()->getDefaultFontEN(); GMFontSizePt fontSize = 32; // 一共有两种类型的元素,text和image,它们居中对齐,且有一个包围盒来计算几何大小。 e = e->FirstChildElement(); while (e) { GMString tag = e->Name(); if (tag == L"text") { hasChild = true; ScreenObject::TextOptions options = { font, fontSize, GMFloat4(1, 1, 1, 1) }; // size GMString sizeStr = e->Attribute("size"); if (!sizeStr.isEmpty()) { options.fontSize = parseFloat(sizeStr); } obj->addText(e->GetText(), options); } else if (tag == L"image") { hasChild = true; GMString assetName = e->Attribute("buffer"); GMBuffer buffer = findBuffer(assetName); // addImage if (buffer.getSize() > 0) obj->addImage(buffer); else gm_warning(gm_dbg_wrap("Cannot find buffer asset '{0}'"), assetName); } else if (tag == L"space") { GMString spacingStr = e->Attribute("value"); if (!spacingStr.isEmpty()) obj->addSpacing(parseFloat(spacingStr)); else gm_warning(gm_dbg_wrap("Invalid spacing value.")); } else if (tag == L"font") { GMString fontName = e->Attribute("value"); if (!fontName.isEmpty()) { GMFontHandle fontCandidate = HandlerInstance->getFontHandleByName(fontName); if (fontCandidate) font = fontCandidate; else gm_warning(gm_dbg_wrap("Cannot find font '{0}'."), fontName); } } else if (tag == L"fontSize") { GMString fontSizeStr = e->Attribute("value"); if (!fontSizeStr.isEmpty()) { fontSize = parseFloat(fontSizeStr); } } else if (tag == L"setspacing") { GMString setSpacingValueStr = e->Attribute("value"); if (!setSpacingValueStr.isEmpty()) { obj->setSpacing(parseInt(setSpacingValueStr)); } } e = e->NextSiblingElement(); } if (hasChild) { m_objects[id] = AutoReleasePtr<GMGameObject>(obj); } else { obj->destroy(); } } GMAsset Timeline::findAsset(const GMString& assetName) { auto assetIter = m_assets.find(assetName); if (assetIter != m_assets.end()) return assetIter->second; return GMAsset::invalidAsset(); } const PBR* Timeline::findPBR(const GMString& assetName) { auto pbrIter = m_pbrs.find(assetName); if (pbrIter != m_pbrs.end()) return &pbrIter->second; return nullptr; } GMBuffer Timeline::findBuffer(const GMString& bufferName) { auto bufferIter = m_buffers.find(bufferName); if (bufferIter != m_buffers.end()) return bufferIter->second; static GMBuffer s_empty; return s_empty; } void Timeline::parseTransform(GMGameObject* o, GMXMLElement* e) { if (!o) return; GMString str = e->Attribute("scale"); if (!str.isEmpty()) { GMfloat x, y, z; Scanner scanner(str, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); o->setScaling(Scale(GMVec3(x, y, z))); } str = e->Attribute("translate"); if (!str.isEmpty()) { GMfloat x, y, z; Scanner scanner(str, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); o->setTranslation(Translate(GMVec3(x, y, z))); } str = e->Attribute("rotate"); if (!str.isEmpty()) { GMfloat x, y, z, degree; Scanner scanner(str, *this); scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); scanner.nextFloat(degree); GMVec3 axis(x, y, z); if (!FuzzyCompare(Length(axis), 0.f)) o->setRotation(Rotate(Radians(degree), axis)); else gm_warning(gm_dbg_wrap("Wrong rotation axis")); } } void Timeline::parseTextures(GMGameObject* o, GMXMLElement* e) { if (!o) return; ShaderCallback cbAmbient = parseTexture(e, "ambient", GMTextureType::Ambient); ShaderCallback cbDiffuse = parseTexture(e, "diffuse", GMTextureType::Diffuse); ShaderCallback cbNormal = parseTexture(e, "normal", GMTextureType::NormalMap); ShaderCallback cbSpecular = parseTexture(e, "specular", GMTextureType::Specular); ShaderCallback cbAmbientSpeed = parseTextureTransform(e, "ambientTranslateSpeed", GMTextureType::Ambient, GMS_TextureTransformType::Scroll); ShaderCallback cbDiffuseSpeed = parseTextureTransform(e, "diffuseTranslateSpeed", GMTextureType::Diffuse, GMS_TextureTransformType::Scroll); ShaderCallback cbNormalSpeed = parseTextureTransform(e, "normalTranslateSpeed", GMTextureType::NormalMap, GMS_TextureTransformType::Scroll); ShaderCallback cbSpecularSpeed = parseTextureTransform(e, "specularTranslateSpeed", GMTextureType::Specular, GMS_TextureTransformType::Scroll); ShaderCallback cbPbr = parseTexturePBR(e); GMString id = e->Attribute("id"); if (isAny(cbAmbient, cbDiffuse, cbNormal, cbSpecular, cbAmbientSpeed, cbDiffuseSpeed, cbNormalSpeed, cbSpecularSpeed, cbPbr)) { o->foreachModel([this, e, cbAmbient, cbDiffuse, cbNormal, cbSpecular, cbAmbientSpeed, cbDiffuseSpeed, cbNormalSpeed, cbSpecularSpeed, cbPbr](GMModel* model) { if (!model) return; GMShader& shader = model->getShader(); callEvery_1(shader, cbAmbient, cbDiffuse, cbNormal, cbSpecular); callEvery_1(shader, cbAmbientSpeed, cbDiffuseSpeed, cbNormalSpeed, cbSpecularSpeed); callEvery_1(shader, cbPbr); }); } } void Timeline::parseMaterial(GMGameObject* o, GMXMLElement* e) { if (!o) return; ShaderCallback cbMaterial = parseMaterial(e); o->foreachModel([this, e, cbMaterial](GMModel* model) { GMShader& shader = model->getShader(); callEvery_1(shader, cbMaterial); }); } Timeline::ShaderCallback Timeline::parseMaterial(GMXMLElement* e) { GMString kaStr = e->Attribute("ka"); GMString kdStr = e->Attribute("kd"); GMString ksStr = e->Attribute("ks"); GMString shininessStr = e->Attribute("shininess"); struct XYZ { GMfloat x, y, z; }; Nullable<XYZ> ka, ks, kd; Nullable<GMfloat> shininess; if (!kaStr.isEmpty()) { XYZ xyz; Scanner scanner(kaStr, *this); scanner.nextFloat(xyz.x); scanner.nextFloat(xyz.y); scanner.nextFloat(xyz.z); ka = xyz; } if (!kdStr.isEmpty()) { XYZ xyz; Scanner scanner(kdStr, *this); scanner.nextFloat(xyz.x); scanner.nextFloat(xyz.y); scanner.nextFloat(xyz.z); kd = xyz; } if (!ksStr.isEmpty()) { XYZ xyz; Scanner scanner(ksStr, *this); scanner.nextFloat(xyz.x); scanner.nextFloat(xyz.y); scanner.nextFloat(xyz.z); ks = xyz; } if (!shininessStr.isEmpty()) shininess = parseFloat(shininessStr); if (isAny(!ka.isNull, !kd.isNull, !ks.isNull, !shininess.isNull)) { ShaderCallback cb = [this, e, ka, kd, ks, shininess](GMShader& shader) { if (!ka.isNull) shader.getMaterial().setAmbient(GMVec3(ka.value.x, ka.value.y, ka.value.z)); if (!kd.isNull) shader.getMaterial().setDiffuse(GMVec3(kd.value.x, kd.value.y, kd.value.z)); if (!ks.isNull) shader.getMaterial().setSpecular(GMVec3(ks.value.x, ks.value.y, ks.value.z)); if (!shininess.isNull) shader.getMaterial().setShininess(shininess.value); }; return cb; } return ShaderCallback(); } void Timeline::parseBlend(GMGameObject* o, GMXMLElement* e) { if (!o) return; GMString blendStr = e->Attribute("blend"); Nullable<bool> blend; if (!blendStr.isEmpty()) blend = toBool(blendStr); Nullable<GMS_BlendFunc> source, dest; GMString blendSrcStr = e->Attribute("source"); GMString blendDestStr = e->Attribute("dest"); if (!blendSrcStr.isEmpty()) source = toBlendFunc(blendSrcStr); if (!blendDestStr.isEmpty()) dest = toBlendFunc(blendDestStr); GMString id = e->Attribute("id"); if (!blend.isNull || !source.isNull || !dest.isNull) { o->foreachModel([=](GMModel* model) { GMShader& shader = model->getShader(); if (!blend.isNull) shader.setBlend(blend); if (!source.isNull) shader.setBlendFactorSource(source); if (!dest.isNull) shader.setBlendFactorDest(dest); }); } } void Timeline::parsePrimitiveAttributes(GMGameObject* obj, GMXMLElement* e) { GMString colorStr = e->Attribute("color"); if (!colorStr.isEmpty()) { Scanner scanner(colorStr, *this); Array<GMfloat, 4> color; scanner.nextFloat(color[0]); scanner.nextFloat(color[1]); scanner.nextFloat(color[2]); scanner.nextFloat(color[3]); obj->foreachModel([this, color](GMModel* model) { model->setUsageHint(GMUsageHint::DynamicDraw); // 保存副本 GMVertices vertices; vertices.reserve(model->getVerticesCount()); for (auto& part : model->getParts()) { for (auto& vertex : part->vertices()) { vertices.push_back(vertex); } } m_verticesCache[model] = std::move(vertices); setColorForModel(model, &color[0]); }); } GMString colorOpStr = e->Attribute("colorOp"); GMS_VertexColorOp op = GMS_VertexColorOp::DoNotUseVertexColor; if (colorOpStr == "replace") op = GMS_VertexColorOp::Replace; else if (colorOpStr == "add") op = GMS_VertexColorOp::Add; else if (colorOpStr == "multiply") op = GMS_VertexColorOp::Multiply; if (op != GMS_VertexColorOp::DoNotUseVertexColor) { obj->foreachModel([op](GMModel* model) { model->getShader().setVertexColorOp(op); }); } } void Timeline::parsePhysics(GMGameObject* obj, GMXMLElement* e) { if (obj) { GMString isPhysicsStr = e->Attribute("physics"); if (!isPhysicsStr.isEmpty()) { bool isPhysics = toBool(isPhysicsStr); GMSceneAsset scene = obj->getAsset(); if (isPhysics) { GMRigidPhysicsObject* pobj = new GMRigidPhysicsObject(); GMPhysicsShapeAsset phyAsset; GMPhysicsShapeHelper::createConvexShapeFromTriangleModel(scene, phyAsset, false); parsePhysicsAttributes(pobj, e); obj->setPhysicsObject(pobj); pobj->setShape(phyAsset); } } } } void Timeline::parsePhysics(GMDiscreteDynamicsWorld* ddw, GMXMLElement* e) { GMString gravityStr = e->Attribute("gravity"); if (!gravityStr.isEmpty()) { Scanner scanner(gravityStr, *this); GMfloat x, y, z; scanner.nextFloat(x); scanner.nextFloat(y); scanner.nextFloat(z); GMVec3 gravity = GMVec3(x, y, z); ddw->setGravity(gravity); } } void Timeline::parsePhysicsAttributes(GMRigidPhysicsObject* pobj, GMXMLElement* e) { { GMString massStr = e->Attribute("mass"); if (!massStr.isEmpty()) pobj->setMass(parseFloat(massStr)); } } Timeline::ShaderCallback Timeline::parseTexture(GMXMLElement* e, const char* type, GMTextureType textureType) { GMString tex = e->Attribute(type); if (!tex.isEmpty()) { return [this, tex, textureType](GMShader& shader) { GMAsset asset = findAsset(tex); if (!asset.isEmpty() && asset.isTexture()) { GMToolUtil::addTextureToShader(shader, asset, textureType); } else { gm_warning(gm_dbg_wrap("Cannot find texture asset: {0}"), tex); } }; } return ShaderCallback(); } Timeline::ShaderCallback Timeline::parseTextureTransform(GMXMLElement* e, const char* type, GMTextureType textureType, GMS_TextureTransformType transformType) { GMString val = e->Attribute(type); if (!val.isEmpty()) { return [this, val, textureType, transformType](GMShader& shader) { Scanner scanner(val, *this); GMS_TextureTransform tt; tt.type = transformType; scanner.nextFloat(tt.p1); scanner.nextFloat(tt.p2); shader.getTextureList().getTextureSampler(textureType).setTextureTransform(0, tt); }; } return ShaderCallback(); } Timeline::ShaderCallback Timeline::parseTexturePBR(GMXMLElement* e) { GMString pbrStr = e->Attribute("pbr"); if (!pbrStr.isEmpty()) { ShaderCallback cb = [this, e, pbrStr](GMShader& shader) { const PBR* pbr = findPBR(pbrStr); if (pbr) { shader.setIlluminationModel(gm::GMIlluminationModel::CookTorranceBRDF); GMToolUtil::addTextureToShader(shader, pbr->albedo, gm::GMTextureType::Albedo); GMToolUtil::addTextureToShader(shader, pbr->normal, gm::GMTextureType::NormalMap); GMToolUtil::addTextureToShader(shader, pbr->metallicRoughnessAO, gm::GMTextureType::MetallicRoughnessAO); } else { gm_warning(gm_dbg_wrap("Cannot find pbr assets: {0}"), pbrStr); } }; return cb; } return ShaderCallback(); } void Timeline::parseAttributes(GMGameObject* obj, GMXMLElement* e, Action& action) { GM_ASSERT(obj); { GMString value = e->Attribute("visible"); if (!value.isEmpty()) { bool visible = toBool(value); action.action = [action, obj, visible]() { if (action.action) action.action(); obj->setVisible(visible); }; } } { GMString value = e->Attribute("color"); if (!value.isEmpty()) { Scanner scanner(value, *this); Array<GMfloat, 4> color; scanner.nextFloat(color[0]); scanner.nextFloat(color[1]); scanner.nextFloat(color[2]); scanner.nextFloat(color[3]); action.action = [this, action, obj, color]() { obj->foreachModel([action, this, color, obj](GMModel* model) { if (action.action) action.action(); transferColorForModel(model, &color[0]); }); }; } } } void Timeline::parseWaveObjectAttributes(GMWaveGameObjectDescription& desc, GMXMLElement* e) { GMfloat terrainX = 0, terrainZ = 0; GMfloat terrainLength = 1, terrainWidth = 1, heightScaling = 10.f; GMint32 sliceX = 10, sliceY = 10; GMfloat texLen = 10, texHeight = 10; GMfloat texScaleLen = 2, texScaleHeight = 2; terrainX = parseFloat(e->Attribute("terrainX")); terrainZ = parseFloat(e->Attribute("terrainZ")); terrainLength = parseFloat(e->Attribute("length")); terrainWidth = parseFloat(e->Attribute("width")); heightScaling = parseFloat(e->Attribute("heightScaling")); GMString sliceStr = e->Attribute("slice"); if (!sliceStr.isEmpty()) { Scanner scanner(sliceStr, *this); scanner.nextInt(sliceX); scanner.nextInt(sliceY); } GMString texSizeStr = e->Attribute("textureSize"); if (!texSizeStr.isEmpty()) { Scanner scanner(texSizeStr, *this); scanner.nextFloat(texLen); scanner.nextFloat(texHeight); } GMString texScaling = e->Attribute("textureScaling"); if (!texScaling.isEmpty()) { Scanner scanner(texScaling, *this); scanner.nextFloat(texScaleLen); scanner.nextFloat(texScaleHeight); } desc.terrainX = terrainX; desc.terrainZ = terrainZ; desc.terrainLength = terrainLength; desc.terrainWidth = terrainWidth; desc.heightScaling = heightScaling; desc.sliceM = sliceX; desc.sliceN = sliceY; desc.textureLength = texLen; desc.textureHeight = texHeight; desc.textureScaleLength = texScaleLen; desc.textureScaleHeight = texScaleHeight; } void Timeline::parseWaveAttributes(GMWaveDescription& desc, GMXMLElement* e) { GMfloat steepness = 0; GMfloat amplitude = 1; GMfloat direction[3]; GMfloat speed = 2; GMfloat waveLength = 1; GMString steepnessStr = e->Attribute("steepness"); if (!steepnessStr.isEmpty()) steepness = parseFloat(steepnessStr); GMString amplitudeStr = e->Attribute("amplitude"); if (!amplitudeStr.isEmpty()) amplitude = parseFloat(amplitudeStr); GMString directionStr = e->Attribute("direction"); if (!directionStr.isEmpty()) { Scanner scanner(directionStr, *this); scanner.nextFloat(direction[0]); scanner.nextFloat(direction[1]); scanner.nextFloat(direction[2]); } GMString speedStr = e->Attribute("speed"); if (!speedStr.isEmpty()) speed = parseFloat(speedStr); GMString waveLengthStr = e->Attribute("waveLength"); if (!waveLengthStr.isEmpty()) waveLength = parseFloat(waveLengthStr); desc.steepness = steepness; desc.amplitude = amplitude; desc.direction[0] = direction[0]; desc.direction[1] = direction[1]; desc.direction[2] = direction[2]; desc.speed = speed; desc.waveLength = waveLength; } void Timeline::addObject(AutoReleasePtr<GMGameObject>* object, GMXMLElement*, Action& action) { action.action = [this, object]() { GMGameObject* obj = object->release(); m_world->addObjectAndInit(obj); m_world->addToRenderList(obj); GMDiscreteDynamicsWorld* ddw = dynamic_cast<GMDiscreteDynamicsWorld*>(m_world->getPhysicsWorld()); GMRigidPhysicsObject* rigidObj = dynamic_cast<GMRigidPhysicsObject*>(obj->getPhysicsObject()); if (ddw && rigidObj) ddw->addRigidObject(rigidObj); }; } void Timeline::addObject(AutoReleasePtr<ILight>* light, GMXMLElement*, Action& action) { action.action = [this, light]() { m_context->getEngine()->addLight(light->release()); }; } void Timeline::addObject(AutoReleasePtr<IParticleSystem>* particles, GMXMLElement* e, Action& action) { action.action = [this, particles]() { m_world->getParticleSystemManager()->addParticleSystem(particles->release()); }; } void Timeline::addObject(AutoReleasePtr<GMPhysicsWorld>* p, GMXMLElement* e, Action& action) { action.action = [this, p]() { m_world->setPhysicsWorld(p->release()); }; } void Timeline::addObject(GMShadowSourceDesc* s, GMXMLElement*, Action& action) { action.action = [this, s]() { m_context->getEngine()->setShadowSource(*s); }; } void Timeline::removeObject(ILight* light, GMXMLElement* e, Action& action) { GMString object = e->Attribute("object"); action.action = [this, light, object]() { IGraphicEngine* engine = m_context->getEngine(); if (!engine->removeLight(light)) gm_warning(gm_dbg_wrap("Cannot remove light: {0}."), object); }; } void Timeline::removeObject(GMGameObject* obj, GMXMLElement* e, Action& action, bool deleteFromMemory) { GMString objName = e->Attribute("object"); action.action = [this, obj, objName, deleteFromMemory]() { if (!m_world->removeFromRenderList(obj)) { gm_warning(gm_dbg_wrap("Cannot find object '{0}' from render list."), objName); } if (deleteFromMemory) { if (m_world->removeObject(obj)) { m_objects.erase(objName); } else { gm_warning(gm_dbg_wrap("Cannot find object '{0}' in world."), objName); } } }; } void Timeline::setColorForModel(GMModel* model, const GMfloat color[4]) { GMParts& parts = model->getParts(); GMVertices tmp; for (auto iter = parts.begin(); iter != parts.end(); ++iter) { GMPart* part = *iter; part->swap(tmp); for (GMVertex& v : tmp) { v.color = { color[0], color[1], color[2], color[3] }; } part->swap(tmp); } } void Timeline::transferColorForModel(GMModel* model, const GMfloat color[4]) { GMModelDataProxy* proxy = model->getModelDataProxy(); if (!proxy) { setColorForModel(model, color); } else { GMVertices& cache = m_verticesCache[model]; GM_ASSERT(model->getVerticesCount() == cache.size()); proxy->beginUpdateBuffer(GMModelBufferType::VertexBuffer); for (GMsize_t i = 0; i < cache.size(); ++i) { cache[i].color = { color[0], color[1], color[2], color[3] }; } memcpy_s(proxy->getBuffer(), sizeof(GMVertex) * model->getVerticesCount(), cache.data(), sizeof(GMVertex) * cache.size()); proxy->endUpdateBuffer(); } } CurveType Timeline::parseCurve(GMXMLElement* e, GMInterpolationFunctors& f) { GMString function = e->Attribute("function"); if (function == L"cubic-bezier") { GMString controlStr = e->Attribute("control"); if (!controlStr.isEmpty()) { GMfloat cpx0, cpy0, cpx1, cpy1; Scanner scanner(controlStr, *this); scanner.nextFloat(cpx0); scanner.nextFloat(cpy0); scanner.nextFloat(cpx1); scanner.nextFloat(cpy1); f = GMInterpolationFunctors::getDefaultInterpolationFunctors(); f.vec3Functor = GMSharedPtr<IInterpolationVec3>(new GMCubicBezierFunctor<GMVec3>(GMVec2(cpx0, cpy0), GMVec2(cpx1, cpy1))); f.vec4Functor = GMSharedPtr<IInterpolationVec4>(new GMCubicBezierFunctor<GMVec4>(GMVec2(cpx0, cpy0), GMVec2(cpx1, cpy1))); return CurveType::CubicBezier; } else { gm_warning(gm_dbg_wrap("Cubic bezier missing control points. Object for {0}"), GMString(e->Attribute("object"))); } } return CurveType::NoCurve; } void Timeline::bindAction(const Action& a) { if (a.runType == Action::Immediate) m_immediateActions.insert(a); else m_deferredActions.insert(a); } void Timeline::runImmediateActions() { for (auto iter = m_immediateActions.begin(); iter != m_immediateActions.end(); ) { auto action = *iter; if (action.runType == Action::Immediate) { if (action.action) action.action(); } iter = m_immediateActions.erase(iter); } } void Timeline::runActions() { while (m_currentAction != m_deferredActions.end()) { GM_ASSERT(m_currentAction->runType == Action::Deferred); auto next = m_currentAction; ++next; if (next == m_deferredActions.end()) { // 当前为最后一帧 if (m_timeline >= m_currentAction->timePoint) { if (m_currentAction->action) m_currentAction->action(); } else { break; } } else { // 当前不是最后一帧 if (m_currentAction->timePoint <= m_timeline) { if (m_currentAction->action) m_currentAction->action(); } else { break; } } ++m_currentAction; } if (m_currentAction == m_deferredActions.end()) { m_finished = true; m_playing = false; } } AssetType Timeline::getAssetType(const GMString& objectName, OUT void** out) { AssetType result = AssetType::NotFound; if (objectName == L"$camera") { result = AssetType::Camera; if (out) *out = &m_context->getEngine()->getCamera(); } else { do { if (getAssetAndType<AssetType::GameObject>(m_objects, objectName, result, out)) break; if (getAssetAndType<AssetType::Light>(m_lights, objectName, result, out)) break; if (getAssetAndType<AssetType::AudioSource>(m_audioSources, objectName, result, out)) break; if (getAssetAndType<AssetType::Particles>(m_particleSystems, objectName, result, out)) break; if (getAssetAndType<AssetType::Shadow>(m_shadows, objectName, result, out)) break; if (getAssetAndType<AssetType::PhysicsWorld>(m_physicsWorld, objectName, result, out)) break; } while (false); } return result; } void Timeline::playAudio(IAudioSource* source) { source->play(false); } void Timeline::play(GMGameObject* obj, const GMString& name) { if (!name.isEmpty()) { GMsize_t idx = obj->getAnimationIndexByName(name); if (idx == -1) { gm_warning(gm_dbg_wrap("Cannot find animation name of object: {0}"), name); } else { obj->setAnimation(idx); } } obj->reset(true); obj->play(); } GMint32 Timeline::parseInt(const GMString& str, bool* ok) { GMString temp = str; temp = getValueFromDefines(temp); return GMString::parseInt(temp, ok); } GMfloat Timeline::parseFloat(const GMString& str, bool* ok) { GMString temp = str; temp = getValueFromDefines(temp); return GMString::parseFloat(temp, ok); } bool Timeline::objectExists(const GMString& id) { bool exists = !(m_objects.find(id) == m_objects.end()); if (exists) { if (!m_supressedWarnings.isSet(Warning_ObjectExistsWarning)) gm_warning(gm_dbg_wrap("Object exists: '{0}'"), id); } return exists; } Scanner::Scanner(const GMString& line, Timeline& timeline) : m_timeline(timeline) , m_scanner(line) { } bool Scanner::nextInt(REF GMint32& value) { GMString str; m_scanner.next(str); if (str.isEmpty()) return false; value = m_timeline.parseInt(str); return true; } bool Scanner::nextFloat(REF GMfloat& value) { GMString str; m_scanner.next(str); if (str.isEmpty()) return false; value = m_timeline.parseFloat(str); return true; } Slots::Slots(Slots* parent) : m_parent(parent) { if (parent) parent->append(this); } Slots::~Slots() { while (!m_children.empty()) { m_children.front()->destroy(); } } Slots* Slots::getParent() { return m_parent; } bool Slots::addSlot(const GMString& name, const GMString& value) { if (name.isEmpty()) { gm_warning(gm_dbg_wrap("slot name is empty.")); return false; } auto result = m_slots.insert(std::make_pair(name, value)); if (!result.second) gm_warning(gm_dbg_wrap("Slot name exists: '{0}', add failed."), name); return result.second; } bool Slots::getSlotByName(const GMString& name, GMString& result) { auto iter = m_slots.find(name); bool notFound = (iter == m_slots.end()); if (!notFound) { result = iter->second; return true; } else { if (getParent()) return getParent()->getSlotByName(name, result); return false; } } void Slots::destroy() { if (getParent()) getParent()->remove(this); delete this; } void Slots::append(Slots* slots) { m_children.push_back(slots); } void Slots::remove(Slots* slots) { m_children.remove(slots); } SlotsStack::SlotsStack() : m_currentSlots(nullptr) , m_root(new Slots(nullptr)) { m_currentSlots = m_root.get(); } void SlotsStack::pushSlots() { m_currentSlots = new Slots(m_currentSlots); } void SlotsStack::popSlots() { if (m_currentSlots->getParent()) { Slots* tmp = m_currentSlots->getParent(); m_currentSlots->destroy(); m_currentSlots = tmp; } else { GM_ASSERT(m_currentSlots == m_root.get()); } } bool SlotsStack::addSlot(const GMString& name, const GMString& value) { return m_currentSlots->addSlot(name, value); } bool SlotsStack::getSlotByName(const GMString& name, GMString& result) { return m_currentSlots->getSlotByName(name, result); } SupressedWarnings::SupressedWarnings() { GM_ZeroMemory(&m_data[0], sizeof(m_data)); } void SupressedWarnings::set(Warning w) { ++m_data[w]; } bool SupressedWarnings::isSet(Warning w) { return m_data[w] > 0; } void SupressedWarnings::clear(Warning w) { if (m_data[w] > 0) --m_data[w]; }
0
0.95579
1
0.95579
game-dev
MEDIA
0.389715
game-dev
0.967698
1
0.967698
bencbartlett/Overmind
11,516
src/resources/Abathur.ts
import {Colony, getAllColonies} from '../Colony'; import {maxMarketPrices, TraderJoe} from '../logistics/TradeNetwork'; import {Mem} from '../memory/Memory'; import {profile} from '../profiler/decorator'; import {mergeSum, minMax, onPublicServer} from '../utilities/utils'; import {REAGENTS} from './map_resources'; export const priorityStockAmounts: { [key: string]: number } = { XGHO2: 1000, // (-70 % dmg taken) XLHO2: 1000, // (+300 % heal) XZHO2: 1000, // (+300 % fat decr - speed) XZH2O: 1000, // (+300 % dismantle) XKHO2: 1000, // (+300 % ranged attack) XUH2O: 1000, // (+300 % attack) GHO2 : 1000, // (-50 % dmg taken) LHO2 : 1000, // (+200 % heal) ZHO2 : 1000, // (+200 % fat decr - speed) ZH2O : 1000, // (+200 % dismantle) UH2O : 1000, // (+200 % attack) KHO2 : 1000, // (+200 % ranged attack) GO : 1000, // (-30 % dmg taken) LO : 1000, // (+100 % heal) ZO : 1000, // (+100 % fat decr - speed) ZH : 1000, // (+100 % dismantle) UH : 1000, // (+100 % attack) KO : 1000, // (+100 % ranged attack) G : 2000, // For nukes and common compounds }; export const wantedStockAmounts: { [key: string]: number } = { UH : 3000, // (+100 % attack) KO : 3000, // (+100 % ranged attack) XGHO2: 10000, // (-70 % dmg taken) XLHO2: 10000, // (+300 % heal) XZHO2: 6000, // (+300 % fat decr - speed) XZH2O: 6000, // (+300 % dismantle) XKHO2: 8000, // (+300 % ranged attack) XUH2O: 8000, // (+300 % attack) G : 5000, // For nukes XLH2O: 3000, // (+100 % build and repair) LH : 3000, // (+50 % build and repair) XUHO2: 3000, // (+600 % harvest) XKH2O: 3000, // (+300 % carry) ZK : 800, // intermediate UL : 800, // intermediate GH : 800, // (+50 % upgrade) KH : 800, // (+100 % carry) OH : 800, // intermediate GH2O : 800, // (+80 % upgrade) LH2O : 800, // (+80 % build and repair) KH2O : 800, // (+200 % carry) XGH2O: 12000, // (+100 % upgrade) }; export const baseStockAmounts: { [key: string]: number } = { [RESOURCE_CATALYST] : 5000, [RESOURCE_ZYNTHIUM] : 5000, [RESOURCE_LEMERGIUM]: 5000, [RESOURCE_KEANIUM] : 5000, [RESOURCE_UTRIUM] : 5000, [RESOURCE_OXYGEN] : 5000, [RESOURCE_HYDROGEN] : 5000 }; export interface Reaction { mineralType: string; amount: number; } // Compute priority and wanted stock const _priorityStock: Reaction[] = []; for (const resourceType in priorityStockAmounts) { const stock = { mineralType: resourceType, amount : priorityStockAmounts[resourceType] }; _priorityStock.push(stock); } const _wantedStock: Reaction[] = []; for (const resourceType in wantedStockAmounts) { const stock = { mineralType: resourceType, amount : wantedStockAmounts[resourceType] }; _wantedStock.push(stock); } export const priorityStock = _priorityStock; export const wantedStock = _wantedStock; interface AbathurMemory { sleepUntil: number; } const AbathurMemoryDefaults = { sleepUntil: 0 }; /** * Abathur is responsible for the evolution of the swarm and directs global production of minerals. Abathur likes * efficiency, XGHO2, and high lab uptime, and dislikes pronouns. */ @profile export class Abathur { colony: Colony; memory: AbathurMemory; priorityStock: Reaction[]; wantedStock: Reaction[]; assets: { [resourceType: string]: number }; private _globalAssets: { [resourceType: string]: number }; static settings = { minBatchSize: 100, // anything less than this wastes time maxBatchSize: 800, // manager/queen carry capacity sleepTime : 100, // sleep for this many ticks once you can't make anything }; constructor(colony: Colony) { this.colony = colony; this.memory = Mem.wrap(this.colony.memory, 'abathur', AbathurMemoryDefaults); this.priorityStock = priorityStock; this.wantedStock = wantedStock; this.assets = colony.assets; } refresh() { this.memory = Mem.wrap(this.colony.memory, 'abathur', AbathurMemoryDefaults); this.assets = this.colony.assets; } /** * Summarizes the total of all resources currently in a colony store structure */ private computeGlobalAssets(): { [resourceType: string]: number } { const colonyAssets: { [resourceType: string]: number }[] = []; for (const colony of getAllColonies()) { colonyAssets.push(colony.assets); } return mergeSum(colonyAssets); } get globalAssets(): { [resourceType: string]: number } { if (!this._globalAssets) { this._globalAssets = this.computeGlobalAssets(); } return this._globalAssets; } private canReceiveBasicMineralsForReaction(mineralQuantities: { [resourceType: string]: number }, amount: number): boolean { for (const mineral in mineralQuantities) { if (!this.someColonyHasExcess(<ResourceConstant>mineral, mineralQuantities[mineral])) { return false; } } return true; } private canBuyBasicMineralsForReaction(mineralQuantities: { [resourceType: string]: number }): boolean { if (Game.market.credits < TraderJoe.settings.market.reserveCredits) { return false; } for (const mineral in mineralQuantities) { let maxPrice = maxMarketPrices[mineral] || maxMarketPrices.default; if (!onPublicServer()) { maxPrice = Infinity; } if (Overmind.tradeNetwork.priceOf(<ResourceConstant>mineral) > maxPrice) { return false; } } return true; } static stockAmount(resource: ResourceConstant): number { return (wantedStockAmounts[resource] || priorityStockAmounts[resource] || baseStockAmounts[resource] || 0); } private hasExcess(mineralType: ResourceConstant, excessAmount = 0): boolean { return this.assets[mineralType] - excessAmount > Abathur.stockAmount(mineralType); } private someColonyHasExcess(mineralType: ResourceConstant, excessAmount = 0): boolean { return _.any(getAllColonies(), colony => colony.abathur.hasExcess(mineralType, excessAmount)); } /** * Generate a queue of reactions to produce the most needed compound */ getReactionQueue(verbose = false): Reaction[] { // Return nothing if you are sleeping; prevents wasteful reaction queue calculations if (Game.time < this.memory.sleepUntil) { return []; } // Compute the reaction queue for the highest priority item that you should be and can be making const stocksToCheck = [priorityStockAmounts, wantedStockAmounts]; for (const stocks of stocksToCheck) { for (const resourceType in stocks) { const amountOwned = this.assets[resourceType] || 0; const amountNeeded = stocks[resourceType]; if (amountOwned < amountNeeded) { // if there is a shortage of this resource const reactionQueue = this.buildReactionQueue(<ResourceConstant>resourceType, amountNeeded - amountOwned, verbose); const missingBaseMinerals = this.getMissingBasicMinerals(reactionQueue); if (!_.any(missingBaseMinerals) || this.canReceiveBasicMineralsForReaction(missingBaseMinerals, amountNeeded + 1000) || this.canBuyBasicMineralsForReaction(missingBaseMinerals)) { return reactionQueue; } else { if (verbose) console.log(`Missing minerals for ${resourceType}: ${JSON.stringify(missingBaseMinerals)}`); } } } } // If there's nothing you can make, sleep for 100 ticks this.memory.sleepUntil = Game.time + Abathur.settings.sleepTime; return []; } /** * Build a reaction queue for a target compound */ private buildReactionQueue(mineral: ResourceConstant, amount: number, verbose = false): Reaction[] { amount = minMax(amount, Abathur.settings.minBatchSize, Abathur.settings.maxBatchSize); if (verbose) console.log(`Abathur@${this.colony.room.print}: building reaction queue for ${amount} ${mineral}`); let reactionQueue: Reaction[] = []; for (const ingredient of this.ingredientsList(mineral)) { let productionAmount = amount; if (ingredient != mineral) { if (verbose) console.log(`productionAmount: ${productionAmount}, assets: ${this.assets[ingredient]}`); productionAmount = Math.max(productionAmount - (this.assets[ingredient] || 0), 0); } productionAmount = Math.min(productionAmount, Abathur.settings.maxBatchSize); reactionQueue.push({mineralType: ingredient, amount: productionAmount}); } if (verbose) console.log(`Pre-trim queue: ${JSON.stringify(reactionQueue)}`); reactionQueue = this.trimReactionQueue(reactionQueue); if (verbose) console.log(`Post-trim queue: ${JSON.stringify(reactionQueue)}`); reactionQueue = _.filter(reactionQueue, rxn => rxn.amount > 0); if (verbose) console.log(`Final queue: ${JSON.stringify(reactionQueue)}`); return reactionQueue; } /** * Trim a reaction queue, reducing the amounts of precursor compounds which need to be produced */ private trimReactionQueue(reactionQueue: Reaction[]): Reaction[] { // Scan backwards through the queue and reduce the production amount of subsequently baser resources as needed reactionQueue.reverse(); for (const reaction of reactionQueue) { const [ing1, ing2] = REAGENTS[reaction.mineralType]; const precursor1 = _.findIndex(reactionQueue, rxn => rxn.mineralType == ing1); const precursor2 = _.findIndex(reactionQueue, rxn => rxn.mineralType == ing2); for (const index of [precursor1, precursor2]) { if (index != -1) { if (reactionQueue[index].amount == 0) { reactionQueue[index].amount = 0; } else { reactionQueue[index].amount = minMax(reaction.amount, Abathur.settings.minBatchSize, reactionQueue[index].amount); } } } } reactionQueue.reverse(); return reactionQueue; } /** * Figure out which basic minerals are missing and how much */ getMissingBasicMinerals(reactionQueue: Reaction[], verbose = false): { [resourceType: string]: number } { const requiredBasicMinerals = this.getRequiredBasicMinerals(reactionQueue); if (verbose) console.log(`Required basic minerals: ${JSON.stringify(requiredBasicMinerals)}`); if (verbose) console.log(`assets: ${JSON.stringify(this.assets)}`); const missingBasicMinerals: { [resourceType: string]: number } = {}; for (const mineralType in requiredBasicMinerals) { const amountMissing = requiredBasicMinerals[mineralType] - (this.assets[mineralType] || 0); if (amountMissing > 0) { missingBasicMinerals[mineralType] = amountMissing; } } if (verbose) console.log(`Missing basic minerals: ${JSON.stringify(missingBasicMinerals)}`); return missingBasicMinerals; } /** * Get the required amount of basic minerals for a reaction queue */ private getRequiredBasicMinerals(reactionQueue: Reaction[]): { [resourceType: string]: number } { const requiredBasicMinerals: { [resourceType: string]: number } = { [RESOURCE_HYDROGEN] : 0, [RESOURCE_OXYGEN] : 0, [RESOURCE_UTRIUM] : 0, [RESOURCE_KEANIUM] : 0, [RESOURCE_LEMERGIUM]: 0, [RESOURCE_ZYNTHIUM] : 0, [RESOURCE_CATALYST] : 0, }; for (const reaction of reactionQueue) { const ingredients = REAGENTS[reaction.mineralType]; for (const ingredient of ingredients) { if (!REAGENTS[ingredient]) { // resource is base mineral requiredBasicMinerals[ingredient] += reaction.amount; } } } return requiredBasicMinerals; } /** * Recursively generate a list of ingredients required to produce a compound */ private ingredientsList(mineral: ResourceConstant): ResourceConstant[] { if (!REAGENTS[mineral] || _.isEmpty(mineral)) { return []; } else { return this.ingredientsList(REAGENTS[mineral][0]) .concat(this.ingredientsList(REAGENTS[mineral][1]), mineral); } } }
0
0.88724
1
0.88724
game-dev
MEDIA
0.980665
game-dev
0.935048
1
0.935048
kolmafia/kolmafia
4,730
src/net/sourceforge/kolmafia/textui/command/SpeculateCommand.java
package net.sourceforge.kolmafia.textui.command; import net.sourceforge.kolmafia.KoLCharacter; import net.sourceforge.kolmafia.KoLConstants; import net.sourceforge.kolmafia.KoLmafiaCLI.ParameterHandling; import net.sourceforge.kolmafia.ModifierType; import net.sourceforge.kolmafia.Modifiers; import net.sourceforge.kolmafia.RequestLogger; import net.sourceforge.kolmafia.Speculation; import net.sourceforge.kolmafia.modifiers.BitmapModifier; import net.sourceforge.kolmafia.modifiers.BooleanModifier; import net.sourceforge.kolmafia.modifiers.DerivedModifier; import net.sourceforge.kolmafia.modifiers.DoubleModifier; import net.sourceforge.kolmafia.modifiers.StringModifier; import net.sourceforge.kolmafia.persistence.ModifierDatabase; public class SpeculateCommand extends AbstractCommand { public SpeculateCommand() { this.usage = " MCD <num> | equip [<slot>] <item> | unequip <slot> | familiar <type> | enthrone <type> | bjornify <type> | up <eff> | uneffect <eff> | quiet ; [<another>;...] - predict modifiers."; this.flags = ParameterHandling.FULL_LINE; } @Override public void run(final String cmd, final String parameters) { Speculation spec = new Speculation(); boolean quiet = spec.parse(parameters); Modifiers mods = spec.calculate(); ModifierDatabase.overrideModifier(ModifierType.GENERATED, "_spec", mods); if (quiet) { return; } String table = SpeculateCommand.getHTML(mods, ""); if (table != null) { RequestLogger.printHtml(table + "<br>"); } else { RequestLogger.printLine("No modifiers changed."); } } public static String getHTML(Modifiers mods, String attribs) { StringBuilder buf = new StringBuilder("<table border=2 "); buf.append(attribs); buf.append(">"); int len = buf.length(); for (var mod : DoubleModifier.DOUBLE_MODIFIERS) { handleDouble(mod, mods, buf); } for (var mod : DerivedModifier.DERIVED_MODIFIERS) { handleDerived(mod, mods, buf); } for (var mod : BitmapModifier.BITMAP_MODIFIERS) { handleBitmap(mod, mods, buf); } for (var mod : BooleanModifier.BOOLEAN_MODIFIERS) { String modName = mod.getName(); boolean was = KoLCharacter.currentBooleanModifier(mod); boolean now = mods.getBoolean(mod); if (now == was) { continue; } buf.append("<tr><td>"); buf.append(modName); buf.append("</td><td>"); buf.append(now); buf.append("</td></tr>"); } for (var modifier : StringModifier.STRING_MODIFIERS) { String mod = modifier.getName(); String was = KoLCharacter.currentStringModifier(modifier); String now = mods.getString(modifier); if (now.equals(was)) { continue; } if (was.equals("")) { buf.append("<tr><td>"); buf.append(mod); buf.append("</td><td>"); buf.append(now.replaceAll("\t", "<br>")); buf.append("</td></tr>"); } else { buf.append("<tr><td rowspan=2>"); buf.append(mod); buf.append("</td><td>"); buf.append(was.replaceAll("\t", "<br>")); buf.append("</td></tr><tr><td>"); buf.append(now.replaceAll("\t", "<br>")); buf.append("</td></tr>"); } } if (buf.length() > len) { buf.append("</table>"); return buf.toString(); } return null; } private static void handleDouble( final DoubleModifier mod, final Modifiers mods, final StringBuilder buf) { double was = KoLCharacter.currentNumericModifier(mod); double now = mods.getDouble(mod); if (now == was) { return; } doNumeric(mod.getName(), was, now, buf); } private static void handleDerived( final DerivedModifier mod, final Modifiers mods, final StringBuilder buf) { double was = KoLCharacter.currentDerivedModifier(mod); double now = mods.getDerived(mod); if (now == was) { return; } doNumeric(mod.getName(), was, now, buf); } private static void handleBitmap( final BitmapModifier mod, final Modifiers mods, final StringBuilder buf) { double was = KoLCharacter.currentBitmapModifier(mod); double now = mods.getBitmap(mod); if (now == was) { return; } doNumeric(mod.getName(), was, now, buf); } private static void doNumeric( final String mod, final double was, final double now, final StringBuilder buf) { buf.append("<tr><td>"); buf.append(mod); buf.append("</td><td>"); buf.append(KoLConstants.FLOAT_FORMAT.format(now)); buf.append(" ("); if (now > was) { buf.append("+"); } buf.append(KoLConstants.FLOAT_FORMAT.format(now - was)); buf.append(")</td></tr>"); } }
0
0.641776
1
0.641776
game-dev
MEDIA
0.516944
game-dev
0.710036
1
0.710036
StateSmith/StateSmith
8,045
src/StateSmithTest/Output/Algos/out2/Balanced2_Cpp/RocketSm.cpp
// Autogenerated with StateSmith. // Algorithm: Balanced2. See https://github.com/StateSmith/StateSmith/wiki/Algorithms #include "RocketSm.hpp" #include <stdbool.h> // required for `consume_event` flag #include <string.h> // for memset // Starts the state machine. Must be called before dispatching events. Not thread safe. void RocketSm::start() { ROOT_enter(); // ROOT behavior // uml: TransitionTo(ROOT.<InitialState>) { // Step 1: Exit states until we reach `ROOT` state (Least Common Ancestor for transition). Already at LCA, no exiting required. // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `ROOT.<InitialState>`. // ROOT.<InitialState> is a pseudo state and cannot have an `enter` trigger. // ROOT.<InitialState> behavior // uml: TransitionTo(group) { // Step 1: Exit states until we reach `ROOT` state (Least Common Ancestor for transition). Already at LCA, no exiting required. // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `group`. GROUP_enter(); // group.<InitialState> behavior // uml: TransitionTo(g1) { // Step 1: Exit states until we reach `group` state (Least Common Ancestor for transition). Already at LCA, no exiting required. // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `g1`. G1_enter(); // Step 4: complete transition. Ends event dispatch. No other behaviors are checked. return; } // end of behavior for group.<InitialState> } // end of behavior for ROOT.<InitialState> } // end of behavior for ROOT } // Dispatches an event to the state machine. Not thread safe. // Note! This function assumes that the `eventId` parameter is valid. void RocketSm::dispatchEvent(EventId eventId) { switch (this->stateId) { // STATE: RocketSm case StateId::ROOT: // No events handled by this state (or its ancestors). break; // STATE: group case StateId::GROUP: switch (eventId) { case EventId::EV1: GROUP_ev1(); break; default: break; // to avoid "unused enumeration value in switch" warning } break; // STATE: g1 case StateId::G1: switch (eventId) { case EventId::EV1: G1_ev1(); break; default: break; // to avoid "unused enumeration value in switch" warning } break; // STATE: g2 case StateId::G2: switch (eventId) { case EventId::EV2: G2_ev2(); break; case EventId::EV1: GROUP_ev1(); break; // First ancestor handler for this event default: break; // to avoid "unused enumeration value in switch" warning } break; // STATE: s1 case StateId::S1: // No events handled by this state (or its ancestors). break; } } // This function is used when StateSmith doesn't know what the active leaf state is at // compile time due to sub states or when multiple states need to be exited. void RocketSm::exitUpToStateHandler(StateId desiredState) { while (this->stateId != desiredState) { switch (this->stateId) { case StateId::GROUP: GROUP_exit(); break; case StateId::G1: G1_exit(); break; case StateId::G2: G2_exit(); break; case StateId::S1: S1_exit(); break; default: return; // Just to be safe. Prevents infinite loop if state ID memory is somehow corrupted. } } } //////////////////////////////////////////////////////////////////////////////// // event handlers for state ROOT //////////////////////////////////////////////////////////////////////////////// void RocketSm::ROOT_enter() { this->stateId = StateId::ROOT; } //////////////////////////////////////////////////////////////////////////////// // event handlers for state GROUP //////////////////////////////////////////////////////////////////////////////// void RocketSm::GROUP_enter() { this->stateId = StateId::GROUP; } void RocketSm::GROUP_exit() { this->stateId = StateId::ROOT; } void RocketSm::GROUP_ev1() { // group behavior // uml: EV1 TransitionTo(s1) { // Step 1: Exit states until we reach `ROOT` state (Least Common Ancestor for transition). exitUpToStateHandler(StateId::ROOT); // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `s1`. S1_enter(); // Step 4: complete transition. Ends event dispatch. No other behaviors are checked. return; } // end of behavior for group // No ancestor handles this event. } //////////////////////////////////////////////////////////////////////////////// // event handlers for state G1 //////////////////////////////////////////////////////////////////////////////// void RocketSm::G1_enter() { this->stateId = StateId::G1; } void RocketSm::G1_exit() { this->stateId = StateId::GROUP; } void RocketSm::G1_ev1() { bool consume_event = false; // g1 behavior // uml: EV1 [a > 20] TransitionTo(g2) if (a > 20) { // Step 1: Exit states until we reach `group` state (Least Common Ancestor for transition). G1_exit(); // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `g2`. G2_enter(); // Step 4: complete transition. Ends event dispatch. No other behaviors are checked. return; } // end of behavior for g1 // Check if event has been consumed before calling ancestor handler. if (!consume_event) { GROUP_ev1(); } } //////////////////////////////////////////////////////////////////////////////// // event handlers for state G2 //////////////////////////////////////////////////////////////////////////////// void RocketSm::G2_enter() { this->stateId = StateId::G2; } void RocketSm::G2_exit() { this->stateId = StateId::GROUP; } void RocketSm::G2_ev2() { // g2 behavior // uml: EV2 TransitionTo(g1) { // Step 1: Exit states until we reach `group` state (Least Common Ancestor for transition). G2_exit(); // Step 2: Transition action: ``. // Step 3: Enter/move towards transition target `g1`. G1_enter(); // Step 4: complete transition. Ends event dispatch. No other behaviors are checked. return; } // end of behavior for g2 // No ancestor handles this event. } //////////////////////////////////////////////////////////////////////////////// // event handlers for state S1 //////////////////////////////////////////////////////////////////////////////// void RocketSm::S1_enter() { this->stateId = StateId::S1; } void RocketSm::S1_exit() { this->stateId = StateId::ROOT; } // Thread safe. char const * RocketSm::stateIdToString(StateId id) { switch (id) { case StateId::ROOT: return "ROOT"; case StateId::GROUP: return "GROUP"; case StateId::G1: return "G1"; case StateId::G2: return "G2"; case StateId::S1: return "S1"; default: return "?"; } } // Thread safe. char const * RocketSm::eventIdToString(EventId id) { switch (id) { case EventId::EV1: return "EV1"; case EventId::EV2: return "EV2"; default: return "?"; } }
0
0.830678
1
0.830678
game-dev
MEDIA
0.346029
game-dev
0.922451
1
0.922451
Space-Stories/space-station-14
2,569
Content.Server/Construction/Conditions/MinSolution.cs
using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Chemistry.Reagent; using Content.Shared.Construction; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Robust.Shared.Prototypes; namespace Content.Server.Construction.Conditions; /// <summary> /// Requires that a certain solution has a minimum amount of a reagent to proceed. /// </summary> [DataDefinition] public sealed partial class MinSolution : IGraphCondition { /// <summary> /// The solution that needs to have the reagent. /// </summary> [DataField(required: true)] public string Solution = string.Empty; /// <summary> /// The reagent that needs to be present. /// </summary> [DataField(required: true)] public ReagentId Reagent = new(); /// <summary> /// How much of the reagent must be present. /// </summary> [DataField] public FixedPoint2 Quantity = 1; public bool Condition(EntityUid uid, IEntityManager entMan) { var containerSys = entMan.System<SharedSolutionContainerSystem>(); if (!containerSys.TryGetSolution(uid, Solution, out _, out var solution)) return false; solution.TryGetReagentQuantity(Reagent, out var quantity); return quantity >= Quantity; } public bool DoExamine(ExaminedEvent args) { var entMan = IoCManager.Resolve<IEntityManager>(); var uid = args.Examined; var containerSys = entMan.System<SharedSolutionContainerSystem>(); if (!containerSys.TryGetSolution(uid, Solution, out _, out var solution)) return false; solution.TryGetReagentQuantity(Reagent, out var quantity); // already has enough so dont show examine if (quantity >= Quantity) return false; args.PushMarkup(Loc.GetString("construction-examine-condition-min-solution", ("quantity", Quantity - quantity), ("reagent", Name())) + "\n"); return true; } public IEnumerable<ConstructionGuideEntry> GenerateGuideEntry() { yield return new ConstructionGuideEntry() { Localization = "construction-guide-condition-min-solution", Arguments = new (string, object)[] { ("quantity", Quantity), ("reagent", Name()) } }; } private string Name() { var protoMan = IoCManager.Resolve<IPrototypeManager>(); var proto = protoMan.Index<ReagentPrototype>(Reagent.Prototype); return proto.LocalizedName; } }
0
0.850888
1
0.850888
game-dev
MEDIA
0.370505
game-dev
0.867128
1
0.867128
AscEmu/AscEmu
1,357
src/world/Server/Packets/Handlers/CombatHandler.cpp
/* Copyright (c) 2014-2025 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #include "Logging/Logger.hpp" #include "Server/Packets/CmsgAttackSwing.h" #include "Server/WorldSession.h" #include "Objects/Units/Players/Player.hpp" #include "Map/Maps/WorldMap.hpp" using namespace AscEmu::Packets; void WorldSession::handleAttackSwingOpcode(WorldPacket& recvPacket) { CmsgAttackSwing srlPacket; if (!srlPacket.deserialise(recvPacket)) return; sLogger.debugFlag(AscEmu::Logging::LF_OPCODE, "Received CMSG_ATTACKSWING: {} (guidLow)", srlPacket.guid.getGuidLow()); if (_player->isFeared() || _player->isStunned() || _player->isPacified() || _player->isDead()) return; const auto unitTarget = _player->getWorldMap()->getUnit(srlPacket.guid.getRawGuid()); if (unitTarget == nullptr) return; if (!_player->isValidTarget(unitTarget) || unitTarget->isDead()) return; _player->smsg_AttackStart(unitTarget); _player->eventAttackStart(); } void WorldSession::handleAttackStopOpcode(WorldPacket& /*recvPacket*/) { const auto unitTarget = _player->getWorldMap()->getUnit(_player->getTargetGuid()); if (unitTarget == nullptr) return; _player->eventAttackStop(); _player->smsg_AttackStop(unitTarget); }
0
0.976037
1
0.976037
game-dev
MEDIA
0.937725
game-dev
0.971244
1
0.971244
mayao11/PracticalGameAI
1,430
AI_Enemy3_Behavior/Assets/Behavior Designer/Runtime/Basic Tasks/CharacterController/HasColliderHit.cs
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityCharacterController { [TaskCategory("Basic/CharacterController")] [TaskDescription("Returns Success if the collider hit another object, otherwise Failure.")] public class HasColliderHit : Conditional { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The tag of the GameObject to check for a collision against")] public SharedString tag = ""; [Tooltip("The object that started the collision")] public SharedGameObject collidedGameObject; private bool enteredCollision = false; public override TaskStatus OnUpdate() { return enteredCollision ? TaskStatus.Success : TaskStatus.Failure; } public override void OnEnd() { enteredCollision = false; } public override void OnControllerColliderHit(ControllerColliderHit hit) { if (string.IsNullOrEmpty(tag.Value) || tag.Value.Equals(hit.gameObject.tag)) { collidedGameObject.Value = hit.gameObject; enteredCollision = true; } } public override void OnReset() { targetGameObject = null; tag = ""; collidedGameObject = null; } } }
0
0.655337
1
0.655337
game-dev
MEDIA
0.943875
game-dev
0.664042
1
0.664042
PotRooms/StarResonanceData
1,129
lua/goal/goals/goal_in_map_area.lua
local super = require("goal.goal_base") local GoalInMapArea = class("GoalInMapArea", super) function GoalInMapArea:ctor(data) super.ctor() self.configData_ = data end function GoalInMapArea:GetGoalKey() local data = self.configData_ return E.GoalType.InMapArea .. data.SceneId .. data.AreaId end function GoalInMapArea:GoalInit() self:checkGoalFinish() Z.EventMgr:Add(Z.ConstValue.MapAreaChange, self.checkGoalFinish, self) end function GoalInMapArea:GoalUnInit() Z.EventMgr:RemoveObjAll(self) end function GoalInMapArea:checkGoalFinish() local sceneId = Z.StageMgr.GetCurrentSceneId() if sceneId ~= self.configData_.SceneId then return end local mapData = Z.DataMgr.Get("map_data") if self.configData_.AreaId == 0 or mapData.CurAreaId == self.configData_.AreaId then local goalVM = Z.VMMgr.GetVM("goal") goalVM.SetGoalFinish(E.GoalType.InMapArea, self.configData_.AreaId) end end local create = function(strList) local data = {} data.SceneId = tonumber(strList[3]) data.AreaId = tonumber(strList[4]) return GoalInMapArea.new(data) end local ret = {Create = create} return ret
0
0.669984
1
0.669984
game-dev
MEDIA
0.722677
game-dev
0.851736
1
0.851736
HbmMods/Hbm-s-Nuclear-Tech-GIT
1,812
src/main/java/com/hbm/inventory/gui/GUIElectrolyser.java
package com.hbm.inventory.gui; import org.lwjgl.opengl.GL11; import com.hbm.inventory.container.ContainerElectrolyser; import com.hbm.lib.RefStrings; import com.hbm.tileentity.machine.TileEntityElectrolyser; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; public class GUIElectrolyser extends GuiInfoContainer { public static ResourceLocation texture = new ResourceLocation(RefStrings.MODID + ":textures/gui/processing/gui_electrolyser.png"); private TileEntityElectrolyser electrolyser; public GUIElectrolyser(InventoryPlayer invPlayer, TileEntityElectrolyser electrolyser) { super(new ContainerElectrolyser(invPlayer, electrolyser)); this.electrolyser = electrolyser; this.xSize = 210; this.ySize = 247; } @Override public void drawScreen(int mouseX, int mouseY, float f) { super.drawScreen(mouseX, mouseY, f); } protected void mouseClicked(int x, int y, int i) { super.mouseClicked(x, y, i); } @Override protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); Minecraft.getMinecraft().getTextureManager().bindTexture(texture); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); } @Override protected void drawGuiContainerForegroundLayer(int i, int j) { String name = this.electrolyser.hasCustomInventoryName() ? this.electrolyser.getInventoryName() : I18n.format(this.electrolyser.getInventoryName()); this.fontRendererObj.drawString(name, (this.xSize / 2 - this.fontRendererObj.getStringWidth(name) / 2) - 16, 7, 0xffffff); this.fontRendererObj.drawString(I18n.format("container.inventory"), 8, this.ySize - 94, 4210752); } }
0
0.872343
1
0.872343
game-dev
MEDIA
0.911015
game-dev
0.962673
1
0.962673
PotRooms/StarResonanceData
1,106
lua/table/gen/CookCuisineRandomTableMgr.lua
local CookCuisineRandomTableRow local mgr = require("utility.table_manager") local TableInitUtility = Panda.TableInitUtility local super = require("table.table_manager_base") local CookCuisineRandomTableMgr = class("CookCuisineRandomTableMgr", super) function CookCuisineRandomTableMgr:ctor(ptr, fields) super.ctor(self, ptr, fields) end function CookCuisineRandomTableMgr:GetRow(key, notErrorWhenNotFound) local ret = self.__rows[key] if ret ~= nil then return ret end ret = super.GetRow(self, key, "int") if not ret then if not notErrorWhenNotFound then logError("CookCuisineRandomTableMgr:GetRow key:{0} failed in scene:{1}", key, self.GetCurrentSceneId()) end return nil end return ret end function CookCuisineRandomTableMgr:GetDatas() return super.GetDatas(self) end local wrapper return { __init = function(ptr, fields) wrapper = CookCuisineRandomTableMgr.new(ptr, fields) end, GetRow = function(key, notErrorWhenNotFound) return wrapper:GetRow(key, notErrorWhenNotFound) end, GetDatas = function() return wrapper:GetDatas() end }
0
0.683992
1
0.683992
game-dev
MEDIA
0.705122
game-dev
0.687519
1
0.687519
spring/spring
53,029
cont/base/springcontent/LuaGadgets/gadgets.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: gadgets.lua -- brief: the gadget manager, a call-in router -- author: Dave Rodgers -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- TODO: - get rid of the ':'/self referencing, it's a waste of cycles -- - (De)RegisterCOBCallback(data) + callin? -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local SAFEWRAP = 0 -- 0: disabled -- 1: enabled, but can be overriden by gadget.GetInfo().unsafe -- 2: always enabled local HANDLER_DIR = 'LuaGadgets/' local GADGETS_DIR = Script.GetName():gsub('US$', '') .. '/Gadgets/' local LOG_SECTION = "" -- FIXME: "LuaRules" section is not registered anywhere local VFSMODE = VFS.ZIP_ONLY -- FIXME: ZIP_FIRST ? if (Spring.IsDevLuaEnabled()) then VFSMODE = VFS.RAW_ONLY end VFS.Include(HANDLER_DIR .. 'setupdefs.lua', nil, VFSMODE) VFS.Include(HANDLER_DIR .. 'system.lua', nil, VFSMODE) VFS.Include(HANDLER_DIR .. 'callins.lua', nil, VFSMODE) local actionHandler = VFS.Include(HANDLER_DIR .. 'actions.lua', nil, VFSMODE) -------------------------------------------------------------------------------- function pgl() -- (print gadget list) FIXME: move this into a gadget for k,v in ipairs(gadgetHandler.gadgets) do Spring.Log(LOG_SECTION, LOG.ERROR, string.format("%3i %3i %s", k, v.ghInfo.layer, v.ghInfo.name) ) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- the gadgetHandler object -- gadgetHandler = { gadgets = {}, orderList = {}, knownGadgets = {}, knownCount = 0, knownChanged = true, GG = {}, -- shared table for gadgets globals = {}, -- global vars/funcs CMDIDs = {}, xViewSize = 1, yViewSize = 1, actionHandler = actionHandler, mouseOwner = nil, } -- initialize the call-in lists do for _,listname in ipairs(CALLIN_LIST) do gadgetHandler[listname .. 'List'] = {} end end -- Utility call local isSyncedCode = (SendToUnsynced ~= nil) local function IsSyncedCode() return isSyncedCode end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- array-table reverse iterator -- -- all callin handlers use this so that gadgets can -- RemoveGadget() themselves (during iteration over -- a callin list) without causing a miscount -- -- c.f. Array{Insert,Remove} -- local function r_ipairs(tbl) local function r_iter(tbl, key) if (key <= 1) then return nil end -- next idx, next val return (key - 1), tbl[key - 1] end return r_iter, tbl, (1 + #tbl) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- returns: basename, dirname -- local function Basename(fullpath) local _,_,base = string.find(fullpath, "([^\\/:]*)$") local _,_,path = string.find(fullpath, "(.*[\\/:])[^\\/:]*$") if (path == nil) then path = "" end return base, path end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:Initialize() local syncedHandler = Script.GetSynced() if not syncedHandler then self.xViewSize, self.yViewSize = Spring.GetViewGeometry() end local unsortedGadgets = {} -- get the gadget names local gadgetFiles = VFS.DirList(GADGETS_DIR, "*.lua", VFSMODE) -- table.sort(gadgetFiles) -- for k,gf in ipairs(gadgetFiles) do -- Spring.Echo('gf1 = ' .. gf) -- FIXME -- end -- stuff the gadgets into unsortedGadgets for k,gf in ipairs(gadgetFiles) do -- Spring.Echo('gf2 = ' .. gf) -- FIXME local gadget = self:LoadGadget(gf) if (gadget) then table.insert(unsortedGadgets, gadget) end end -- sort the gadgets table.sort(unsortedGadgets, function(g1, g2) local l1 = g1.ghInfo.layer local l2 = g2.ghInfo.layer if (l1 ~= l2) then return (l1 < l2) end local n1 = g1.ghInfo.name local n2 = g2.ghInfo.name local o1 = self.orderList[n1] local o2 = self.orderList[n2] if (o1 ~= o2) then return (o1 < o2) else return (n1 < n2) end end) -- add the gadgets for _,g in ipairs(unsortedGadgets) do gadgetHandler:InsertGadget(g) local gtype = ((syncedHandler and "SYNCED") or "UNSYNCED") local gname = g.ghInfo.name local gbasename = g.ghInfo.basename Spring.Log(LOG_SECTION, LOG.INFO, string.format("Loaded %s gadget: %-18s <%s>", gtype, gname, gbasename)) end end function gadgetHandler:LoadGadget(filename) local basename = Basename(filename) local text = VFS.LoadFile(filename, VFSMODE) if (text == nil) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Failed to load: ' .. filename) return nil end local chunk, err = loadstring(text, filename) if (chunk == nil) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Failed to load: ' .. basename .. ' (' .. err .. ')') return nil end local gadget = gadgetHandler:NewGadget() setfenv(chunk, gadget) local success, err = pcall(chunk) if (not success) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Failed to load: ' .. basename .. ' (' .. tostring(err) .. ')') return nil end if (err == false) then return nil -- gadget asked for a quiet death end -- raw access to gadgetHandler if (gadget.GetInfo and gadget:GetInfo().handler) then gadget.gadgetHandler = self end self:FinalizeGadget(gadget, filename, basename) local name = gadget.ghInfo.name err = self:ValidateGadget(gadget) if (err) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Failed to load: ' .. basename .. ' (' .. err .. ')') return nil end local knownInfo = self.knownGadgets[name] if (knownInfo) then if (knownInfo.active) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Failed to load: ' .. basename .. ' (duplicate name)') return nil end else -- create a knownInfo table knownInfo = {} knownInfo.desc = gadget.ghInfo.desc knownInfo.author = gadget.ghInfo.author knownInfo.basename = gadget.ghInfo.basename knownInfo.filename = gadget.ghInfo.filename self.knownGadgets[name] = knownInfo self.knownCount = self.knownCount + 1 self.knownChanged = true end knownInfo.active = true local info = gadget.GetInfo and gadget:GetInfo() local order = self.orderList[name] if (((order ~= nil) and (order > 0)) or ((order == nil) and ((info == nil) or info.enabled))) then -- this will be an active gadget if (order == nil) then self.orderList[name] = 12345 -- back of the pack else self.orderList[name] = order end else self.orderList[name] = 0 self.knownGadgets[name].active = false return nil end return gadget end function gadgetHandler:NewGadget() local gadget = {} -- load the system calls into the gadget table for k,v in pairs(System) do gadget[k] = v end gadget._G = _G -- the global table gadget.GG = self.GG -- the shared table gadget.gadget = gadget -- easy self referencing -- wrapped calls (closures) gadget.gadgetHandler = {} local gh = gadget.gadgetHandler local self = self gadget.include = function (f) return VFS.Include(f, gadget, VFSMODE) end gh.RaiseGadget = function (_) self:RaiseGadget(gadget) end gh.LowerGadget = function (_) self:LowerGadget(gadget) end gh.RemoveGadget = function (_) self:RemoveGadget(gadget) end gh.GetViewSizes = function (_) return self:GetViewSizes() end gh.GetHourTimer = function (_) return self:GetHourTimer() end gh.IsSyncedCode = function (_) return IsSyncedCode() end gh.UpdateCallIn = function (_, name) self:UpdateGadgetCallIn(name, gadget) end gh.RemoveCallIn = function (_, name) self:RemoveGadgetCallIn(name, gadget) end gh.RegisterCMDID = function(_, id) self:RegisterCMDID(gadget, id) end gh.RegisterGlobal = function(_, name, value) return self:RegisterGlobal(gadget, name, value) end gh.DeregisterGlobal = function(_, name) return self:DeregisterGlobal(gadget, name) end gh.SetGlobal = function(_, name, value) return self:SetGlobal(gadget, name, value) end gh.AddChatAction = function (_, cmd, func, help) return actionHandler.AddChatAction(gadget, cmd, func, help) end gh.RemoveChatAction = function (_, cmd) return actionHandler.RemoveChatAction(gadget, cmd) end if (not IsSyncedCode()) then gh.AddSyncAction = function(_, cmd, func, help) return actionHandler.AddSyncAction(gadget, cmd, func, help) end gh.RemoveSyncAction = function(_, cmd) return actionHandler.RemoveSyncAction(gadget, cmd) end end -- for proxied call-ins gh.IsMouseOwner = function (_) return (self.mouseOwner == gadget) end gh.DisownMouse = function (_) if (self.mouseOwner == gadget) then self.mouseOwner = nil end end return gadget end function gadgetHandler:FinalizeGadget(gadget, filename, basename) local gi = {} gi.filename = filename gi.basename = basename if (gadget.GetInfo == nil) then gi.name = basename gi.layer = 0 else local info = gadget:GetInfo() gi.name = info.name or basename gi.layer = info.layer or 0 gi.desc = info.desc or "" gi.author = info.author or "" gi.license = info.license or "" gi.enabled = info.enabled or false end gadget.ghInfo = {} -- a proxy table local mt = { __index = gi, __newindex = function() error("ghInfo tables are read-only") end, __metatable = "protected" } setmetatable(gadget.ghInfo, mt) end function gadgetHandler:ValidateGadget(gadget) if (gadget.GetTooltip and not gadget.IsAbove) then return "Gadget has GetTooltip() but not IsAbove()" end if (gadget.TweakGetTooltip and not gadget.TweakIsAbove) then return "Gadget has TweakGetTooltip() but not TweakIsAbove()" end return nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function SafeWrap(func, funcName) local gh = gadgetHandler return function(g, ...) local r = { pcall(func, g, ...) } if (r[1]) then table.remove(r, 1) return unpack(r) else if (funcName ~= 'Shutdown') then gadgetHandler:RemoveGadget(g) else Spring.Log(LOG_SECTION, LOG.ERROR, 'Error in Shutdown') end local name = g.ghInfo.name Spring.Log(LOG_SECTION, LOG.INFO, r[2]) Spring.Log(LOG_SECTION, LOG.INFO, 'Removed gadget: ' .. name) return nil end end end local function SafeWrapGadget(gadget) if (SAFEWRAP <= 0) then return elseif (SAFEWRAP == 1) then if (gadget.GetInfo and gadget.GetInfo().unsafe) then Spring.Log(LOG_SECTION, LOG.ERROR, 'LuaUI: loaded unsafe gadget: ' .. gadget.ghInfo.name) return end end for _,ciName in ipairs(CALLIN_LIST) do if (gadget[ciName]) then gadget[ciName] = SafeWrap(gadget[ciName], ciName) end if (gadget.Initialize) then gadget.Initialize = SafeWrap(gadget.Initialize, 'Initialize') end end end -------------------------------------------------------------------------------- local function ArrayInsert(t, g) local layer = g.ghInfo.layer local index = 1 for i,v in ipairs(t) do if (v == g) then return -- already in the table end -- insert-sort the gadget based on its layer -- note: reversed value ordering, highest to lowest -- iteration over the callin lists is also reversed if (layer < v.ghInfo.layer) then index = i + 1 end end table.insert(t, index, g) end local function ArrayRemove(t, g) for k,v in ipairs(t) do if (v == g) then table.remove(t, k) -- break end end end function gadgetHandler:InsertGadget(gadget) if (gadget == nil) then return end ArrayInsert(self.gadgets, gadget) for _,listname in ipairs(CALLIN_LIST) do local func = gadget[listname] if (func ~= nil and type(func) == 'function') then ArrayInsert(self[listname .. 'List'], gadget) end end self:UpdateCallIns() if (gadget.Initialize) then gadget:Initialize() end if self.knownGadgets[gadget.ghInfo.name].active then -- Gadget initialized successfully and did not remove itself. if gadget.ViewResize then gadget:ViewResize(self.xViewSize, self.yViewSize) end end end function gadgetHandler:RemoveGadget(gadget) if (gadget == nil) then return end local name = gadget.ghInfo.name self.knownGadgets[name].active = false if (gadget.Shutdown) then gadget:Shutdown() end ArrayRemove(self.gadgets, gadget) self:RemoveGadgetGlobals(gadget) actionHandler.RemoveGadgetActions(gadget) for _,listname in ipairs(CALLIN_LIST) do ArrayRemove(self[listname..'List'], gadget) end for id,g in pairs(self.CMDIDs) do if (g == gadget) then self.CMDIDs[id] = nil end end self:UpdateCallIns() end -------------------------------------------------------------------------------- function gadgetHandler:UpdateCallIn(name) local listName = name .. 'List' local forceUpdate = (name == 'GotChatMsg' or name == 'RecvFromSynced') -- redundant? _G[name] = nil if (forceUpdate or #self[listName] > 0) then local selffunc = self[name] if (selffunc ~= nil) then _G[name] = function(...) return selffunc(self, ...) end else Spring.Log(LOG_SECTION, LOG.ERROR, "UpdateCallIn: " .. name .. " is not implemented") end end Script.UpdateCallIn(name) end function gadgetHandler:UpdateGadgetCallIn(name, g) local listName = name .. 'List' local ciList = self[listName] if (ciList) then local func = g[name] if (func ~= nil and type(func) == 'function') then ArrayInsert(ciList, g) else ArrayRemove(ciList, g) end self:UpdateCallIn(name) else Spring.Log(LOG_SECTION, LOG.ERROR, 'UpdateGadgetCallIn: bad name: ' .. name) end end function gadgetHandler:RemoveGadgetCallIn(name, g) local listName = name .. 'List' local ciList = self[listName] if (ciList) then ArrayRemove(ciList, g) self:UpdateCallIn(name) else Spring.Log(LOG_SECTION, LOG.ERROR, 'RemoveGadgetCallIn: bad name: ' .. name) end end function gadgetHandler:UpdateCallIns() for _,name in ipairs(CALLIN_LIST) do self:UpdateCallIn(name) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:EnableGadget(name) local ki = self.knownGadgets[name] if (not ki) then Spring.Log(LOG_SECTION, LOG.ERROR, "EnableGadget(), could not find gadget: " .. tostring(name)) return false end if (not ki.active) then Spring.Log(LOG_SECTION, LOG.INFO, 'Loading: '..ki.filename) local order = gadgetHandler.orderList[name] if (not order or (order <= 0)) then self.orderList[name] = 1 end local w = self:LoadGadget(ki.filename) if (not w) then return false end self:InsertGadget(w) end return true end function gadgetHandler:DisableGadget(name) local ki = self.knownGadgets[name] if (not ki) then Spring.Log(LOG_SECTION, LOG.ERROR, "DisableGadget(), could not find gadget: " .. tostring(name)) return false end if (ki.active) then local w = self:FindGadget(name) if (not w) then return false end Spring.Log(LOG_SECTION, LOG.INFO, 'Removed: '..ki.filename) self:RemoveGadget(w) -- deactivate self.orderList[name] = 0 -- disable end return true end function gadgetHandler:ToggleGadget(name) local ki = self.knownGadgets[name] if (not ki) then Spring.Log(LOG_SECTION, LOG.ERROR, "ToggleGadget(), could not find gadget: " .. tostring(name)) return end if (ki.active) then return self:DisableGadget(name) elseif (self.orderList[name] <= 0) then return self:EnableGadget(name) else -- the gadget is not active, but enabled; disable it self.orderList[name] = 0 end return true end -------------------------------------------------------------------------------- local function FindGadgetIndex(t, w) for k,v in ipairs(t) do if (v == w) then return k end end return nil end function gadgetHandler:RaiseGadget(gadget) if (gadget == nil) then return end local function FindLowestIndex(t, i, layer) local n = #t for x = (i + 1), n, 1 do if (t[x].ghInfo.layer < layer) then return (x - 1) end end return n end local function Raise(callinList, gadget) local gadgetIdx = FindGadgetIndex(callinList, gadget) if (gadgetIdx == nil) then return end -- starting from gIdx and counting up, find the index -- of the first gadget whose layer is lower** than g's -- and move g to right before (lowestIdx - 1) it -- ** lists are in reverse layer order, lowest at back local lowestIdx = FindLowestIndex(callinList, gadgetIdx, gadget.ghInfo.layer) if (lowestIdx > gadgetIdx) then -- insert first since lowestIdx is larger table.insert(callinList, lowestIdx, gadget) table.remove(callinList, gadgetIdx) end end Raise(self.gadgets, gadget) for _,listname in ipairs(CALLIN_LIST) do if (gadget[listname] ~= nil) then Raise(self[listname .. 'List'], gadget) end end end function gadgetHandler:LowerGadget(gadget) if (gadget == nil) then return end local function FindHighestIndex(t, i, layer) for x = (i - 1), 1, -1 do if (t[x].ghInfo.layer > layer) then return (x + 1) end end return 1 end local function Lower(callinList, gadget) local gadgetIdx = FindGadgetIndex(callinList, gadget) if (gadgetIdx == nil) then return end -- starting from gIdx and counting down, find the index -- of the first gadget whose layer is higher** than g's -- and move g to right after (highestIdx + 1) it -- ** lists are in reverse layer order, highest at front local highestIdx = FindHighestIndex(callinList, gadgetIdx, gadget.ghInfo.layer) if (highestIdx < gadgetIdx) then -- remove first since highestIdx is smaller table.remove(callinList, gadgetIdx) table.insert(callinList, highestIdx, gadget) end end Lower(self.gadgets, gadget) for _,listname in ipairs(CALLIN_LIST) do if (gadget[listname] ~= nil) then Lower(self[listname .. 'List'], gadget) end end end function gadgetHandler:FindGadget(name) if (type(name) ~= 'string') then return nil end for k,v in ipairs(self.gadgets) do if (name == v.ghInfo.name) then return v,k end end return nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Global var/func management -- function gadgetHandler:RegisterGlobal(owner, name, value) if (name == nil) then return false end if (_G[name] ~= nil) then return false end if (self.globals[name] ~= nil) then return false end if (CALLIN_MAP[name] ~= nil) then return false end _G[name] = value self.globals[name] = owner return true end function gadgetHandler:DeregisterGlobal(owner, name) if (name == nil) then return false end _G[name] = nil self.globals[name] = nil return true end function gadgetHandler:SetGlobal(owner, name, value) if ((name == nil) or (self.globals[name] ~= owner)) then return false end _G[name] = value return true end function gadgetHandler:RemoveGadgetGlobals(owner) local count = 0 for name, o in pairs(self.globals) do if (o == owner) then _G[name] = nil self.globals[name] = nil count = count + 1 end end return count end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Helper facilities -- local hourTimer = 0 function gadgetHandler:GetHourTimer() return hourTimer end function gadgetHandler:GetViewSizes() return self.xViewSize, self.yViewSize end function gadgetHandler:RegisterCMDID(gadget, id) if (id <= 1000) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Gadget (' .. gadget.ghInfo.name .. ') ' .. 'tried to register a reserved CMD_ID') Script.Kill('Reserved CMD_ID code: ' .. id) end if (self.CMDIDs[id] ~= nil) then Spring.Log(LOG_SECTION, LOG.ERROR, 'Gadget (' .. gadget.ghInfo.name .. ') ' .. 'tried to register a duplicated CMD_ID') Script.Kill('Duplicate CMD_ID code: ' .. id) end self.CMDIDs[id] = gadget end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- The call-in distribution routines -- function gadgetHandler:Shutdown() for _,g in r_ipairs(self.ShutdownList) do g:Shutdown() end end function gadgetHandler:GameSetup(state, ready, playerStates) local success, newReady = false, ready for _,g in r_ipairs(self.GameSetupList) do success, newReady = g:GameSetup(state, ready, playerStates) end return success, newReady end function gadgetHandler:GamePreload() for _,g in r_ipairs(self.GamePreloadList) do g:GamePreload() end end function gadgetHandler:GameStart() for _,g in r_ipairs(self.GameStartList) do g:GameStart() end end function gadgetHandler:GameOver(winningAllyTeams) for _,g in r_ipairs(self.GameOverList) do g:GameOver(winningAllyTeams) end end function gadgetHandler:GameFrame(frameNum) for _,g in r_ipairs(self.GameFrameList) do g:GameFrame(frameNum) end end function gadgetHandler:GamePaused(playerID, paused) for _,g in r_ipairs(self.GamePausedList) do g:GamePaused(playerID, paused) end end function gadgetHandler:GameProgress(serverFrameNum) for _,g in r_ipairs(self.GameProgressList) do g:GameProgress(serverFrameNum) end end function gadgetHandler:GameID(gameID) for _,g in r_ipairs(self.GameIDList) do g:GameID(gameID) end end function gadgetHandler:RecvFromSynced(...) if (actionHandler.RecvFromSynced(...)) then return end for _,g in r_ipairs(self.RecvFromSyncedList) do if (g:RecvFromSynced(...)) then return end end end function gadgetHandler:GotChatMsg(msg, player) if ((player == 0) and Spring.IsCheatingEnabled()) then local sp = '^%s*' -- start pattern local ep = '%s+(.*)' -- end pattern local s, e, match s, e, match = string.find(msg, sp..'togglegadget'..ep) if (match) then self:ToggleGadget(match) return true end s, e, match = string.find(msg, sp..'enablegadget'..ep) if (match) then self:EnableGadget(match) return true end s, e, match = string.find(msg, sp..'disablegadget'..ep) if (match) then self:DisableGadget(match) return true end end if (actionHandler.GotChatMsg(msg, player)) then return true end for _,g in r_ipairs(self.GotChatMsgList) do if (g:GotChatMsg(msg, player)) then return true end end return false end function gadgetHandler:RecvLuaMsg(msg, player) for _,g in r_ipairs(self.RecvLuaMsgList) do if (g:RecvLuaMsg(msg, player)) then return true end end return false end -------------------------------------------------------------------------------- -- -- Drawing call-ins -- function gadgetHandler:ViewResize(view) self.xViewSize = view.viewSizeX self.yViewSize = view.viewSizeY for _,g in r_ipairs(self.ViewResizeList) do g:ViewResize(self.xViewSize, self.yViewSize) end end -------------------------------------------------------------------------------- -- -- Team and player call-ins -- function gadgetHandler:TeamDied(teamID) for _,g in r_ipairs(self.TeamDiedList) do g:TeamDied(teamID) end end function gadgetHandler:TeamChanged(teamID) for _,g in r_ipairs(self.TeamChangedList) do g:TeamChanged(teamID) end end function gadgetHandler:SyncedPlayerChanged(playerID) for _,g in r_ipairs(self.SyncedPlayerChangedList) do g:SyncedPlayerChanged(playerID) end end function gadgetHandler:PlayerChanged(playerID) for _,g in r_ipairs(self.PlayerChangedList) do g:PlayerChanged(playerID) end end function gadgetHandler:PlayerAdded(playerID) for _,g in r_ipairs(self.PlayerAddedList) do g:PlayerAdded(playerID) end end function gadgetHandler:PlayerRemoved(playerID, reason) for _,g in r_ipairs(self.PlayerRemovedList) do g:PlayerRemoved(playerID, reason) end end -------------------------------------------------------------------------------- -- -- LuaRules Game call-ins -- function gadgetHandler:DrawUnit(unitID, drawMode) for _,g in r_ipairs(self.DrawUnitList) do if (g:DrawUnit(unitID, drawMode)) then return true end end return false end function gadgetHandler:DrawFeature(featureID, drawMode) for _,g in r_ipairs(self.DrawFeatureList) do if (g:DrawFeature(featureID, drawMode)) then return true end end return false end function gadgetHandler:DrawShield(unitID, weaponID, drawMode) for _,g in r_ipairs(self.DrawShieldList) do if (g:DrawShield(unitID, weaponID, drawMode)) then return true end end return false end function gadgetHandler:DrawProjectile(projectileID, drawMode) for _,g in r_ipairs(self.DrawProjectileList) do if (g:DrawProjectile(projectileID, drawMode)) then return true end end return false end function gadgetHandler:DrawMaterial(materialID, drawMode) for _,g in r_ipairs(self.DrawMaterialList) do if (g:DrawMaterial(materialID, drawMode)) then return true end end return false end function gadgetHandler:RecvSkirmishAIMessage(aiTeam, dataStr) for _,g in r_ipairs(self.RecvSkirmishAIMessageList) do local dataRet = g:RecvSkirmishAIMessage(aiTeam, dataStr) if (dataRet) then return dataRet end end end function gadgetHandler:CommandFallback(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag) for _,g in r_ipairs(self.CommandFallbackList) do local used, remove = g:CommandFallback(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag) if (used) then return remove end end return true -- remove the command end function gadgetHandler:AllowCommand( unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag, playerID, fromSynced, fromLua ) for _,g in r_ipairs(self.AllowCommandList) do if (not g:AllowCommand( unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag, playerID, fromSynced, fromLua) ) then return false end end return true end function gadgetHandler:AllowStartPosition(playerID, teamID, readyState, cx, cy, cz, rx, ry, rz) for _,g in r_ipairs(self.AllowStartPositionList) do if (not g:AllowStartPosition(playerID, teamID, readyState, cx, cy, cz, rx, ry, rz)) then return false end end return true end function gadgetHandler:AllowUnitCreation(unitDefID, builderID, builderTeam, x, y, z, facing) for _,g in r_ipairs(self.AllowUnitCreationList) do if (not g:AllowUnitCreation(unitDefID, builderID, builderTeam, x, y, z, facing)) then return false end end return true end function gadgetHandler:AllowUnitTransfer(unitID, unitDefID, oldTeam, newTeam, capture) for _,g in r_ipairs(self.AllowUnitTransferList) do if (not g:AllowUnitTransfer(unitID, unitDefID, oldTeam, newTeam, capture)) then return false end end return true end function gadgetHandler:AllowUnitBuildStep(builderID, builderTeam, unitID, unitDefID, part) for _,g in r_ipairs(self.AllowUnitBuildStepList) do if (not g:AllowUnitBuildStep(builderID, builderTeam, unitID, unitDefID, part)) then return false end end return true end function gadgetHandler:AllowUnitTransport( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam ) for _,g in r_ipairs(self.AllowUnitTransportList) do if (not g:AllowUnitTransport( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam )) then return false end end return true end function gadgetHandler:AllowUnitTransportLoad( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam, loadPosX, loadPosY, loadPosZ ) for _,g in r_ipairs(self.AllowUnitTransportLoadList) do if (not g:AllowUnitTransportLoad( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam, loadPosX, loadPosY, loadPosZ )) then return false end end return true end function gadgetHandler:AllowUnitTransportUnload( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam, unloadPosX, unloadPosY, unloadPosZ ) for _,g in r_ipairs(self.AllowUnitTransportUnloadList) do if (not g:AllowUnitTransportUnload( transporterID, transporterUnitDefID, transporterTeam, transporteeID, transporteeUnitDefID, transporteeTeam, unloadPosX, unloadPosY, unloadPosZ )) then return false end end return true end function gadgetHandler:AllowUnitCloak(unitID, enemyID) for _,g in r_ipairs(self.AllowUnitCloakList) do if (not g:AllowUnitCloak(unitID, enemyID)) then return false end end return true end function gadgetHandler:AllowUnitDecloak(unitID, objectID, weaponID) for _,g in r_ipairs(self.AllowUnitDecloakList) do if (not g:AllowUnitDecloak(unitID, objectID, weaponID)) then return false end end return true end function gadgetHandler:AllowUnitKamikaze(unitID, targetID) for _,g in r_ipairs(self.AllowUnitKamikazeList) do if (not g:AllowUnitKamikaze(unitID, targetID)) then return false end end return true end function gadgetHandler:AllowFeatureBuildStep(builderID, builderTeam, featureID, featureDefID, part) for _,g in r_ipairs(self.AllowFeatureBuildStepList) do if (not g:AllowFeatureBuildStep(builderID, builderTeam, featureID, featureDefID, part)) then return false end end return true end function gadgetHandler:AllowFeatureCreation(featureDefID, teamID, x, y, z) for _,g in r_ipairs(self.AllowFeatureCreationList) do if (not g:AllowFeatureCreation(featureDefID, teamID, x, y, z)) then return false end end return true end function gadgetHandler:AllowResourceLevel(teamID, res, level) for _,g in r_ipairs(self.AllowResourceLevelList) do if (not g:AllowResourceLevel(teamID, res, level)) then return false end end return true end function gadgetHandler:AllowResourceTransfer(oldTeamID, newTeamID, res, amount) for _,g in r_ipairs(self.AllowResourceTransferList) do if (not g:AllowResourceTransfer(oldTeamID, newTeamID, res, amount)) then return false end end return true end function gadgetHandler:AllowDirectUnitControl(unitID, unitDefID, unitTeam, playerID) for _,g in r_ipairs(self.AllowDirectUnitControlList) do if (not g:AllowDirectUnitControl(unitID, unitDefID, unitTeam, playerID)) then return false end end return true end function gadgetHandler:AllowBuilderHoldFire(unitID, unitDefID, action) for _,g in r_ipairs(self.AllowBuilderHoldFireList) do if (not g:AllowBuilderHoldFire(unitID, unitDefID, action)) then return false end end return true end function gadgetHandler:MoveCtrlNotify(unitID, unitDefID, unitTeam, data) local state = false for _,g in r_ipairs(self.MoveCtrlNotifyList) do if (g:MoveCtrlNotify(unitID, unitDefID, unitTeam, data)) then state = true end end return state end function gadgetHandler:TerraformComplete(unitID, unitDefID, unitTeam, buildUnitID, buildUnitDefID, buildUnitTeam) for _,g in r_ipairs(self.TerraformCompleteList) do if (g:TerraformComplete(unitID, unitDefID, unitTeam, buildUnitID, buildUnitDefID, buildUnitTeam)) then return true end end return false end function gadgetHandler:AllowWeaponTargetCheck(attackerID, attackerWeaponNum, attackerWeaponDefID) local ignore = true for _, g in r_ipairs(self.AllowWeaponTargetCheckList) do local allowCheck, ignoreCheck = g:AllowWeaponTargetCheck(attackerID, attackerWeaponNum, attackerWeaponDefID) if not ignoreCheck then ignore = false if not allowCheck then return 0 end end end return ((ignore and -1) or 1) end function gadgetHandler:AllowWeaponTarget(attackerID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority) local allowed = true local priority = 1.0 for _, g in r_ipairs(self.AllowWeaponTargetList) do local targetAllowed, targetPriority = g:AllowWeaponTarget(attackerID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority) if (not targetAllowed) then allowed = false; break end priority = math.max(priority, targetPriority) end return allowed, priority end function gadgetHandler:AllowWeaponInterceptTarget(interceptorUnitID, interceptorWeaponNum, interceptorTargetID) for _, g in r_ipairs(self.AllowWeaponInterceptTargetList) do if (not g:AllowWeaponInterceptTarget(interceptorUnitID, interceptorWeaponNum, interceptorTargetID)) then return false end end return true end -------------------------------------------------------------------------------- -- -- Unit call-ins -- function gadgetHandler:UnitCreated(unitID, unitDefID, unitTeam, builderID) for _,g in r_ipairs(self.UnitCreatedList) do g:UnitCreated(unitID, unitDefID, unitTeam, builderID) end end function gadgetHandler:UnitFinished(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitFinishedList) do g:UnitFinished(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitFromFactory( unitID, unitDefID, unitTeam, factID, factDefID, userOrders ) for _,g in r_ipairs(self.UnitFromFactoryList) do g:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders) end end function gadgetHandler:UnitReverseBuilt(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitReverseBuiltList) do g:UnitReverseBuilt(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitDestroyed( unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam ) for _,g in r_ipairs(self.UnitDestroyedList) do g:UnitDestroyed( unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam ) end end function gadgetHandler:RenderUnitDestroyed(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.RenderUnitDestroyedList) do g:RenderUnitDestroyed(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitExperience(unitID, unitDefID, unitTeam, experience, oldExperience) for _,g in r_ipairs(self.UnitExperienceList) do g:UnitExperience(unitID, unitDefID, unitTeam, experience, oldExperience) end end function gadgetHandler:UnitIdle(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitIdleList) do g:UnitIdle(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitCmdDone(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag) for _,g in r_ipairs(self.UnitCmdDoneList) do g:UnitCmdDone(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag) end end function gadgetHandler:UnitCommand( unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag, playerID, fromSynced, fromLua ) for _,g in r_ipairs(self.UnitCommandList) do g:UnitCommand( unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag, playerID, fromSynced, fromLua ) end end function gadgetHandler:UnitPreDamaged( unitID, unitDefID, unitTeam, damage, paralyzer, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) local retDamage = damage local retImpulse = 1.0 for _,g in r_ipairs(self.UnitPreDamagedList) do dmg, imp = g:UnitPreDamaged( unitID, unitDefID, unitTeam, retDamage, paralyzer, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) if (dmg ~= nil) then retDamage = dmg end if (imp ~= nil) then retImpulse = imp end end return retDamage, retImpulse end function gadgetHandler:UnitDamaged( unitID, unitDefID, unitTeam, damage, paralyzer, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) for _,g in r_ipairs(self.UnitDamagedList) do g:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam) end end function gadgetHandler:UnitStunned(unitID, unitDefID, unitTeam, stunned) for _,g in r_ipairs(self.UnitStunnedList) do g:UnitStunned(unitID, unitDefID, unitTeam, stunned) end end function gadgetHandler:UnitTaken(unitID, unitDefID, unitTeam, newTeam) for _,g in r_ipairs(self.UnitTakenList) do g:UnitTaken(unitID, unitDefID, unitTeam, newTeam) end end function gadgetHandler:UnitGiven(unitID, unitDefID, unitTeam, oldTeam) for _,g in r_ipairs(self.UnitGivenList) do g:UnitGiven(unitID, unitDefID, unitTeam, oldTeam) end end function gadgetHandler:UnitEnteredRadar(unitID, unitTeam, allyTeam, unitDefID) for _,g in r_ipairs(self.UnitEnteredRadarList) do g:UnitEnteredRadar(unitID, unitTeam, allyTeam, unitDefID) end end function gadgetHandler:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) for _,g in r_ipairs(self.UnitEnteredLosList) do g:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) end end function gadgetHandler:UnitLeftRadar(unitID, unitTeam, allyTeam, unitDefID) for _,g in r_ipairs(self.UnitLeftRadarList) do g:UnitLeftRadar(unitID, unitTeam, allyTeam, unitDefID) end end function gadgetHandler:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) for _,g in r_ipairs(self.UnitLeftLosList) do g:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) end end function gadgetHandler:UnitEnteredWater(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitEnteredWaterList) do g:UnitEnteredWater(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitLeftWater(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitLeftWaterList) do g:UnitLeftWater(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitEnteredAir(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitEnteredAirList) do g:UnitEnteredAir(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitLeftAir(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitLeftAirList) do g:UnitLeftAir(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitSeismicPing(x, y, z, strength, allyTeam, unitID, unitDefID) for _,g in r_ipairs(self.UnitSeismicPingList) do g:UnitSeismicPing(x, y, z, strength, allyTeam, unitID, unitDefID) end end function gadgetHandler:UnitLoaded(unitID, unitDefID, unitTeam, transportID, transportTeam) for _,g in r_ipairs(self.UnitLoadedList) do g:UnitLoaded(unitID, unitDefID, unitTeam, transportID, transportTeam) end end function gadgetHandler:UnitUnloaded(unitID, unitDefID, unitTeam, transportID, transportTeam) for _,g in r_ipairs(self.UnitUnloadedList) do g:UnitUnloaded(unitID, unitDefID, unitTeam, transportID, transportTeam) end end function gadgetHandler:UnitCloaked(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitCloakedList) do g:UnitCloaked(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitDecloaked(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitDecloakedList) do g:UnitDecloaked(unitID, unitDefID, unitTeam) end end function gadgetHandler:UnitUnitCollision(colliderID, collideeID) for _,g in r_ipairs(self.UnitUnitCollisionList) do if (g:UnitUnitCollision(colliderID, collideeID)) then return true end end return false end function gadgetHandler:UnitFeatureCollision(colliderID, collideeID) for _,g in r_ipairs(self.UnitFeatureCollisionList) do if (g:UnitFeatureCollision(colliderID, collideeID)) then return true end end return false end function gadgetHandler:StockpileChanged(unitID, unitDefID, unitTeam, weaponNum, oldCount, newCount) for _,g in r_ipairs(self.StockpileChangedList) do g:StockpileChanged(unitID, unitDefID, unitTeam, weaponNum, oldCount, newCount) end end function gadgetHandler:UnitHarvestStorageFull(unitID, unitDefID, unitTeam) for _,g in r_ipairs(self.UnitHarvestStorageFullList) do g:UnitHarvestStorageFull(unitID, unitDefID, unitTeam) end end -------------------------------------------------------------------------------- -- -- Feature call-ins -- function gadgetHandler:FeatureCreated(featureID, allyTeam) for _,g in r_ipairs(self.FeatureCreatedList) do g:FeatureCreated(featureID, allyTeam) end end function gadgetHandler:FeatureDestroyed(featureID, allyTeam) for _,g in r_ipairs(self.FeatureDestroyedList) do g:FeatureDestroyed(featureID, allyTeam) end end function gadgetHandler:FeatureDamaged( featureID, featureDefID, featureTeam, damage, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) for _,g in r_ipairs(self.FeatureDamagedList) do g:FeatureDamaged(featureID, featureDefID, featureTeam, damage, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam) end end function gadgetHandler:FeaturePreDamaged( featureID, featureDefID, featureTeam, damage, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) local retDamage = damage local retImpulse = 1.0 for _,g in r_ipairs(self.FeaturePreDamagedList) do dmg, imp = g:FeaturePreDamaged( featureID, featureDefID, featureTeam, retDamage, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam ) if (dmg ~= nil) then retDamage = dmg end if (imp ~= nil) then retImpulse = imp end end return retDamage, retImpulse end -------------------------------------------------------------------------------- -- -- Projectile call-ins -- function gadgetHandler:ProjectileCreated(proID, proOwnerID, proWeaponDefID) for _,g in r_ipairs(self.ProjectileCreatedList) do g:ProjectileCreated(proID, proOwnerID, proWeaponDefID) end end function gadgetHandler:ProjectileDestroyed(proID) for _,g in r_ipairs(self.ProjectileDestroyedList) do g:ProjectileDestroyed(proID) end end -------------------------------------------------------------------------------- -- -- Shield call-ins -- function gadgetHandler:ShieldPreDamaged( proID, proOwnerID, shieldEmitterWeapNum, shieldCarrierUnitID, bounceProj, beamEmitterWeapNum, beamEmitterUnitID, spx, spy, spz, hpx, hpy, hpz ) for _,g in r_ipairs(self.ShieldPreDamagedList) do -- first gadget to handle this consumes the event if (g:ShieldPreDamaged(proID, proOwnerID, shieldEmitterWeapNum, shieldCarrierUnitID, bounceProj, beamEmitterWeapNum, beamEmitterUnitID, spx, spy, spz, hpx, hpy, hpz)) then return true end end return false end -------------------------------------------------------------------------------- -- -- Misc call-ins -- function gadgetHandler:Explosion(weaponID, px, py, pz, ownerID, projectileID) -- "noGfx = noGfx or ..." short-circuits, so equivalent to this for _,g in r_ipairs(self.ExplosionList) do if (g:Explosion(weaponID, px, py, pz, ownerID, projectileID)) then return true end end return false end -------------------------------------------------------------------------------- -- -- Draw call-ins -- function gadgetHandler:Update() for _,g in r_ipairs(self.UpdateList) do g:Update() end end function gadgetHandler:DefaultCommand(type, id, cmd) for _,g in r_ipairs(self.DefaultCommandList) do local id = g:DefaultCommand(type, id, cmd) if (id) then return id end end end function gadgetHandler:CommandNotify(id, params, options) for _,g in r_ipairs(self.CommandNotifyList) do if (g:CommandNotify(id, params, options)) then return true end end return false end function gadgetHandler:DrawGenesis() for _,g in r_ipairs(self.DrawGenesisList) do g:DrawGenesis() end end function gadgetHandler:DrawWater() for _,g in r_ipairs(self.DrawWaterList) do g:DrawWater() end end function gadgetHandler:DrawSky() for _,g in r_ipairs(self.DrawSkyList) do g:DrawSky() end end function gadgetHandler:DrawSun() for _,g in r_ipairs(self.DrawSunList) do g:DrawSun() end end function gadgetHandler:DrawGrass() for _,g in r_ipairs(self.DrawGrassList) do g:DrawGrass() end end function gadgetHandler:DrawTrees() for _,g in r_ipairs(self.DrawTreesList) do g:DrawTrees() end end function gadgetHandler:DrawWorld() for _,g in r_ipairs(self.DrawWorldList) do g:DrawWorld() end end function gadgetHandler:DrawWorldPreUnit() for _,g in r_ipairs(self.DrawWorldPreUnitList) do g:DrawWorldPreUnit() end end function gadgetHandler:DrawWorldPreParticles() for _,g in r_ipairs(self.DrawWorldPreParticlesList) do g:DrawWorldPreParticles() end end function gadgetHandler:DrawWorldShadow() for _,g in r_ipairs(self.DrawWorldShadowList) do g:DrawWorldShadow() end end function gadgetHandler:DrawWorldReflection() for _,g in r_ipairs(self.DrawWorldReflectionList) do g:DrawWorldReflection() end end function gadgetHandler:DrawWorldRefraction() for _,g in r_ipairs(self.DrawWorldRefractionList) do g:DrawWorldRefraction() end end function gadgetHandler:DrawGroundPreForward() for _,g in r_ipairs(self.DrawGroundPreForwardList) do g:DrawGroundPreForward() end end function gadgetHandler:DrawGroundPostForward() for _,g in r_ipairs(self.DrawGroundPostForwardList) do g:DrawGroundPostForward() end end function gadgetHandler:DrawGroundPreDeferred() for _,g in r_ipairs(self.DrawGroundPreDeferredList) do g:DrawGroundPreDeferred() end end function gadgetHandler:DrawGroundPostDeferred() for _,g in r_ipairs(self.DrawGroundPostDeferredList) do g:DrawGroundPostDeferred() end end function gadgetHandler:DrawUnitsPostDeferred() for _,g in r_ipairs(self.DrawUnitsPostDeferredList) do g:DrawUnitsPostDeferred() end end function gadgetHandler:DrawFeaturesPostDeferred() for _,g in r_ipairs(self.DrawFeaturesPostDeferredList) do g:DrawFeaturesPostDeferred() end end function gadgetHandler:DrawScreenEffects(vsx, vsy) for _,g in r_ipairs(self.DrawScreenEffectsList) do g:DrawScreenEffects(vsx, vsy) end end function gadgetHandler:DrawScreenPost(vsx, vsy) for _,g in r_ipairs(self.DrawScreenPostList) do g:DrawScreenPost(vsx, vsy) end end function gadgetHandler:DrawScreen(vsx, vsy) for _,g in r_ipairs(self.DrawScreenList) do g:DrawScreen(vsx, vsy) end end function gadgetHandler:DrawInMiniMap(mmsx, mmsy) for _,g in r_ipairs(self.DrawInMiniMapList) do g:DrawInMiniMap(mmsx, mmsy) end end function gadgetHandler:SunChanged() for _,g in r_ipairs(self.SunChangedList) do g:SunChanged() end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:KeyPress(key, mods, isRepeat, label, unicode) for _,g in r_ipairs(self.KeyPressList) do if (g:KeyPress(key, mods, isRepeat, label, unicode)) then return true end end return false end function gadgetHandler:KeyRelease(key, mods, label, unicode) for _,g in r_ipairs(self.KeyReleaseList) do if (g:KeyRelease(key, mods, label, unicode)) then return true end end return false end function gadgetHandler:TextInput(utf8, ...) if (self.tweakMode) then return true end for _,g in r_ipairs(self.TextInputList) do if (g:TextInput(utf8, ...)) then return true end end return false end function gadgetHandler:MousePress(x, y, button) local mo = self.mouseOwner if (mo) then mo:MousePress(x, y, button) return true -- already have an active press end for _,g in r_ipairs(self.MousePressList) do if (g:MousePress(x, y, button)) then self.mouseOwner = g return true end end return false end function gadgetHandler:MouseMove(x, y, dx, dy, button) local mo = self.mouseOwner if (mo and mo.MouseMove) then return mo:MouseMove(x, y, dx, dy, button) end end function gadgetHandler:MouseRelease(x, y, button) local mo = self.mouseOwner local mx, my, lmb, mmb, rmb = Spring.GetMouseState() if (not (lmb or mmb or rmb)) then self.mouseOwner = nil end if (mo and mo.MouseRelease) then return mo:MouseRelease(x, y, button) end return -1 end function gadgetHandler:MouseWheel(up, value) for _,g in r_ipairs(self.MouseWheelList) do if (g:MouseWheel(up, value)) then return true end end return false end function gadgetHandler:IsAbove(x, y) for _,g in r_ipairs(self.IsAboveList) do if (g:IsAbove(x, y)) then return true end end return false end function gadgetHandler:GetTooltip(x, y) for _,g in r_ipairs(self.GetTooltipList) do if (g:IsAbove(x, y)) then local tip = g:GetTooltip(x, y) if (string.len(tip) > 0) then return tip end end end return '' end function gadgetHandler:MapDrawCmd(playerID, cmdType, px, py, pz, labelText) for _,g in r_ipairs(self.MapDrawCmdList) do if (g:MapDrawCmd(playerID, cmdType, px, py, pz, labelText)) then return true end end return false end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:DownloadStarted(id) for _,g in r_ipairs(self.DownloadStartedList) do g:DownloadStarted(id) end end function gadgetHandler:DownloadQueued(id) for _,g in r_ipairs(self.DownloadQueuedList) do g:DownloadQueued(id) end end function gadgetHandler:DownloadFinished(id) for _,g in r_ipairs(self.DownloadFinishedList) do g:DownloadFinished(id) end end function gadgetHandler:DownloadFailed(id, errorid) for _,g in r_ipairs(self.DownloadFailedList) do g:DownloadFailed(id, errorid) end end function gadgetHandler:DownloadProgress(id, downloaded, total) for _,g in r_ipairs(self.DownloadProgressList) do g:DownloadProgress(id, downloaded, total) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:Save(zip) for _,g in r_ipairs(self.SaveList) do g:Save(zip) end end function gadgetHandler:Load(zip) for _,g in r_ipairs(self.LoadList) do g:Load(zip) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadgetHandler:Pong(pingTag, pktSendTime, pktRecvTime) for _,g in r_ipairs(self.PongList) do g:Pong(pingTag, pktSendTime, pktRecvTime) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- gadgetHandler:Initialize() -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
0
0.894467
1
0.894467
game-dev
MEDIA
0.599003
game-dev
0.955371
1
0.955371
FrictionalGames/PenumbraOverture
5,853
GameObject.h
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of Penumbra Overture. * * Penumbra Overture 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. * * Penumbra Overture 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 Penumbra Overture. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GAME_GAME_OBJECT_H #define GAME_GAME_OBJECT_H #include "StdAfx.h" #include "GameEntity.h" using namespace hpl; //----------------------------------------- class iGameEnemy; //----------------------------------------- class cGameObject_SaveData : public iGameEntity_SaveData { kSerializableClassInit(cGameObject_SaveData); public: eObjectInteractMode mInteractMode; iGameEntity* CreateEntity(); }; //------------------------------------------ class cGameObject; class cGameObjectBodyCallback : public iPhysicsBodyCallback { public: cGameObjectBodyCallback(cInit *apInit, cGameObject *apObject); bool OnBeginCollision(iPhysicsBody *apBody, iPhysicsBody *apCollideBody); void OnCollide(iPhysicsBody *apBody, iPhysicsBody *apCollideBody,cPhysicsContactData* apContactData); cInit *mpInit; cGameObject *mpObject; }; //-------------------------------------- class cObjectDisappearProperties { public: cObjectDisappearProperties(){ mbActive = false; } bool mbActive; float mfMinTime; float mfMaxTime; float mfTime; float mfMinDistance; float mfMinCloseDistance; }; //-------------------------------------- class cObjectBreakProperties { public: cObjectBreakProperties(){ mbActive = false; } bool mbActive; tString msEntity; tString msSound; tString msPS; float mfMinImpulse; float mfMinNormalSpeed; float mfMinPlayerImpulse; float mfCenterForce; bool mbExplosion; float mfExpl_Radius; float mfExpl_MinDamage; float mfExpl_MaxDamage; float mfExpl_MinForce; float mfExpl_MaxForce; float mfExpl_MaxImpulse; float mfExpl_MinMass; int mlExpl_Strength; bool mbLightFlash; cColor mLight_Color; float mfLight_Radius; float mfLight_AddTime; float mfLight_NegTime; cVector3f mvLight_Offset; bool mbEarRing; float mfEarRing_MaxDist; float mfEarRing_Time; }; //-------------------------------------- class cObjectAttractProperties { public: cObjectAttractProperties(){ mbActive = false; } bool mbActive; float mfDistance; tStringVec mvSubtypes; bool mbIsEaten; float mfEatLength; }; //-------------------------------------- class cObjectDamageProperties { public: cObjectDamageProperties(){ mbActive = false; } bool mbActive; float mfMinLinearDamageSpeed; float mfMinAngularDamageSpeed; float mfMaxLinearDamageSpeed; float mfMaxAngularDamageSpeed; float mfMinDamage; float mfMaxDamage; int mlDamageStrength; }; //-------------------------------------- class cGameObject : public iGameEntity { #ifdef __GNUC__ typedef iGameEntity __super; #endif friend class cEntityLoader_GameObject; friend class cGameObjectBodyCallback; public: cGameObject(cInit *apInit,const tString& asName); ~cGameObject(void); void OnPlayerInteract(); void OnPlayerPick(); bool IsSaved(){ if(mDisappearProps.mbActive) return false; return mbIsSaved; } void Update(float afTimeStep); void BreakAction(); void OnDeath(float afDamage); bool IsBreakable(){ return mBreakProps.mbActive;} void OnPlayerGravityCollide(iCharacterBody *apCharBody, cCollideData *apCollideData); void SetInteractMode(eObjectInteractMode aInteractMode); eObjectInteractMode GetInteractMode(){ return mInteractMode;} void SetupBreakObject(); bool IsDestroyable(){ return mbDestroyable;} float GetDestroyStrength(){ return mfDestroyStrength;} const tString& GetDestroySound(){ return msDestoySound;} void SetupForceOffset(); //SaveObject implementation iGameEntity_SaveData* CreateSaveData(); void SaveToSaveData(iGameEntity_SaveData *apSaveData); void LoadFromSaveData(iGameEntity_SaveData *apSaveData); private: void GrabObject(); void MoveObject(); float GetMoveDist(); void PushObject(); float GetPushDist(); void UpdateAttraction(float afTimeStep); std::set<iGameEnemy*> m_setAttractedEnemies; iGameEnemy* mpCurrentAttraction; float mfAttractCount; eObjectInteractMode mInteractMode; float mfForwardUpMul; float mfForwardRightMul; float mfUpMul; float mfRightMul; bool mbPickAtPoint; bool mbRotateWithPlayer; bool mbUseNormalMass; float mfGrabMassMul; bool mbCanBeThrown; bool mbCanBePulled; bool mbIsMover; bool mbDestroyable; float mfDestroyStrength; tString msDestoySound; bool mbForceLightOffset; cVector3f mvLightOffset; tMatrixfVec mvLightLocalOffsets; float mfHapticTorqueMul; float mfCloseToSameCount; cObjectBreakProperties mBreakProps; cObjectDisappearProperties mDisappearProps; cObjectAttractProperties mAttractProps; cObjectDamageProperties mDamageProps; cGameObjectBodyCallback *mpBodyCallback; }; //-------------------------------------- class cEntityLoader_GameObject : public cEntityLoader_Object { public: cEntityLoader_GameObject(const tString &asName, cInit *apInit); ~cEntityLoader_GameObject(); static eObjectInteractMode ToInteractMode(const char* apString); private: void BeforeLoad(TiXmlElement *apRootElem, const cMatrixf &a_mtxTransform,cWorld3D *apWorld); void AfterLoad(TiXmlElement *apRootElem, const cMatrixf &a_mtxTransform,cWorld3D *apWorld); cInit *mpInit; }; #endif // GAME_GAME_OBJECT_H
0
0.795359
1
0.795359
game-dev
MEDIA
0.965861
game-dev
0.554719
1
0.554719
notphage/fatality.win-CS2
20,809
cs2_internal/src/lua/api/entity.cpp
#include "macros.h" #include "lua/state.h" #include "lua/api_def.h" #include "lua/helpers.h" //int lua::api_def::entities::index( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( s.is_number( 2 ) ) // { // const auto key = s.get_integer( 2 ); // // auto ent = interfaces::entity_list()->get_client_entity( key ); // // if ( !ent ) // return 0; // // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // // return 1; // } // // return 0; //} // //int lua::api_def::entity::index(lua_State* l) //{ // runtime_state s(l); // if (!interfaces::engine()->IsInGame()) // return 0; // // if (!s.is_string(2)) // return 0; // // switch (fnv1a_rt(s.get_string(2))) // { // case FNV1A("get_index"): // s.push(get_index); // return 1; // case FNV1A("is_valid"): // s.push(is_valid); // return 1; // case FNV1A("is_alive"): // s.push(is_alive); // return 1; // case FNV1A("is_dormant"): // s.push(is_dormant); // return 1; // case FNV1A("is_player"): // s.push(is_player); // return 1; // case FNV1A("is_enemy"): // s.push(is_enemy); // return 1; // case FNV1A("get_class"): // s.push(get_class); // return 1; // case FNV1A("get_prop"): // s.push(get_prop); // return 1; // case FNV1A("set_prop"): // s.push(set_prop); // return 1; // case FNV1A("get_hitbox_position"): // s.push(get_hitbox_position); // return 1; // case FNV1A("get_eye_position"): // s.push(get_eye_position); // return 1; // case FNV1A("get_player_info"): // s.push(get_player_info); // return 1; // case FNV1A("get_move_type"): // s.push(get_move_type); // return 1; // case FNV1A("get_esp_alpha"): // s.push(get_esp_alpha); // return 1; // case FNV1A("get_ptr"): // s.push(get_ptr); // return 1; // case FNV1A("get_bbox"): // s.push(get_bbox); // return 1; // case FNV1A("get_weapon"): // s.push(get_weapon); // return 1; // } // // auto ent = *reinterpret_cast<C_BaseEntity**>(s.get_user_data(1)); // if (!ent || !is_sane(ent)) // return 0; // // const auto client_class = ent->GetClientClass(); // if (fnv1a_rt(client_class->m_pNetworkName) == FNV1A("CCSGameRulesProxy")) // ent = (C_BaseEntity*)interfaces::game_rules_proxy().game_rules; // // const auto prop_name = s.get_string(2); // const auto var = helpers::get_netvar(prop_name, client_class); // if (!var.offset) // return 0; // // if (var.is_array) // { // helpers::lua_var v{ent, var}; // s.create_user_object(XOR_STR("csgo.netvar"), &v); // return 1; // } // // return helpers::state_get_prop({ ent, var }, s); //} // //int lua::api_def::entity::get_ptr(lua_State* l) //{ // runtime_state s(l); // if (!interfaces::engine()->IsInGame()) // return 0; // // const auto ent = extract_type<C_CSPlayer>(s, XOR_STR("usage: ent:get_esp_alpha()")); // if (!ent || !is_sane(ent) || !ent->is_player()) // return 0; // // s.push((int)ent); // return 1; //} // //int lua::api_def::entity::new_index(lua_State* l) //{ // runtime_state s(l); // if (!interfaces::engine()->IsInGame()) // return 0; // // if (!s.is_string(2)) // return 0; // // auto ent = *reinterpret_cast<C_BaseEntity**>(s.get_user_data(1)); // if (!ent || !is_sane(ent)) // return 0; // // const auto client_class = ent->GetClientClass(); // if (fnv1a_rt(client_class->m_pNetworkName) == FNV1A("CCSGameRulesProxy")) // ent = (C_BaseEntity*)interfaces::game_rules_proxy().game_rules; // // const auto prop_name = s.get_string(2); // const auto var = helpers::get_netvar(prop_name, client_class); // if (!var.offset || var.is_array) // return 0; // // helpers::state_set_prop({ ent, var }, s, 3); // return 0; //} // //int lua::api_def::entities::get_entity( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_number( 1 ) ) // { // s.error( XOR_STR( "usage: entities.get_entity(number)" ) ); // return 0; // } // // auto ent = interfaces::entity_list()->get_client_entity( s.get_integer( 1 ) ); // // if ( !ent ) // return 0; // // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // // return 1; //} // //int lua::api_def::entities::get_entity_from_handle( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_number( 1 ) ) // { // s.error( XOR_STR( "usage: entities.get_entity_from_handle(number)" ) ); // return 0; // } // // auto ent = interfaces::entity_list()->get_client_entity_from_handle( s.get_integer( 1 ) ); // // if ( !ent ) // return 0; // // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // // return 1; //} // //int lua::api_def::entities::for_each( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_function( 1 ) ) // { // s.error( XOR_STR( "usage: entities.for_each(function)" ) ); // return 0; // } // // const auto me = api.find_by_state( l ); // if ( !me ) // { // s.error( XOR_STR( "FATAL: could not find the script. Did it escape the sandbox?" ) ); // return 0; // } // // const auto func_ref = s.registry_add(); // // interfaces::entity_list()->for_each( [&] ( C_BaseEntity* ent ) // { // s.registry_get( func_ref ); // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // if ( !s.call( 1, 0 ) ) // { // me->did_error = true; // lua::helpers::error( XOR_STR( "runtime_error" ), s.get_last_error_description().c_str() ); // if ( const auto f = api.find_script_file( me->id ); f.has_value() ) // f->get().should_unload = true; // // return; // } // } ); // // s.registry_remove( func_ref ); // // return 0; //} // //int lua::api_def::entities::for_each_z( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_function( 1 ) ) // { // s.error( XOR_STR( "usage: entities.for_each_z(function)" ) ); // return 0; // } // // const auto me = api.find_by_state( l ); // if ( !me ) // { // s.error( XOR_STR( "FATAL: could not find the script. Did it escape the sandbox?" ) ); // return 0; // } // // const auto func_ref = s.registry_add(); // // interfaces::entity_list()->for_each_z( [&] ( C_BaseEntity* ent ) // { // s.registry_get( func_ref ); // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // if ( !s.call( 1, 0 ) ) // { // me->did_error = true; // lua::helpers::error( XOR_STR( "runtime_error" ), s.get_last_error_description().c_str() ); // if ( const auto f = api.find_script_file( me->id ); f.has_value() ) // f->get().should_unload = true; // // return; // } // } ); // // s.registry_remove( func_ref ); // // return 0; //} // //int lua::api_def::entities::for_each_player( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_function( 1 ) ) // { // s.error( XOR_STR( "usage: entities.for_each_player(function)" ) ); // return 0; // } // // const auto me = api.find_by_state( l ); // if ( !me ) // { // s.error( XOR_STR( "FATAL: could not find the script. Did it escape the sandbox?" ) ); // return 0; // } // // const auto func_ref = s.registry_add(); // // interfaces::entity_list()->for_each_player( [&] ( C_CSPlayer* ent ) // { // s.registry_get( func_ref ); // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // // if ( !s.call( 1, 0 ) ) // { // me->did_error = true; // lua::helpers::error( XOR_STR( "runtime_error" ), s.get_last_error_description().c_str() ); // if ( const auto f = api.find_script_file( me->id ); f.has_value() ) // f->get().should_unload = true; // // return; // } // } ); // // s.registry_remove( func_ref ); // // return 0; //} // //int lua::api_def::entities::for_each_player_z( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.is_function( 1 ) ) // { // s.error( XOR_STR( "usage: entities.for_each_player_z(function)" ) ); // return 0; // } // // auto func_ref = s.registry_add(); // // interfaces::entity_list()->for_each_player_z( [&] ( C_CSPlayer* ent ) // { // s.registry_get( func_ref ); // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), ent ); // // if ( !s.call( 1, 0 ) ) // s.error( s.get_last_error_description() ); // } ); // // s.registry_remove( func_ref ); // // return 0; //} // //bool lua::api_def::entity::is_sane( C_BaseEntity* ent ) //{ // return std::find( interfaces::entity_list()->begin(), interfaces::entity_list()->end(), ent ) != interfaces::entity_list()->end(); //} // //int lua::api_def::entity::get_index( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_BaseEntity>( s, XOR_STR( "usage: ent:get_index()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->EntIndex() ); // return 1; //} // //int lua::api_def::entity::is_valid( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:is_valid()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->is_player() && ent->is_valid() ); // // return 1; //} // //int lua::api_def::entity::is_alive( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:is_alive()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->is_player() && ent->get_alive() ); // // return 1; //} // //int lua::api_def::entity::is_dormant( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:is_dormant()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->IsDormant() ); // // return 1; //} // //int lua::api_def::entity::is_player( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:is_player()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->is_player() ); // // return 1; //} // //int lua::api_def::entity::is_enemy( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:is_enemy()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->is_player() && ent->is_enemy() ); // // return 1; //} // //int lua::api_def::entity::get_class( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_class()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // s.push( ent->GetClientClass()->m_pNetworkName ); // // return 1; //} // //int lua::api_def::entity::get_hitbox_position( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.check_arguments( { // { ltd::user_data }, // { ltd::number } } ) ) // { // s.error( XOR_STR( "usage: ent:get_hitbox_position(number)" ) ); // return 0; // } // // const auto ent = *reinterpret_cast< C_CSPlayer** >( s.get_user_data( 1 ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // // const auto hitbox_pos = ent->get_hitbox_pos( s.get_integer( 2 ) ); // if ( hitbox_pos.IsZero() || !hitbox_pos.IsValid() ) // return 0; // // s.push( hitbox_pos.x ); // s.push( hitbox_pos.y ); // s.push( hitbox_pos.z ); // // return 3; //} // //int lua::api_def::entity::get_eye_position( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_eye_position()" ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // const auto eye_pos = ent->get_eye_pos(); // // s.push( eye_pos.x ); // s.push( eye_pos.y ); // s.push( eye_pos.z ); // // return 3; //} // //int lua::api_def::entity::get_player_info( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_player_info()" ) ); // // if ( !ent || !is_sane( ent ) || !ent->is_player() ) // return 0; // // const auto player_info = ent->get_player_info(); // // s.create_table(); // { // s.set_field( XOR( "name" ), player_info.name ); // s.set_field( XOR( "user_id" ), player_info.userid ); // s.set_field( XOR( "steam_id" ), player_info.guid ); // s.set_field( XOR( "steam_id64" ), std::to_string( player_info.xuid ).c_str() ); // s.set_field( XOR( "steam_id64_low" ), player_info.xuidlow ); // s.set_field( XOR( "steam_id64_high" ), player_info.xuidhigh ); // } // // return 1; //} // //int lua::api_def::entity::get_prop( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.check_arguments( { // { ltd::user_data }, // { ltd::string }, // { ltd::number, true } } ) ) // { // s.error( XOR_STR( "usage: ent:get_prop(name, index (optional))" ) ); // return 0; // } // // auto index = 0; // // // 3 IS 3! // if ( s.is_number( 3 ) ) // index = s.get_integer( 3 ); // // auto ent = *reinterpret_cast< C_BaseEntity** >( s.get_user_data( 1 ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // const auto client_class = ent->GetClientClass(); // if ( fnv1a_rt( client_class->m_pNetworkName ) == FNV1A( "CCSGameRulesProxy" ) ) // ent = interfaces::game_rules_proxy() ? reinterpret_cast< C_BaseEntity* >( *interfaces::game_rules_proxy() ) : nullptr; // // auto prop_name = std::string( s.get_string( 2 ) ); // const auto name_hash = fnv1a_rt( prop_name.c_str() ); // // const auto ref = helpers::get_netvar( prop_name.c_str(), client_class ); // // if ( !ref.offset ) // return 0; // // const auto addr = uint32_t( ent ) + ref.offset; // switch ( ref.type ) // { // default: // case send_prop_type::dpt_int: // if ( prop_name.find( XOR_STR( "m_b" ) ) != std::string::npos ) // s.push( reinterpret_cast< bool* >( addr )[ index ] ); // else if ( prop_name.find( XOR_STR( "m_f" ) ) != std::string::npos && name_hash != FNV1A( "m_fFlags" ) ) // s.push( reinterpret_cast< float* >( addr )[ index ] ); // else if ( prop_name.find( XOR_STR( "m_v" ) ) != std::string::npos || // prop_name.find( XOR_STR( "m_ang" ) ) != std::string::npos ) // { // s.push( reinterpret_cast< float* >( addr )[ index ] ); // s.push( reinterpret_cast< float* >( addr )[ index + 1 ] ); // s.push( reinterpret_cast< float* >( addr )[ index + 2 ] ); // return 3; // } // else if ( prop_name.find( XOR_STR( "m_psz" ) ) != std::string::npos || // prop_name.find( XOR_STR( "m_sz" ) ) != std::string::npos ) // s.push( reinterpret_cast< const char* >( addr ) ); // else // { // if ( name_hash == FNV1A( "m_iItemDefinitionIndex" ) ) // s.push( reinterpret_cast< short* >( addr )[ index ] ); // else // s.push( reinterpret_cast< int* >( addr )[ index ] ); // } // // return 1; // case send_prop_type::dpt_float: // s.push( reinterpret_cast< float* >( addr )[ index ] ); // return 1; // case send_prop_type::dpt_vector: // s.push( reinterpret_cast< float* >( addr )[ index * 3 ] ); // s.push( reinterpret_cast< float* >( addr )[ index * 3 + 1 ] ); // s.push( reinterpret_cast< float* >( addr )[ index * 3 + 2 ] ); // return 3; // case send_prop_type::dpt_vectorxy: // s.push( reinterpret_cast< float* >( addr )[ index * 2 ] ); // s.push( reinterpret_cast< float* >( addr )[ index * 2 + 1 ] ); // return 2; // case send_prop_type::dpt_string: // s.push( reinterpret_cast< const char* >( addr ) ); // return 1; // case send_prop_type::dpt_int64: // { // const auto var = reinterpret_cast< int64_t* >( addr )[ index ]; // s.push( std::to_string( var ).c_str() ); // return 1; // } // } //} // //int lua::api_def::entity::set_prop( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // if ( !s.check_arguments( { // { ltd::user_data }, // { ltd::string }, // { ltd::number } }, true ) ) // { // s.error( XOR_STR( "usage: ent:set_prop(name, index, value(s))" ) ); // return 0; // } // // auto index = 0; // // // 3 IS 3! // if ( s.is_number( 3 ) ) // index = s.get_integer( 3 ); // // const auto ent = *reinterpret_cast< C_BaseEntity** >( s.get_user_data( 1 ) ); // // if ( !ent || !is_sane( ent ) ) // return 0; // // const auto client_class = ent->GetClientClass(); // // auto prop_name = std::string( s.get_string( 2 ) ); // // const auto ref = helpers::get_netvar( prop_name.c_str(), client_class ); // // if ( !ref.offset ) // return 0; // // const auto addr = uint32_t( ent ) + ref.offset; // // switch ( ref.type ) // { // default: // case send_prop_type::dpt_int: // if ( s.is_number( 4 ) ) // reinterpret_cast< int* >( addr )[ index ] = s.get_integer( 4 ); // else if ( s.is_boolean( 4 ) ) // reinterpret_cast< bool* >( addr )[ index ] = s.get_boolean( 4 ); // break; // case send_prop_type::dpt_float: // if ( s.is_number( 4 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 4 ); // break; // case send_prop_type::dpt_vector: // if ( s.is_number( 4 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 4 ); // if ( s.is_number( 5 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 5 ); // if ( s.is_number( 6 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 6 ); // break; // case send_prop_type::dpt_vectorxy: // if ( s.is_number( 4 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 4 ); // if ( s.is_number( 5 ) ) // reinterpret_cast< float* >( addr )[ index ] = s.get_float( 5 ); // break; // case send_prop_type::dpt_string: // case send_prop_type::dpt_int64: // s.error( "Not implemented" ); // break; // } // return 0; //} // //int lua::api_def::entity::get_move_type( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_move_type()" ) ); // // if ( !ent || !is_sane( ent ) || !ent->is_player() ) // return 0; // // s.push( ent->get_move_type() ); // // return 1; //} // //int lua::api_def::entity::get_bbox( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_bbox() x1, y1, x2, y2" ) ); // // if ( !ent || !is_sane( ent ) || !ent->is_player() ) // return 0; // // const auto& info = visuals::players[ ent->EntIndex() ]; // if ( !info.valid ) // return 0; // // const auto tl = ( info.top.x - info.width ); // const auto br = ( info.bot.x + info.width ); // // s.push( tl ); // s.push( info.top.y ); // s.push( br ); // s.push( info.bot.y ); // return 4; //} // //int lua::api_def::entity::get_weapon( lua_State* l ) //{ // runtime_state s( l ); // // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_weapon(): entity" ) ); // // if ( !ent || !is_sane( ent ) || !ent->is_player() ) // return 0; // // const auto weapon = globals::get_weapon( ent->get_active_weapon() ); // if ( !weapon || !is_sane( weapon ) ) // return 0; // // s.create_user_object_ptr( XOR_STR( "csgo.entity" ), weapon ); // return 1; //} // //int lua::api_def::entity::get_esp_alpha( lua_State* l ) //{ // runtime_state s( l ); // if ( !interfaces::engine()->IsInGame() ) // return 0; // // const auto ent = extract_type<C_CSPlayer>( s, XOR_STR( "usage: ent:get_esp_alpha()" ) ); // if ( !ent || !is_sane( ent ) || !ent->is_player() ) // return 0; // // s.push( visuals::players[ ent->EntIndex() ].alpha ); // return 1; //} // //namespace lua::api_def::net_prop //{ // int index(lua_State* l) // { // runtime_state s(l); // // const auto v = s.user_data<helpers::lua_var>(1); // if (!entity::is_sane(v.ent) || !v.v.is_array) // return 0; // // helpers::lua_var vr{v}; // vr.v.is_array = false; // vr.v.offset += 4 * s.get_integer(2); // return helpers::state_get_prop(vr, s); // } // // int new_index(lua_State* l) // { // runtime_state s(l); // // const auto v = s.user_data<helpers::lua_var>(1); // if (!entity::is_sane(v.ent) || !v.v.is_array) // return 0; // // helpers::lua_var vr{v}; // vr.v.is_array = false; // vr.v.offset += 4 * s.get_integer(2); // helpers::state_set_prop(vr, s, 3); // return 0; // } //} // namespace lua::api_def::net_prop
0
0.806212
1
0.806212
game-dev
MEDIA
0.908671
game-dev
0.781753
1
0.781753
huayuxingtguiyujing/Wargame
6,454
Assets/Script/GamePlay/Network/PlayScene/PoliticNetworkLoader.cs
using System.Collections; using System.Collections.Generic; using Unity.Netcode; using UnityEngine; using WarGame_True.Infrastructure.Map.Provinces; using WarGame_True.Infrastructure.NetworkPackage; namespace WarGame_True.GamePlay.Politic { public class PoliticNetworkLoader : NetworkBehaviour { [Header("")] [SerializeField] PoliticLoader politicLoader; [SerializeField] GameObject networkFactionPrefab; // old method: use a middle layer(networkfaction) to hanlder change in faction // but it's not convenient //public NetworkList<NetworkObjectReference> networkFactions = new NetworkList<NetworkObjectReference>(); public NetworkVariable<bool> dirtySign = new NetworkVariable<bool>(false); // NOTICE: ʼPoliticLoader public void InitPoliticNetwork() { //if (NetworkManager.Singleton.IsServer) { // //// ݵǰѡ networkobj, networkObj ָӦfaction // //for(int i = 0; i < politicLoader.BookMarkFactions.Count; i++) { // // GameObject networkFactionObj = Instantiate(networkFactionPrefab); // // // networkObject // // NetworkObject networkObject = networkFactionObj.GetComponent<NetworkObject>(); // // networkObject.Spawn(); // // networkFactions.Add(networkObject); // //} //} foreach (var faction in politicLoader.BookMarkFactions) { // Factionͬ¼ faction.ChangeLevelEvent += ChangeLevelEvent; } // NOTICE: ضǷnetworkfactionٵͻִеһ // еĿͻ ͬnetworkfaction faction //SyncNetworkFactions(); } /* networkFactions ط ɾ /// <summary> /// ͬпͻ˵ NetworkFaction /// </summary> /// <param name="rpcParams"></param> public void SyncNetworkFactions() { Debug.Log("SyncFaction: " + NetworkManager.LocalClientId); // Ϊÿصfaction networkFaction, ʼ Debug.Log("networkFactions num: " + networkFactions.Count); foreach (var localFaction in politicLoader.BookMarkFactions) { NetworkFaction networkFaction = GetAvailableNetworkFaction(); if (networkFaction != null) { //Debug.Log("Faction: " + localFaction.FactionInfo.FactionTag); networkFaction.SetNetworkFaction(localFaction, this); } else { //Debug.Log("ûƥnetworkFaction"); } } DebugAllNetworkFactions(); } /// <summary> /// ȡǰ ճNetworkFaction /// </summary> private NetworkFaction GetAvailableNetworkFaction() { // ERROR: ǰڿͻˣnetworkFactionsǿյ foreach (NetworkObject networkObject in networkFactions) { NetworkFaction networkFaction = networkObject.gameObject.GetComponent<NetworkFaction>(); if (!networkFaction.ExistFaction) { return networkFaction; } } return null; } private void DebugAllNetworkFactions() { foreach (NetworkObject networkObject in networkFactions) { NetworkFaction networkFaction = networkObject.gameObject.GetComponent<NetworkFaction>(); Debug.Log(networkFaction.NetworkFactionTag); } } public NetworkFaction GetNetworkFactionByTag(string tag) { foreach (NetworkObject networkObject in networkFactions) { NetworkFaction networkFaction = networkObject.gameObject.GetComponent<NetworkFaction>(); if (networkFaction.ExistFaction && networkFaction.NetworkFactionTag == tag) { return networkFaction; } } return null; } public Faction GetFactionByTag(string tag) { NetworkFaction networkFaction = GetNetworkFactionByTag(tag); if(networkFaction != null) { return networkFaction.faction; } return null; } */ /// <summary> /// ˰ʡάõĻصһҵıͬͻ /// </summary> private void ChangeLevelEvent(string factionTagStr, TaxLevel taxLevel, ExpropriateGrainLevel grainLevel, MaintenanceLevel maintenanceLevel) { NetworkString factionTag = factionTagStr; ChangeLevelServerRpc(factionTag, taxLevel, grainLevel, maintenanceLevel); } [ServerRpc(RequireOwnership = false)] private void ChangeLevelServerRpc(NetworkString factionTag, TaxLevel taxLevel, ExpropriateGrainLevel grainLevel, MaintenanceLevel maintenanceLevel, ServerRpcParams rpcParams = default) { Debug.Log($"{factionTag.ToString()} , ˮƽ: TaxLevel-${taxLevel},GrainLevel-${grainLevel},MaintLevel-${maintenanceLevel}"); ulong changeClientId = rpcParams.Receive.SenderClientId; // ֪ͨзи ChangeLevelClientRpc(changeClientId, factionTag, taxLevel, grainLevel, maintenanceLevel); // ֤ɹ: ͬnetworkObjϵıǿе dirtySign.Value = true; } [ClientRpc] private void ChangeLevelClientRpc(ulong changeClientId, NetworkString factionTag, TaxLevel taxLevel, ExpropriateGrainLevel grainLevel, MaintenanceLevel maintenanceLevel, ClientRpcParams rpcParams = default) { if (changeClientId == NetworkManager.LocalClientId) { // ϲҪڶ޸ return; } Faction faction = politicLoader.GetFactionByTag(factionTag.ToString()); if (faction != null) { faction.SetLevelDirectly(taxLevel, grainLevel, maintenanceLevel); Debug.Log($"{changeClientId}ĸ˰{factionTag} ɹ!"); } else { Debug.Log("δҵӦfaction: " + factionTag); } } } }
0
0.771708
1
0.771708
game-dev
MEDIA
0.866633
game-dev,networking
0.671618
1
0.671618
codingben/maple-fighters
2,118
src/maple-fighters/Assets/Maple Fighters/Scripts/Gameplay/Map/Climb/Ladder/LadderInteractor.cs
using Scripts.Constants; using Scripts.Gameplay.Player; using UnityEngine; namespace Scripts.Gameplay.Map.Climb { [RequireComponent(typeof(PlayerController), typeof(Collider2D))] public class LadderInteractor : ClimbInteractor { private PlayerController playerController; private ColliderInteraction colliderInteraction; private void Awake() { playerController = GetComponent<PlayerController>(); var collider = GetComponent<Collider2D>(); colliderInteraction = new ColliderInteraction(collider); } protected override void SetPlayerToClimbState() { playerController.SetPlayerState(GetClimbState()); } protected override void UnsetPlayerFromClimbState() { var playerState = playerController.IsGrounded() ? PlayerStates.Idle : PlayerStates.Falling; playerController.SetPlayerState(playerState); } protected override PlayerStates GetPlayerState() { return playerController.GetPlayerState(); } protected override KeyCode GetUpKey() { return playerController.GetKeyboardSettings().ClimbUpKey; } protected override KeyCode GetSecondaryUpKey() { return playerController.GetKeyboardSettings().SecondaryClimbUpKey; } protected override KeyCode GetDownKey() { return playerController.GetKeyboardSettings().ClimbDownKey; } protected override KeyCode GetSecondaryDownKey() { return playerController.GetKeyboardSettings().SecondaryClimbDownKey; } protected override ColliderInteraction GetColliderInteraction() { return colliderInteraction; } protected override string GetTagName() { return GameTags.LadderTag; } protected override PlayerStates GetClimbState() { return PlayerStates.Ladder; } } }
0
0.783202
1
0.783202
game-dev
MEDIA
0.991119
game-dev
0.655462
1
0.655462
dyn4j/dyn4j
3,338
src/main/java/org/dyn4j/world/World.java
/* * Copyright (c) 2010-2021 William Bittle http://www.dyn4j.org/ * 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 the copyright holder 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 HOLDER 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 org.dyn4j.world; import org.dyn4j.collision.CollisionItem; import org.dyn4j.collision.CollisionPair; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.dynamics.PhysicsBody; import org.dyn4j.dynamics.joint.Joint; /** * Full implementation of both the {@link CollisionWorld} and {@link PhysicsWorld} interfaces. * <p> * <b>NOTE</b>: This class uses the {@link Body#setOwner(Object)} and * {@link Body#setFixtureModificationHandler(org.dyn4j.collision.FixtureModificationHandler)} * methods to handle certain scenarios like fixture removal on a body or bodies added to * more than one world. Likewise, the {@link Joint#setOwner(Object)} method is used to handle * joints being added to the world. Callers should <b>NOT</b> use these methods. * @author William Bittle * @version 4.1.0 * @since 4.0.0 * @param <T> the {@link PhysicsBody} type */ public class World<T extends PhysicsBody> extends AbstractPhysicsWorld<T, WorldCollisionData<T>> { /** * Default constructor. */ public World() { this(CollisionWorld.DEFAULT_INITIAL_BODY_CAPACITY, PhysicsWorld.DEFAULT_INITIAL_JOINT_CAPACITY); } /** * Optional constructor. * @param initialBodyCapacity the initial body capacity * @param initialJointCapacity the initial joint capacity */ public World(int initialBodyCapacity, int initialJointCapacity) { super(initialBodyCapacity, initialJointCapacity); } /* (non-Javadoc) * @see org.dyn4j.world.AbstractCollisionWorld#createCollisionData(org.dyn4j.collision.CollisionPair) */ @Override protected WorldCollisionData<T> createCollisionData(CollisionPair<CollisionItem<T, BodyFixture>> pair) { return new WorldCollisionData<T>(pair); } }
0
0.743338
1
0.743338
game-dev
MEDIA
0.623037
game-dev
0.702249
1
0.702249
SkelletonX/DDTank4.1
1,962
Source Server/Game.Logic/PetEffects/PetClearPlusGuardEquipEffect.cs
// Decompiled with JetBrains decompiler // Type: Game.Logic.PetEffects.PetClearPlusGuardEquipEffect // Assembly: Game.Logic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: E8B04D54-7E5B-47C4-9280-AF82495F6281 // Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\Game.Logic.dll using Game.Logic.Phy.Object; namespace Game.Logic.PetEffects { public class PetClearPlusGuardEquipEffect : BasePetEffect { private int m_count; private int m_currentId; private int m_delay; private int m_probability; private int m_type; public PetClearPlusGuardEquipEffect( int count, int probability, int type, int skillId, int delay, string elementID) : base(ePetEffectType.PetClearPlusGuardEquipEffect, elementID) { this.m_count = count; this.m_probability = probability == -1 ? 10000 : probability; this.m_type = type; this.m_delay = delay; this.m_currentId = skillId; } protected override void OnAttachedToPlayer(Player player) { player.PlayerBeginMoving += new PlayerEventHandle(this.player_WhenMoving); } protected override void OnRemovedFromPlayer(Player player) { player.PlayerBeginMoving -= new PlayerEventHandle(this.player_WhenMoving); } private void player_WhenMoving(Player player) { if (player.PetEffects.AddGuardValue <= 0) return; player.BaseGuard -= (double) player.PetEffects.AddGuardValue; player.PetEffects.AddGuardValue = 0; } public override bool Start(Living living) { PetClearPlusGuardEquipEffect ofType = living.PetEffectList.GetOfType(ePetEffectType.PetClearPlusGuardEquipEffect) as PetClearPlusGuardEquipEffect; if (ofType == null) return base.Start(living); ofType.m_probability = this.m_probability > ofType.m_probability ? this.m_probability : ofType.m_probability; return true; } } }
0
0.882956
1
0.882956
game-dev
MEDIA
0.533342
game-dev
0.94617
1
0.94617
BretJohnson/XGraphics
1,922
src/XamarinForms/XGraphics.XamarinForms/Geometries/PathFigure.cs
// This file is generated from IPathFigure.cs. Update the source file to change its contents. using System.Collections.Generic; using XGraphics.Geometries; using Xamarin.Forms; namespace XGraphics.XamarinForms.Geometries { public class PathFigure : BindableObjectWithCascadingNotifications, IPathFigure { public static readonly BindableProperty SegmentsProperty = PropertyUtils.Create(nameof(Segments), typeof(XGraphicsCollection<PathSegment>), typeof(PathFigure), null); public static readonly BindableProperty StartPointProperty = PropertyUtils.Create(nameof(StartPoint), typeof(Wrapper.Point), typeof(PathFigure), Wrapper.Point.Default); public static readonly BindableProperty IsClosedProperty = PropertyUtils.Create(nameof(IsClosed), typeof(bool), typeof(PathFigure), false); public static readonly BindableProperty IsFilledProperty = PropertyUtils.Create(nameof(IsFilled), typeof(bool), typeof(PathFigure), true); public PathFigure() { Segments = new XGraphicsCollection<PathSegment>(); } public XGraphicsCollection<PathSegment> Segments { get => (XGraphicsCollection<PathSegment>)GetValue(SegmentsProperty); set => SetValue(SegmentsProperty, value); } IEnumerable<IPathSegment> IPathFigure.Segments => Segments; public Wrapper.Point StartPoint { get => (Wrapper.Point)GetValue(StartPointProperty); set => SetValue(StartPointProperty, value); } Point IPathFigure.StartPoint => StartPoint.WrappedPoint; public bool IsClosed { get => (bool)GetValue(IsClosedProperty); set => SetValue(IsClosedProperty, value); } public bool IsFilled { get => (bool)GetValue(IsFilledProperty); set => SetValue(IsFilledProperty, value); } } }
0
0.527122
1
0.527122
game-dev
MEDIA
0.786417
game-dev
0.807378
1
0.807378
Source-SDK-Archives/source-sdk-2004
8,331
src_mod/dlls/hl2_dll/npc_apcdriver.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "npc_vehicledriver.h" #include "vehicle_apc.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define SF_APCDRIVER_NO_ROCKET_ATTACK 0x10000 #define SF_APCDRIVER_NO_GUN_ATTACK 0x20000 #define NPC_APCDRIVER_REMEMBER_TIME 4 //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CNPC_APCDriver : public CNPC_VehicleDriver { DECLARE_CLASS( CNPC_APCDriver, CNPC_VehicleDriver ); public: DECLARE_DATADESC(); DEFINE_CUSTOM_AI; virtual void Spawn( void ); virtual void Activate( void ); virtual bool FVisible( CBaseEntity *pTarget, int traceMask, CBaseEntity **ppBlocker ); virtual bool WeaponLOSCondition( const Vector &ownerPos, const Vector &targetPos, bool bSetConditions ); virtual Class_T Classify ( void ) { return CLASS_COMBINE; } virtual void PrescheduleThink( ); virtual Disposition_t IRelationType(CBaseEntity *pTarget); // AI virtual int RangeAttack1Conditions( float flDot, float flDist ); virtual int RangeAttack2Conditions( float flDot, float flDist ); private: // Are we being carried by a dropship? bool IsBeingCarried(); // Enable, disable firing void InputEnableFiring( inputdata_t &inputdata ); void InputDisableFiring( inputdata_t &inputdata ); CHandle<CPropAPC> m_hAPC; float m_flTimeLastSeenEnemy; bool m_bFiringDisabled; }; BEGIN_DATADESC( CNPC_APCDriver ) //DEFINE_FIELD( m_hAPC, FIELD_EHANDLE ), DEFINE_FIELD( m_bFiringDisabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_flTimeLastSeenEnemy, FIELD_TIME ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableFiring", InputEnableFiring ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableFiring", InputDisableFiring ), END_DATADESC() LINK_ENTITY_TO_CLASS( npc_apcdriver, CNPC_APCDriver ); //------------------------------------------------------------------------------ // Purpose : //------------------------------------------------------------------------------ void CNPC_APCDriver::Spawn( void ) { BaseClass::Spawn(); m_flTimeLastSeenEnemy = -NPC_APCDRIVER_REMEMBER_TIME; CapabilitiesClear(); CapabilitiesAdd( bits_CAP_INNATE_RANGE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK2 ); m_bFiringDisabled = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_APCDriver::Activate( void ) { BaseClass::Activate(); m_hAPC = dynamic_cast<CPropAPC*>((CBaseEntity*)m_hVehicleEntity); if ( !m_hAPC ) { Warning( "npc_apcdriver %s couldn't find his apc named %s.\n", STRING(GetEntityName()), STRING(m_iszVehicleName) ); UTIL_Remove( this ); return; } SetParent( m_hAPC ); SetAbsOrigin( m_hAPC->WorldSpaceCenter() ); SetLocalAngles( vec3_angle ); m_flDistTooFar = m_hAPC->MaxAttackRange(); SetDistLook( m_hAPC->MaxAttackRange() ); } //----------------------------------------------------------------------------- // Enable, disable firing //----------------------------------------------------------------------------- void CNPC_APCDriver::InputEnableFiring( inputdata_t &inputdata ) { m_bFiringDisabled = false; } void CNPC_APCDriver::InputDisableFiring( inputdata_t &inputdata ) { m_bFiringDisabled = true; } //----------------------------------------------------------------------------- // Purpose: Let's not hate things the APC makes //----------------------------------------------------------------------------- Disposition_t CNPC_APCDriver::IRelationType(CBaseEntity *pTarget) { if ( pTarget == m_hAPC || (pTarget->GetOwnerEntity() == m_hAPC) ) return D_LI; return BaseClass::IRelationType(pTarget); } //------------------------------------------------------------------------------ // Are we being carried by a dropship? //------------------------------------------------------------------------------ bool CNPC_APCDriver::IsBeingCarried() { // Inert if we're carried... Vector vecVelocity; m_hAPC->GetVelocity( &vecVelocity, NULL ); return ( m_hAPC->GetMoveParent() != NULL ) || (fabs(vecVelocity.z) >= 15); } //------------------------------------------------------------------------------ // Is the enemy visible? //------------------------------------------------------------------------------ bool CNPC_APCDriver::WeaponLOSCondition(const Vector &ownerPos, const Vector &targetPos, bool bSetConditions) { if ( m_hAPC->m_lifeState != LIFE_ALIVE ) return false; if ( IsBeingCarried() || m_bFiringDisabled ) return false; float flTargetDist = ownerPos.DistTo( targetPos ); if (flTargetDist > m_hAPC->MaxAttackRange()) return false; return true; } //----------------------------------------------------------------------------- // Is the enemy visible? //----------------------------------------------------------------------------- bool CNPC_APCDriver::FVisible( CBaseEntity *pTarget, int traceMask, CBaseEntity **ppBlocker ) { if ( m_hAPC->m_lifeState != LIFE_ALIVE ) return false; if ( IsBeingCarried() || m_bFiringDisabled ) return false; float flTargetDist = GetAbsOrigin().DistTo( pTarget->GetAbsOrigin() ); if (flTargetDist > m_hAPC->MaxAttackRange()) return false; bool bVisible = m_hAPC->FVisible( pTarget, traceMask, ppBlocker ); if ( bVisible && (pTarget == GetEnemy()) ) { m_flTimeLastSeenEnemy = gpGlobals->curtime; } if ( pTarget->IsPlayer() || pTarget->Classify() == CLASS_BULLSEYE ) { if (!bVisible) { if ( ( gpGlobals->curtime - m_flTimeLastSeenEnemy ) <= NPC_APCDRIVER_REMEMBER_TIME ) return true; } } return bVisible; } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- int CNPC_APCDriver::RangeAttack1Conditions( float flDot, float flDist ) { if ( HasSpawnFlags(SF_APCDRIVER_NO_GUN_ATTACK) ) return COND_NONE; if ( m_hAPC->m_lifeState != LIFE_ALIVE ) return COND_NONE; if ( IsBeingCarried() || m_bFiringDisabled ) return COND_NONE; if ( !HasCondition( COND_SEE_ENEMY ) ) return COND_NONE; if ( !m_hAPC->IsInPrimaryFiringCone() ) return COND_NONE; // Vehicle not ready to fire again yet? if ( m_pVehicleInterface->Weapon_PrimaryCanFireAt() > gpGlobals->curtime + 0.1f ) return COND_NONE; float flMinDist, flMaxDist; m_pVehicleInterface->Weapon_PrimaryRanges( &flMinDist, &flMaxDist ); if (flDist < flMinDist) return COND_NONE; if (flDist > flMaxDist) return COND_NONE; return COND_CAN_RANGE_ATTACK1; } int CNPC_APCDriver::RangeAttack2Conditions( float flDot, float flDist ) { if ( HasSpawnFlags(SF_APCDRIVER_NO_ROCKET_ATTACK) ) return COND_NONE; if ( m_hAPC->m_lifeState != LIFE_ALIVE ) return COND_NONE; if ( IsBeingCarried() || m_bFiringDisabled ) return COND_NONE; if ( !HasCondition( COND_SEE_ENEMY ) ) return COND_NONE; // Vehicle not ready to fire again yet? if ( m_pVehicleInterface->Weapon_SecondaryCanFireAt() > gpGlobals->curtime + 0.1f ) return COND_NONE; float flMinDist, flMaxDist; m_pVehicleInterface->Weapon_SecondaryRanges( &flMinDist, &flMaxDist ); if (flDist < flMinDist) return COND_NONE; if (flDist > flMaxDist) return COND_NONE; return COND_CAN_RANGE_ATTACK2; } //----------------------------------------------------------------------------- // Aim the laser dot! //----------------------------------------------------------------------------- void CNPC_APCDriver::PrescheduleThink( ) { BaseClass::PrescheduleThink(); if ( m_hAPC->m_lifeState == LIFE_ALIVE ) { if ( GetEnemy() ) { m_hAPC->AimPrimaryWeapon( GetEnemy()->BodyTarget( GetAbsOrigin(), false ) ); } m_hAPC->AimSecondaryWeaponAt( GetEnemy() ); } else if ( m_hAPC->m_lifeState == LIFE_DEAD ) { UTIL_Remove( this ); } } //----------------------------------------------------------------------------- // // Schedules // //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( npc_apcdriver, CNPC_APCDriver ) AI_END_CUSTOM_NPC()
0
0.99412
1
0.99412
game-dev
MEDIA
0.967158
game-dev
0.989011
1
0.989011