repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/macro.rs | lib/armv9a/src/macro.rs | #[macro_export]
macro_rules! define_mask {
($end:expr, $beg:expr) => {
((1 << $end) - (1 << $beg) + (1 << $end))
};
}
#[macro_export]
macro_rules! define_bitfield {
($field:ident, [$($end:tt-$beg:tt)|*]) => {
#[allow(non_upper_case_globals)]
pub const $field: u64 = $( define_mask!($end, $beg) )|*;
};
}
#[macro_export]
macro_rules! define_register {
($regname:ident) => { define_register!($regname, ); };
($regname:ident, $($field:ident $bits:tt),*) => {
#[allow(non_snake_case)]
pub mod $regname {
pub struct Register;
impl Register {
/// # Safety
#[inline(always)]
pub unsafe fn get(&self) -> u64 {
let rtn;
core::arch::asm! {
concat!("mov {}, ", stringify!($regname)),
out(reg) rtn
}
rtn
}
/// # Safety
#[inline(always)]
pub unsafe fn get_masked(&self, mask: u64) -> u64 {
let rtn: u64;
core::arch::asm! {
concat!("mov {}, ", stringify!($regname)),
out(reg) rtn
}
rtn & mask
}
/// # Safety
#[inline(always)]
pub unsafe fn get_masked_value(&self, mask: u64) -> u64 {
let rtn: u64;
core::arch::asm! {
concat!("mov {}, ", stringify!($regname)),
out(reg) rtn
}
(rtn & mask) >> (mask.trailing_zeros())
}
/// # Safety
#[inline(always)]
pub unsafe fn set(&self, val: u64) {
core::arch::asm! {
concat!("mov ", stringify!($regname), ", {}"),
in(reg) val
}
}
}
$( define_bitfield!($field, $bits); )*
}
#[allow(non_upper_case_globals)]
pub static $regname: $regname::Register = $regname::Register {};
};
}
#[macro_export]
macro_rules! define_bits {
($name:ident) => { define_register!($name, ); };
($name:ident, $($field:ident $bits:tt),*) => {
#[allow(non_snake_case)]
#[derive(Copy, Clone)]
#[repr(C)]
pub struct $name (pub u64);
impl $name {
#[inline(always)]
pub fn new(data: u64) -> $name {
$name(data)
}
#[inline(always)]
pub fn get_mut(&mut self) -> &mut Self {
self
}
#[inline(always)]
pub fn get(&self) -> u64 {
self.0
}
#[inline(always)]
pub fn get_masked(&self, mask: u64) -> u64 {
self.0 & mask
}
#[inline(always)]
pub fn get_masked_value(&self, mask: u64) -> u64 {
(self.0 & mask) >> (mask.trailing_zeros())
}
#[inline(always)]
pub fn set(&mut self, val: u64) -> &mut Self {
self.0 = val;
self
}
#[inline(always)]
pub fn set_masked(&mut self, mask: u64, val: u64) -> &mut Self {
self.0 = (self.0 & !mask) | (val & mask);
self
}
#[inline(always)]
pub fn set_masked_value(&mut self, mask: u64, val: u64) -> &mut Self {
self.0 = (self.0 & !mask)
| ((val << (mask.trailing_zeros())) & mask);
self
}
#[inline(always)]
pub fn set_bits(&mut self, mask: u64) -> &mut Self {
self.0 |= mask;
self
}
#[inline(always)]
pub fn clear_bits(&mut self, mask: u64) -> &mut Self {
self.0 &= !mask;
self
}
$( define_bitfield!($field, $bits); )*
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs.rs | lib/armv9a/src/regs.rs | #![allow(unused_attributes)]
#[macro_use]
mod macros;
mod cptr_el2;
mod id_aa64pfr1_el1;
mod id_aa64zfr0_el1;
mod mdcr_el2;
mod pmcr_el0;
pub mod pmu;
mod smcr_el2;
mod svcr;
mod zcr_el1;
mod zcr_el2;
pub use cptr_el2::CPTR_EL2;
pub use id_aa64pfr1_el1::ID_AA64PFR1_SME_EL1;
pub use id_aa64zfr0_el1::ID_AA64ZFR0_EL1;
pub use mdcr_el2::MDCR_EL2;
pub use pmcr_el0::PMCR_EL0;
pub use smcr_el2::SMCR_EL2;
pub use svcr::SVCR;
pub use zcr_el1::ZCR_EL1;
pub use zcr_el2::ZCR_EL2;
use crate::bits_in_reg;
define_bits!(
EsrEl1,
// Exception Class.
EC[31 - 26],
// Instruction Length for synchronous exceptions.
IL[25 - 25],
// Syndrome information.
ISS[24 - 0]
);
define_bits!(
EsrEl2,
// Exception Class.
EC[31 - 26],
// Instruction Length for synchronous exceptions.
IL[25 - 25],
// Instruction syndrome valid.
ISV[24 - 24],
// IMPLEMENTATION DEFINED syndrome (for SError)
IDS[24 - 24],
// Syndrome Access Size (ISV == '1')
SAS[23 - 22],
// Syndrome Sign Extend (ISV == '1')
SSE[21 - 21],
// Syndrome Register Transfer (ISV == '1')
SRT[20 - 16],
// Width of the register accessed by the instruction is Sixty-Four (ISV == '1')
SF[15 - 15],
// Acquire/Release. (ISV == '1')
AR[14 - 14],
// Indicates that the fault came from use of VNCR_EL2 register by EL1 code.
VNCR[13 - 13],
// Synchronous Error Type
SET[12 - 11],
// Asynchronous Error Type. (for SError)
AET[12 - 10],
// FAR not Valid
FNV[10 - 10],
// External Abort type
EA[9 - 9],
// Cache Maintenance
CM[8 - 8],
S1PTW[7 - 7],
// Write not Read.
WNR[6 - 6],
DFSC[5 - 0],
// Trapped instruction (for WFx)
TI[1 - 0]
);
impl EsrEl2 {
pub fn get_access_size_mask(&self) -> u64 {
match self.get_masked_value(EsrEl2::SAS) {
0 => 0xff, // byte
1 => 0xffff, // half-word
2 => 0xffffffff, // word
3 => 0xffffffff_ffffffff, // double word
_ => unreachable!(), // SAS consists of two bits
}
}
}
pub const ESR_EL1_EC_UNKNOWN: u64 = 0;
pub const ESR_EL2_EC_UNKNOWN: u64 = 0;
pub const ESR_EL2_EC_WFX: u64 = 1;
pub const ESR_EL2_EC_FPU: u64 = 7;
pub const ESR_EL2_EC_SVC: u64 = 21;
pub const ESR_EL2_EC_HVC: u64 = 22;
pub const ESR_EL2_EC_SMC: u64 = 23;
pub const ESR_EL2_EC_SYSREG: u64 = 24;
pub const ESR_EL2_EC_SVE: u64 = 25;
pub const ESR_EL2_EC_INST_ABORT: u64 = 32;
pub const ESR_EL2_EC_DATA_ABORT: u64 = 36;
pub const ESR_EL2_EC_SERROR: u64 = 47;
pub const ESR_EL2_TI_WFI: u64 = 0;
pub const ESR_EL2_TI_WFE: u64 = 1;
pub const ESR_EL2_TI_WFIT: u64 = 2;
pub const ESR_EL2_TI_WFET: u64 = 3;
pub const DFSC_PERM_FAULT_MASK: u64 = 0b111100;
pub const DFSC_PERM_FAULTS: u64 = 0b001100; // 0b0011xx
pub const NON_EMULATABLE_ABORT_MASK: u64 =
EsrEl2::EC | EsrEl2::SET | EsrEl2::FNV | EsrEl2::EA | EsrEl2::DFSC;
pub const EMULATABLE_ABORT_MASK: u64 =
NON_EMULATABLE_ABORT_MASK | EsrEl2::ISV | EsrEl2::SAS | EsrEl2::SF | EsrEl2::WNR;
pub const INST_ABORT_MASK: u64 = EsrEl2::EC | EsrEl2::SET | EsrEl2::EA | EsrEl2::DFSC;
pub const SERROR_MASK: u64 = EsrEl2::EC | EsrEl2::IDS | EsrEl2::AET | EsrEl2::EA | EsrEl2::DFSC;
pub const WFX_MASK: u64 = EsrEl2::EC | EsrEl2::TI;
macro_rules! define_iss_id {
($name:ident, $Op0:expr, $Op1:expr, $CRn:expr, $CRm:expr, $Op2:expr) => {
pub const $name: u32 = bits_in_reg(ISS::Op0, $Op0) as u32
| bits_in_reg(ISS::Op1, $Op1) as u32
| bits_in_reg(ISS::CRn, $CRn) as u32
| bits_in_reg(ISS::CRm, $CRm) as u32
| bits_in_reg(ISS::Op2, $Op2) as u32;
};
}
define_bits!(
ISS,
IL[25 - 25],
Op0[21 - 20],
Op2[19 - 17],
Op1[16 - 14],
CRn[13 - 10],
Rt[9 - 5],
CRm[4 - 1],
Direction[0 - 0]
);
define_iss_id!(ISS_ID_AA64PFR0_EL1, 3, 0, 0, 4, 0);
define_iss_id!(ISS_ID_AA64PFR1_EL1, 3, 0, 0, 4, 1);
define_iss_id!(ISS_ID_AA64DFR0_EL1, 3, 0, 0, 5, 0);
define_iss_id!(ISS_ID_AA64DFR1_EL1, 3, 0, 0, 5, 1);
define_iss_id!(ISS_ID_AA64AFR0_EL1, 3, 0, 0, 5, 4);
define_iss_id!(ISS_ID_AA64AFR1_EL1, 3, 0, 0, 5, 5);
define_iss_id!(ISS_ID_AA64ISAR0_EL1, 3, 0, 0, 6, 0);
define_iss_id!(ISS_ID_AA64ISAR1_EL1, 3, 0, 0, 6, 1);
define_iss_id!(ISS_ID_AA64MMFR0_EL1, 3, 0, 0, 7, 0);
define_iss_id!(ISS_ID_AA64MMFR1_EL1, 3, 0, 0, 7, 1);
define_iss_id!(ISS_ID_AA64MMFR2_EL1, 3, 0, 0, 7, 2);
define_iss_id!(ISS_ID_AA64ZFR0_EL1, 3, 0, 0, 4, 4);
define_iss_id!(ISS_ID_ICC_DIR_EL1, 3, 0, 0xc, 0xb, 1);
define_iss_id!(ISS_ID_ICC_SGI1R_EL1, 3, 0, 0xc, 0xb, 5);
define_iss_id!(ISS_ID_ICC_SGI0R_EL1, 3, 0, 0xc, 0xb, 7);
define_iss_id!(ISS_ID_ICC_PMR_EL1, 3, 0, 4, 6, 0);
define_iss_id!(ISS_ID_ICC_MASK, 3, 0, 0xc, 0xb, 0);
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/cptr_el2.rs | lib/armv9a/src/regs/cptr_el2.rs | use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub CPTR_EL2 [
// Trap accesses to CPACR_EL1 from EL1 to EL2,
TCPAC OFFSET(31) NUMBITS(1) [],
// Trap Activity Monitor access from EL1 and EL0.
TAM OFFSET(30) NUMBITS(1) [],
// Traps System register accesses to all implemented trace registers
TTA OFFSET(20) NUMBITS(1) [],
// Traps execution of SME instructions
TSM OFFSET(12) NUMBITS(1) [],
// Traps execution of Advanced SIMD and floating-point instructions
TFP OFFSET(10) NUMBITS(1) [],
// Traps execution of SVE instructions
TZ OFFSET(8) NUMBITS(1) [],
/*
// Traps System register accesses to all implemented trace registers
TTA OFFSET(28) NUMBITS(1) [],
// Traps execution at EL2, EL1, and EL0 of SME instructions
SMEN OFFSET(24) NUMBITS(2) [
TrapAll = 0b00,
TrapE0 = 0b01,
TrapNone = 0b11,
],
// Traps execution of SIMD and FPU
FPEN OFFSET(20) NUMBITS(2) [
TrapAll = 0b00,
TrapE0 = 0b01,
TrapNone = 0b11,
],
// Traps execution of non-streaming SVE
ZEN OFFSET(16) NUMBITS(2) [
TrapAll = 0b00,
TrapE0 = 0b01,
TrapNone = 0b11,
]
*/
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = CPTR_EL2::Register;
sys_coproc_read_raw!(u64, "CPTR_EL2", "x");
}
impl Writeable for Reg {
type T = u64;
type R = CPTR_EL2::Register;
sys_coproc_write_raw!(u64, "CPTR_EL2", "x");
}
pub const CPTR_EL2: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/pmcr_el0.rs | lib/armv9a/src/regs/pmcr_el0.rs | //! Performance Monitors Control Register - EL0
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub PMCR_EL0 [
/// Number of event counters implemented
N OFFSET(11) NUMBITS(5) [],
LP OFFSET(7) NUMBITS(1) [],
LC OFFSET(6) NUMBITS(1) [],
DP OFFSET(5) NUMBITS(1) [],
X OFFSET(4) NUMBITS(1) [],
D OFFSET(3) NUMBITS(1) [],
C OFFSET(2) NUMBITS(1) [],
P OFFSET(1) NUMBITS(1) [],
E OFFSET(0) NUMBITS(1) [],
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = PMCR_EL0::Register;
sys_coproc_read_raw!(u64, "PMCR_EL0", "x");
}
impl Writeable for Reg {
type T = u64;
type R = PMCR_EL0::Register;
sys_coproc_write_raw!(u64, "PMCR_EL0", "x");
}
pub const PMCR_EL0: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/pmu.rs | lib/armv9a/src/regs/pmu.rs | #![allow(unused_imports)]
#![allow(unused_attributes)]
use tock_registers::interfaces::{Readable, Writeable};
#[macro_export]
macro_rules! define_pmu_register {
($mod_name:ident, $reg_name:ident, $reg_literal:tt) => {
pub mod $mod_name {
use tock_registers::interfaces::{Readable, Writeable};
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = ();
sys_coproc_read_raw!(u64, $reg_literal, "x");
}
impl Writeable for Reg {
type T = u64;
type R = ();
sys_coproc_write_raw!(u64, $reg_literal, "x");
}
pub const $reg_name: Reg = Reg {};
}
};
}
define_pmu_register!(pmccfiltr_el0, PMCCFILTR_EL0, "PMCCFILTR_EL0");
define_pmu_register!(pmccntr_el0, PMCCNTR_EL0, "PMCCNTR_EL0");
define_pmu_register!(pmcntenset_el0, PMCNTENSET_EL0, "PMCNTENSET_EL0");
define_pmu_register!(pmcntenclr_el0, PMCNTENCLR_EL0, "PMCNTENCLR_EL0");
define_pmu_register!(pmintenset_el1, PMINTENSET_EL1, "PMINTENSET_EL1");
define_pmu_register!(pmintenclr_el1, PMINTENCLR_EL1, "PMINTENCLR_EL1");
define_pmu_register!(pmovsset_el0, PMOVSSET_EL0, "PMOVSSET_EL0");
define_pmu_register!(pmovsclr_el0, PMOVSCLR_EL0, "PMOVSCLR_EL0");
define_pmu_register!(pmselr_el0, PMSELR_EL0, "PMSELR_EL0");
define_pmu_register!(pmuserenr_el0, PMUSERENR_EL0, "PMUSERENR_EL0");
define_pmu_register!(pmxevcntr_el0, PMXEVCNTR_EL0, "PMXEVCNTR_EL0");
define_pmu_register!(pmxevtyper_el0, PMXEVTYPER_EL0, "PMXEVTYPER_EL0");
define_pmu_register!(pmevcntr0_el0, PMEVCNTR0_EL0, "PMEVCNTR0_EL0");
define_pmu_register!(pmevcntr1_el0, PMEVCNTR1_EL0, "PMEVCNTR1_EL0");
define_pmu_register!(pmevcntr2_el0, PMEVCNTR2_EL0, "PMEVCNTR2_EL0");
define_pmu_register!(pmevcntr3_el0, PMEVCNTR3_EL0, "PMEVCNTR3_EL0");
define_pmu_register!(pmevcntr4_el0, PMEVCNTR4_EL0, "PMEVCNTR4_EL0");
define_pmu_register!(pmevcntr5_el0, PMEVCNTR5_EL0, "PMEVCNTR5_EL0");
define_pmu_register!(pmevcntr6_el0, PMEVCNTR6_EL0, "PMEVCNTR6_EL0");
define_pmu_register!(pmevcntr7_el0, PMEVCNTR7_EL0, "PMEVCNTR7_EL0");
define_pmu_register!(pmevcntr8_el0, PMEVCNTR8_EL0, "PMEVCNTR8_EL0");
define_pmu_register!(pmevcntr9_el0, PMEVCNTR9_EL0, "PMEVCNTR9_EL0");
define_pmu_register!(pmevcntr10_el0, PMEVCNTR10_EL0, "PMEVCNTR10_EL0");
define_pmu_register!(pmevcntr11_el0, PMEVCNTR11_EL0, "PMEVCNTR11_EL0");
define_pmu_register!(pmevcntr12_el0, PMEVCNTR12_EL0, "PMEVCNTR12_EL0");
define_pmu_register!(pmevcntr13_el0, PMEVCNTR13_EL0, "PMEVCNTR13_EL0");
define_pmu_register!(pmevcntr14_el0, PMEVCNTR14_EL0, "PMEVCNTR14_EL0");
define_pmu_register!(pmevcntr15_el0, PMEVCNTR15_EL0, "PMEVCNTR15_EL0");
define_pmu_register!(pmevcntr16_el0, PMEVCNTR16_EL0, "PMEVCNTR16_EL0");
define_pmu_register!(pmevcntr17_el0, PMEVCNTR17_EL0, "PMEVCNTR17_EL0");
define_pmu_register!(pmevcntr18_el0, PMEVCNTR18_EL0, "PMEVCNTR18_EL0");
define_pmu_register!(pmevcntr19_el0, PMEVCNTR19_EL0, "PMEVCNTR19_EL0");
define_pmu_register!(pmevcntr20_el0, PMEVCNTR20_EL0, "PMEVCNTR20_EL0");
define_pmu_register!(pmevcntr21_el0, PMEVCNTR21_EL0, "PMEVCNTR21_EL0");
define_pmu_register!(pmevcntr22_el0, PMEVCNTR22_EL0, "PMEVCNTR22_EL0");
define_pmu_register!(pmevcntr23_el0, PMEVCNTR23_EL0, "PMEVCNTR23_EL0");
define_pmu_register!(pmevcntr24_el0, PMEVCNTR24_EL0, "PMEVCNTR24_EL0");
define_pmu_register!(pmevcntr25_el0, PMEVCNTR25_EL0, "PMEVCNTR25_EL0");
define_pmu_register!(pmevcntr26_el0, PMEVCNTR26_EL0, "PMEVCNTR26_EL0");
define_pmu_register!(pmevcntr27_el0, PMEVCNTR27_EL0, "PMEVCNTR27_EL0");
define_pmu_register!(pmevcntr28_el0, PMEVCNTR28_EL0, "PMEVCNTR28_EL0");
define_pmu_register!(pmevcntr29_el0, PMEVCNTR29_EL0, "PMEVCNTR29_EL0");
define_pmu_register!(pmevcntr30_el0, PMEVCNTR30_EL0, "PMEVCNTR30_EL0");
define_pmu_register!(pmevtyper0_el0, PMEVTYPER0_EL0, "PMEVTYPER0_EL0");
define_pmu_register!(pmevtyper1_el0, PMEVTYPER1_EL0, "PMEVTYPER1_EL0");
define_pmu_register!(pmevtyper2_el0, PMEVTYPER2_EL0, "PMEVTYPER2_EL0");
define_pmu_register!(pmevtyper3_el0, PMEVTYPER3_EL0, "PMEVTYPER3_EL0");
define_pmu_register!(pmevtyper4_el0, PMEVTYPER4_EL0, "PMEVTYPER4_EL0");
define_pmu_register!(pmevtyper5_el0, PMEVTYPER5_EL0, "PMEVTYPER5_EL0");
define_pmu_register!(pmevtyper6_el0, PMEVTYPER6_EL0, "PMEVTYPER6_EL0");
define_pmu_register!(pmevtyper7_el0, PMEVTYPER7_EL0, "PMEVTYPER7_EL0");
define_pmu_register!(pmevtyper8_el0, PMEVTYPER8_EL0, "PMEVTYPER8_EL0");
define_pmu_register!(pmevtyper9_el0, PMEVTYPER9_EL0, "PMEVTYPER9_EL0");
define_pmu_register!(pmevtyper10_el0, PMEVTYPER10_EL0, "PMEVTYPER10_EL0");
define_pmu_register!(pmevtyper11_el0, PMEVTYPER11_EL0, "PMEVTYPER11_EL0");
define_pmu_register!(pmevtyper12_el0, PMEVTYPER12_EL0, "PMEVTYPER12_EL0");
define_pmu_register!(pmevtyper13_el0, PMEVTYPER13_EL0, "PMEVTYPER13_EL0");
define_pmu_register!(pmevtyper14_el0, PMEVTYPER14_EL0, "PMEVTYPER14_EL0");
define_pmu_register!(pmevtyper15_el0, PMEVTYPER15_EL0, "PMEVTYPER15_EL0");
define_pmu_register!(pmevtyper16_el0, PMEVTYPER16_EL0, "PMEVTYPER16_EL0");
define_pmu_register!(pmevtyper17_el0, PMEVTYPER17_EL0, "PMEVTYPER17_EL0");
define_pmu_register!(pmevtyper18_el0, PMEVTYPER18_EL0, "PMEVTYPER18_EL0");
define_pmu_register!(pmevtyper19_el0, PMEVTYPER19_EL0, "PMEVTYPER19_EL0");
define_pmu_register!(pmevtyper20_el0, PMEVTYPER20_EL0, "PMEVTYPER20_EL0");
define_pmu_register!(pmevtyper21_el0, PMEVTYPER21_EL0, "PMEVTYPER21_EL0");
define_pmu_register!(pmevtyper22_el0, PMEVTYPER22_EL0, "PMEVTYPER22_EL0");
define_pmu_register!(pmevtyper23_el0, PMEVTYPER23_EL0, "PMEVTYPER23_EL0");
define_pmu_register!(pmevtyper24_el0, PMEVTYPER24_EL0, "PMEVTYPER24_EL0");
define_pmu_register!(pmevtyper25_el0, PMEVTYPER25_EL0, "PMEVTYPER25_EL0");
define_pmu_register!(pmevtyper26_el0, PMEVTYPER26_EL0, "PMEVTYPER26_EL0");
define_pmu_register!(pmevtyper27_el0, PMEVTYPER27_EL0, "PMEVTYPER27_EL0");
define_pmu_register!(pmevtyper28_el0, PMEVTYPER28_EL0, "PMEVTYPER28_EL0");
define_pmu_register!(pmevtyper29_el0, PMEVTYPER29_EL0, "PMEVTYPER29_EL0");
define_pmu_register!(pmevtyper30_el0, PMEVTYPER30_EL0, "PMEVTYPER30_EL0");
pub use pmccfiltr_el0::PMCCFILTR_EL0;
pub use pmccntr_el0::PMCCNTR_EL0;
pub use pmcntenclr_el0::PMCNTENCLR_EL0;
pub use pmcntenset_el0::PMCNTENSET_EL0;
pub use pmevcntr0_el0::PMEVCNTR0_EL0;
pub use pmevcntr10_el0::PMEVCNTR10_EL0;
pub use pmevcntr11_el0::PMEVCNTR11_EL0;
pub use pmevcntr12_el0::PMEVCNTR12_EL0;
pub use pmevcntr13_el0::PMEVCNTR13_EL0;
pub use pmevcntr14_el0::PMEVCNTR14_EL0;
pub use pmevcntr15_el0::PMEVCNTR15_EL0;
pub use pmevcntr16_el0::PMEVCNTR16_EL0;
pub use pmevcntr17_el0::PMEVCNTR17_EL0;
pub use pmevcntr18_el0::PMEVCNTR18_EL0;
pub use pmevcntr19_el0::PMEVCNTR19_EL0;
pub use pmevcntr1_el0::PMEVCNTR1_EL0;
pub use pmevcntr20_el0::PMEVCNTR20_EL0;
pub use pmevcntr21_el0::PMEVCNTR21_EL0;
pub use pmevcntr22_el0::PMEVCNTR22_EL0;
pub use pmevcntr23_el0::PMEVCNTR23_EL0;
pub use pmevcntr24_el0::PMEVCNTR24_EL0;
pub use pmevcntr25_el0::PMEVCNTR25_EL0;
pub use pmevcntr26_el0::PMEVCNTR26_EL0;
pub use pmevcntr27_el0::PMEVCNTR27_EL0;
pub use pmevcntr28_el0::PMEVCNTR28_EL0;
pub use pmevcntr29_el0::PMEVCNTR29_EL0;
pub use pmevcntr2_el0::PMEVCNTR2_EL0;
pub use pmevcntr30_el0::PMEVCNTR30_EL0;
pub use pmevcntr3_el0::PMEVCNTR3_EL0;
pub use pmevcntr4_el0::PMEVCNTR4_EL0;
pub use pmevcntr5_el0::PMEVCNTR5_EL0;
pub use pmevcntr6_el0::PMEVCNTR6_EL0;
pub use pmevcntr7_el0::PMEVCNTR7_EL0;
pub use pmevcntr8_el0::PMEVCNTR8_EL0;
pub use pmevcntr9_el0::PMEVCNTR9_EL0;
pub use pmevtyper0_el0::PMEVTYPER0_EL0;
pub use pmevtyper10_el0::PMEVTYPER10_EL0;
pub use pmevtyper11_el0::PMEVTYPER11_EL0;
pub use pmevtyper12_el0::PMEVTYPER12_EL0;
pub use pmevtyper13_el0::PMEVTYPER13_EL0;
pub use pmevtyper14_el0::PMEVTYPER14_EL0;
pub use pmevtyper15_el0::PMEVTYPER15_EL0;
pub use pmevtyper16_el0::PMEVTYPER16_EL0;
pub use pmevtyper17_el0::PMEVTYPER17_EL0;
pub use pmevtyper18_el0::PMEVTYPER18_EL0;
pub use pmevtyper19_el0::PMEVTYPER19_EL0;
pub use pmevtyper1_el0::PMEVTYPER1_EL0;
pub use pmevtyper20_el0::PMEVTYPER20_EL0;
pub use pmevtyper21_el0::PMEVTYPER21_EL0;
pub use pmevtyper22_el0::PMEVTYPER22_EL0;
pub use pmevtyper23_el0::PMEVTYPER23_EL0;
pub use pmevtyper24_el0::PMEVTYPER24_EL0;
pub use pmevtyper25_el0::PMEVTYPER25_EL0;
pub use pmevtyper26_el0::PMEVTYPER26_EL0;
pub use pmevtyper27_el0::PMEVTYPER27_EL0;
pub use pmevtyper28_el0::PMEVTYPER28_EL0;
pub use pmevtyper29_el0::PMEVTYPER29_EL0;
pub use pmevtyper2_el0::PMEVTYPER2_EL0;
pub use pmevtyper30_el0::PMEVTYPER30_EL0;
pub use pmevtyper3_el0::PMEVTYPER3_EL0;
pub use pmevtyper4_el0::PMEVTYPER4_EL0;
pub use pmevtyper5_el0::PMEVTYPER5_EL0;
pub use pmevtyper6_el0::PMEVTYPER6_EL0;
pub use pmevtyper7_el0::PMEVTYPER7_EL0;
pub use pmevtyper8_el0::PMEVTYPER8_EL0;
pub use pmevtyper9_el0::PMEVTYPER9_EL0;
pub use pmintenclr_el1::PMINTENCLR_EL1;
pub use pmintenset_el1::PMINTENSET_EL1;
pub use pmovsclr_el0::PMOVSCLR_EL0;
pub use pmovsset_el0::PMOVSSET_EL0;
pub use pmselr_el0::PMSELR_EL0;
pub use pmuserenr_el0::PMUSERENR_EL0;
pub use pmxevcntr_el0::PMXEVCNTR_EL0;
pub use pmxevtyper_el0::PMXEVTYPER_EL0;
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/smcr_el2.rs | lib/armv9a/src/regs/smcr_el2.rs | //! SME Control Register - EL2
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub SMCR_EL2 [
/// When FEAT_SME_FA64 is implemented:
/// Controls whether execution of an A64 instruction is
/// considered legal when the PE is in Streaming SVE mode
FA64 OFFSET(31) NUMBITS(1) [],
/// Reserved
RAZWI OFFSET(4) NUMBITS(5) [],
/// Effective Streaming SVE Vector Length (SVL)
LEN OFFSET(0) NUMBITS(4) []
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = SMCR_EL2::Register;
// Use the opcode instead of its register mnemonic
// to pass compilation without SIMD(neon, sve, sme) features in the compile option
//sys_coproc_read_raw!(u64, "SMCR_EL2", "x");
sys_coproc_read_raw!(u64, "S3_4_C1_C2_6", "x");
}
impl Writeable for Reg {
type T = u64;
type R = SMCR_EL2::Register;
//sys_coproc_write_raw!(u64, "SMCR_EL2", "x");
sys_coproc_write_raw!(u64, "S3_4_C1_C2_6", "x");
}
pub const SMCR_EL2: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/zcr_el1.rs | lib/armv9a/src/regs/zcr_el1.rs | //! Realm Management Monitor Configuration Register - EL1
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub ZCR_EL1 [
RAZWI OFFSET(4) NUMBITS(5) [],
LEN OFFSET(0) NUMBITS(4) []
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = ZCR_EL1::Register;
//sys_coproc_read_raw!(u64, "ZCR_EL1", "x");
sys_coproc_read_raw!(u64, "S3_0_C1_C2_0", "x");
}
impl Writeable for Reg {
type T = u64;
type R = ZCR_EL1::Register;
//sys_coproc_write_raw!(u64, "ZCR_EL1", "x");
sys_coproc_write_raw!(u64, "S3_0_C1_C2_0", "x");
}
pub const ZCR_EL1: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/id_aa64pfr1_el1.rs | lib/armv9a/src/regs/id_aa64pfr1_el1.rs | // SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Copyright (c) 2024 by the author(s)
//
// Author(s):
// - Sangwan Kwon <sangwan.kwon@samsung.com>
//! AArch64 Processor Feature Register 1 - EL1
//!
//! Provides additional information about implemented PE features in AArch64 state.
use tock_registers::{interfaces::Readable, register_bitfields};
register_bitfields! {u64,
pub ID_AA64PFR1_SME_EL1 [
/// Support for the Scalable Matrix Extension.
SME OFFSET(24) NUMBITS(4) [],
/// Support for the Memory Tagging Extension.
MTE OFFSET(8) NUMBITS(4) [],
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = ID_AA64PFR1_SME_EL1::Register;
sys_coproc_read_raw!(u64, "ID_AA64PFR1_EL1", "x");
}
pub const ID_AA64PFR1_SME_EL1: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/mdcr_el2.rs | lib/armv9a/src/regs/mdcr_el2.rs | //! Realm Management Monitor Configuration Register - EL2
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub MDCR_EL2 [
MTPME OFFSET(28) NUMBITS(1) [],
HCCD OFFSET(23) NUMBITS(1) [],
HPMD OFFSET(17) NUMBITS(1) [],
TDA OFFSET(9) NUMBITS(1) [],
TPM OFFSET(6) NUMBITS(1) [],
TPMCR OFFSET(5) NUMBITS(1) [],
HPMN OFFSET(0) NUMBITS(5) [],
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = MDCR_EL2::Register;
sys_coproc_read_raw!(u64, "MDCR_EL2", "x");
}
impl Writeable for Reg {
type T = u64;
type R = MDCR_EL2::Register;
sys_coproc_write_raw!(u64, "MDCR_EL2", "x");
}
pub const MDCR_EL2: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/macros.rs | lib/armv9a/src/regs/macros.rs | // SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Copyright (c) 2018-2023 by the author(s)
//
// Author(s):
// - Andre Richter <andre.o.richter@gmail.com>
macro_rules! __read_raw {
($width:ty, $asm_instr:tt, $asm_reg_name:tt, $asm_width:tt) => {
/// Reads the raw bits of the CPU register.
#[inline]
fn get(&self) -> $width {
match () {
#[cfg(target_arch = "aarch64")]
() => {
let reg;
unsafe {
core::arch::asm!(concat!($asm_instr, " {reg:", $asm_width, "}, ", $asm_reg_name), reg = out(reg) reg, options(nomem, nostack));
}
reg
}
#[cfg(not(target_arch = "aarch64"))]
() => unimplemented!(),
}
}
};
}
macro_rules! __write_raw {
($width:ty, $asm_instr:tt, $asm_reg_name:tt, $asm_width:tt) => {
/// Writes raw bits to the CPU register.
#[cfg_attr(not(target_arch = "aarch64"), allow(unused_variables))]
#[inline]
fn set(&self, value: $width) {
match () {
#[cfg(target_arch = "aarch64")]
() => {
unsafe {
core::arch::asm!(concat!($asm_instr, " ", $asm_reg_name, ", {reg:", $asm_width, "}"), reg = in(reg) value, options(nomem, nostack))
}
}
#[cfg(not(target_arch = "aarch64"))]
() => unimplemented!(),
}
}
};
}
/// Raw read from system coprocessor registers.
macro_rules! sys_coproc_read_raw {
($width:ty, $asm_reg_name:tt, $asm_width:tt) => {
__read_raw!($width, "mrs", $asm_reg_name, $asm_width);
};
}
/// Raw write to system coprocessor registers.
macro_rules! sys_coproc_write_raw {
($width:ty, $asm_reg_name:tt, $asm_width:tt) => {
__write_raw!($width, "msr", $asm_reg_name, $asm_width);
};
}
#[macro_export]
/// Raw read from (ordinary) registers.
macro_rules! read_raw {
($width:ty, $asm_reg_name:tt, $asm_width:tt) => {
__read_raw!($width, "mov", $asm_reg_name, $asm_width);
};
}
#[macro_export]
/// Raw write to (ordinary) registers.
macro_rules! write_raw {
($width:ty, $asm_reg_name:tt, $asm_width:tt) => {
__write_raw!($width, "mov", $asm_reg_name, $asm_width);
};
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/id_aa64zfr0_el1.rs | lib/armv9a/src/regs/id_aa64zfr0_el1.rs | // SPDX-License-Identifier: Apache-2.0 OR MIT
//
//! AArch64 Processor Feature Register 1 - EL1
//!
//! Provides additional information about implemented PE features in AArch64 state.
use tock_registers::{interfaces::Readable, register_bitfields};
register_bitfields! {u64,
pub ID_AA64ZFR0_EL1 [
/// Support for SVE FP64 double-precision floating-point matrix multiplication instructions
F64MM OFFSET(56) NUMBITS(4) [],
/// Support for the SVE FP32 single-precision floating-point matrix multiplication instruction
F32MM OFFSET(52) NUMBITS(4) [],
/// Support for SVE Int8 matrix multiplication instructions
I8MM OFFSET(44) NUMBITS(4) [],
/// Support for SVE SM4 instructions
SM4 OFFSET(40) NUMBITS(4) [],
/// Support for the SVE SHA3 instructions
SHA3 OFFSET(32) NUMBITS(4) [],
/// Support for SVE BFloat16 instructions
BF16 OFFSET(20) NUMBITS(4) [],
/// Support for SVE bit permute instructions
BitPerm OFFSET(16) NUMBITS(4) [],
/// Support for SVE AES instructions
AES OFFSET(4) NUMBITS(4) [],
/// Support for SVE
SVEver OFFSET(0) NUMBITS(4) [],
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = ID_AA64ZFR0_EL1::Register;
sys_coproc_read_raw!(u64, "ID_AA64PFR1_EL1", "x");
}
pub const ID_AA64ZFR0_EL1: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/zcr_el2.rs | lib/armv9a/src/regs/zcr_el2.rs | //! Realm Management Monitor Configuration Register - EL2
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub ZCR_EL2 [
RAZWI OFFSET(4) NUMBITS(5) [],
LEN OFFSET(0) NUMBITS(4) []
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = ZCR_EL2::Register;
//sys_coproc_read_raw!(u64, "ZCR_EL2", "x");
sys_coproc_read_raw!(u64, "S3_4_C1_C2_0", "x");
}
impl Writeable for Reg {
type T = u64;
type R = ZCR_EL2::Register;
//sys_coproc_write_raw!(u64, "ZCR_EL2", "x");
sys_coproc_write_raw!(u64, "S3_4_C1_C2_0", "x");
}
pub const ZCR_EL2: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/armv9a/src/regs/svcr.rs | lib/armv9a/src/regs/svcr.rs | //! Streaming Vector Control Register
//!
//! Controls Streaming SVE mode and SME behavior.
use tock_registers::{
interfaces::{Readable, Writeable},
register_bitfields,
};
register_bitfields! {u64,
pub SVCR [
/// Enables SME ZA storage.
ZA OFFSET(1) NUMBITS(1) [],
/// Enables Streaming SVE mode.
SM OFFSET(0) NUMBITS(1) [],
]
}
pub struct Reg;
impl Readable for Reg {
type T = u64;
type R = SVCR::Register;
// Use the opcode instead of its register mnemonic
// to pass compilation without SIMD(neon, sve, sme) features in the compile option
//sys_coproc_read_raw!(u64, "SVCR", "x");
sys_coproc_read_raw!(u64, "S3_3_C4_C2_2", "x");
}
impl Writeable for Reg {
type T = u64;
type R = SVCR::Register;
//sys_coproc_write_raw!(u64, "SVCR", "x");
sys_coproc_write_raw!(u64, "S3_3_C4_C2_2", "x");
}
pub const SVCR: Reg = Reg {};
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/safe-abstraction/src/lib.rs | lib/safe-abstraction/src/lib.rs | #![warn(rust_2018_idioms)]
#![deny(warnings)]
#![no_std]
//! # Safe Abstraction Crate
//!
//! The `safe_abstraction` crate is a library designed
//! to facilitate safer abstraction over `unsafe` code.
//!
//! Its primary goal is to enhance the safety of `unsafe` code
//! by providing data structures and functions that minimize
//! the need for direct `unsafe` code usage,
//! and by offering traits for automating
//! and explicitly marking parts of `unsafe` code
//! that require developer intervention.
//!
//! ## Features
//!
//! - **Encapsulation of Unsafe Code**: Offers a way to safely abstract `unsafe` operations,
//! allowing for lower-level operations like memory access to be performed more safely.
//!
//! - **Runtime Safety Checks**: Provides methods to perform crucial safety checks at runtime,
//! such as verifying if a pointer is null and checking whether a pointer is properly aligned.
//! These checks happen when the methods are called during the execution of a program.
//!
//! - **Compile-Time Type Safety Checks**: Enforces certain safety guarantees at compile time.
//! For example, the use of Rust's type system can ensure that only pointers
//! to types with known sizes are used, leveraging the `Sized` trait bound.
//!
//! - **Developer-Driven Safety Verification**: Introduces traits that allow developers
//! to explicitly mark parts of `unsafe` code that still require manual safety guarantees,
//! making it clear which parts of the code need careful review.
pub mod raw_ptr {
//! # Raw Pointer Safety Abstraction Module
//!
//! This module provides a set of traits designed
//! to facilitate safe abstraction over raw pointers.
//!
//! Raw pointers (`*const T` and `*mut T`) offer great power
//! but come with great responsibility: they are unsafe by nature
//! and require careful handling to ensure safety.
//!
//! The `raw_ptr` module introduces traits
//! that enforce checks on raw pointers
//! to ensure that their usage adheres
//! to Rust’s safety guarantees.
//!
//! ## Traits Overview
//! - `RawPtr`: Ensures that the size of the structure
//! pointed to by the raw pointer is determined at compile time,
//! enabling safe memory operations.
//!
//! - `SafetyChecked`: Implements checks to ensure that the raw pointer
//! is not null and properly aligned.
//!
//! - `SafetyAssured`: Provides guarantees that the instance
//! pointed to by the raw pointer is properly initialized,
//! adheres to Rust's ownership rules.
pub trait RawPtr: Sized {
/// # Safety
///
/// When calling this method, you have to ensure that all of the following is true:
///
/// * The pointer must point to an initialized instance of `T`.
///
/// * You must enforce Rust's aliasing rules
unsafe fn as_ref<'a, T: RawPtr>(addr: usize) -> &'a T {
&*(addr as *const T)
}
/// # Safety
///
/// When calling this method, you have to ensure that all of the following is true:
///
/// * The pointer must point to an initialized instance of `T`.
///
/// * You must enforce Rust's aliasing rules
unsafe fn as_mut<'a, T: RawPtr>(addr: usize) -> &'a mut T {
&mut *(addr as *mut T)
}
fn addr(&self) -> usize {
let ptr: *const Self = self;
ptr as usize
}
}
/// `SafetyChecked` Trait
///
/// This trait signifies that certain safety checks
/// can be automatically performed by the code itself.
///
/// Implementing this trait indicates that the associated functionality
/// has been designed to undergo automatic safety verification processes,
/// minimizing the need for manual intervention.
///
/// It is particularly useful for encapsulating operations
/// that can be safely abstracted away from direct `unsafe` code usage.
///
/// Types implementing `SafetyChecked` should ensure
/// that all potential safety risks are either inherently
/// mitigated by the implementation or are automatically checkable at compile or run time.
pub trait SafetyChecked: RawPtr {
fn is_not_null(&self) -> bool {
let ptr: *const Self = self;
!ptr.is_null()
}
fn is_aligned(&self) -> bool {
self.addr() % core::mem::align_of::<usize>() == 0
}
}
/// `SafetyAssured` Trait
///
/// The `SafetyAssured` trait is intended
/// to be used as a marker for code sections
/// where safety cannot be automatically checked
/// or guaranteed by the compiler or runtime environment.
/// Instead, the safety of operations marked with this trait relies on manual checks
/// and guarantees provided by the developer.
///
/// Implementing `SafetyAssured` serves
/// as a declaration that the developer has manually reviewed
/// the associated operations and is confident in their safety,
/// despite the inability to enforce these guarantees automatically.
/// It is a commitment to adhering to Rust's safety principles
/// while working within the necessary confines of `unsafe` code.
pub trait SafetyAssured {
/// Checks if the instance is properly initialized.
///
/// This method should verify that all necessary initializations
/// for the instance have been completed.
/// For example, it should check if memory allocations have been made
/// and if they are filled with appropriate values,
/// or if all fields of a struct have been initialized to their expected default values.
/// Proper initialization is crucial to prevent issues such as use of uninitialized memory.
fn is_initialized(&self) -> bool;
/// Checks whether ownership rules are upheld for this instance,
/// with a particular focus on instances that originate from raw pointers.
///
/// This method evaluates the adherence to Rust's ownership model,
/// ensuring safe resource management while preventing issues
/// like use-after-free, data races, and unauthorized mutable aliasing.
/// A return value of `true` indicates strict compliance with these rules.
///
/// However, it is crucial to return `false` under the following conditions:
/// - The instance is derived from a raw pointer, and operates in a multi-core or multi-threaded
/// context without appropriate synchronization mechanisms (e.g., mutexes). This situation
/// significantly increases the risk of unsafe access patterns, such as data races or
/// simultaneous mutable aliasing, that violate Rust’s guarantees on memory safety.
/// - Any other detected violation of ownership rules, such as incorrect lifecycle management
/// leading to potential dangling references or use-after-free scenarios.
///
/// By mandating the use of synchronization tools in concurrent environments for instances
/// originating from raw pointers, this function underscores the necessity of diligent safety
/// practices to uphold Rust's safety guarantees, alerting developers to areas of concern
/// that require attention.
fn verify_ownership(&self) -> bool;
}
/// Enumerates the types of errors that can occur in the `assume_safe` function.
#[derive(Debug)]
pub enum Error {
/// Indicates a failure in safety checks (SafetyChecked trait).
SafetyCheckFailed,
/// Indicates a failure in assurance checks (SafetyAssured trait).
AssuranceCheckFailed,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match *self {
Error::SafetyCheckFailed => write!(f, "Safety check failed"),
Error::AssuranceCheckFailed => write!(f, "Assurance check failed"),
}
}
}
impl core::error::Error for Error {}
/// Attempts to create a `SafetyAssumed` instance from a address.
///
/// This function checks both `SafetyChecked` and `SafetyAssured` traits' conditions
/// to ensure that the target at the given address adheres to safety guarantees.
/// If all checks pass, it returns a `SafetyAssumed` instance encapsulating the address,
/// signifying that interactions with the target can be safely performed.
/// Otherwise, it returns `None`, indicating that safety guarantees cannot be met.
///
/// # Arguments
///
/// * `addr` - The raw address of the target instance to be safely accessed.
///
/// # Returns
///
/// Returns `Ok(SafetyAssumed)` if all safety checks are satisfied, or `Error`
pub fn assume_safe<T: SafetyChecked + SafetyAssured>(
addr: usize,
) -> Result<SafetyAssumed<T>, Error> {
let ptr = addr as *const T;
// Safety: This cast from a raw pointer to a reference is considered safe
// because it is used solely for the purpose of verifying alignment and range,
// without actually dereferencing the pointer.
let ref_ = unsafe { &*(ptr) };
if !ref_.is_not_null() || !ref_.is_aligned() {
return Err(Error::SafetyCheckFailed);
}
if !ref_.is_initialized() || !ref_.verify_ownership() {
return Err(Error::AssuranceCheckFailed);
}
Ok(SafetyAssumed {
addr,
assume_init: false,
_phantom: core::marker::PhantomData,
})
}
pub fn assume_safe_uninit_with<T: SafetyChecked + SafetyAssured>(
addr: usize,
value: T,
) -> Result<SafetyAssumed<T>, Error> {
let ptr = addr as *const T;
// Safety: This cast from a raw pointer to a reference is considered safe
// because it is used solely for the purpose of verifying alignment and range,
// without actually dereferencing the pointer.
let ref_ = unsafe { &*(ptr) };
if !ref_.is_not_null() || !ref_.is_aligned() {
return Err(Error::SafetyCheckFailed);
}
if !ref_.verify_ownership() {
return Err(Error::AssuranceCheckFailed);
}
Ok(SafetyAssumed::new_maybe_uninit_with(addr, value))
}
/// Represents a target instance that has passed all necessary safety checks.
///
/// An instance of `SafetyAssumed` signifies that it is safe to interact with the target
/// through raw pointers, as all required safety conditions
/// (checked by `SafetyChecked` and assured by `SafetyAssured`) have been met.
/// This structure acts as a safe wrapper,
/// allowing for controlled access to the underlying data
/// while upholding Rust's safety guarantees.
///
/// # Fields
///
/// * `addr` - The raw address of the safely assumed target instance.
/// * `_phantom` - A `PhantomData` used to associate generic type `T` with this struct
/// without storing any data of type `T`. This helps manage type invariance
/// and ensure that the Rust compiler accounts for `T` in its type checking.
pub struct SafetyAssumed<T: SafetyChecked + SafetyAssured> {
addr: usize,
assume_init: bool,
_phantom: core::marker::PhantomData<T>,
}
impl<T> SafetyAssumed<T>
where
T: SafetyChecked + SafetyAssured,
{
pub fn new_maybe_uninit_with(addr: usize, value: T) -> Self {
unsafe {
let src: core::mem::MaybeUninit<T> = core::mem::MaybeUninit::new(value);
let src = &src as *const core::mem::MaybeUninit<T>;
let dst = addr as *mut core::mem::MaybeUninit<T>;
core::ptr::copy_nonoverlapping(src, dst, 1);
}
Self {
addr,
assume_init: true,
_phantom: core::marker::PhantomData,
}
}
}
impl<T> AsRef<T> for SafetyAssumed<T>
where
T: SafetyChecked + SafetyAssured,
{
/// Safely returns a mutable reference to the instance of `T`.
///
/// # Safety
/// Similar to `as_ref`, this function assumes that all required safety checks
/// are in place. Mutable access is granted under the presumption of exclusive ownership
/// and proper synchronization when accessed in multi-threaded contexts.
fn as_ref(&self) -> &T {
unsafe {
if self.assume_init {
let ptr = self.addr as *mut core::mem::MaybeUninit<T>;
(*ptr).assume_init_ref()
} else {
T::as_ref(self.addr)
}
}
}
}
impl<T> AsMut<T> for SafetyAssumed<T>
where
T: SafetyChecked + SafetyAssured,
{
/// Safely returns a mutable reference to the instance of `T`.
///
/// # Safety
/// Similar to `as_ref`, this function assumes that all required safety checks
/// are in place. Mutable access is granted under the presumption of exclusive ownership
/// and proper synchronization when accessed in multi-threaded contexts.
fn as_mut(&mut self) -> &mut T {
unsafe {
if self.assume_init {
let ptr = self.addr as *mut core::mem::MaybeUninit<T>;
(*ptr).assume_init_mut()
} else {
T::as_mut(self.addr)
}
}
}
}
impl<T> core::ops::Deref for SafetyAssumed<T>
where
T: SafetyChecked + SafetyAssured,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl<T> core::ops::DerefMut for SafetyAssumed<T>
where
T: SafetyChecked + SafetyAssured,
{
fn deref_mut(&mut self) -> &mut T {
self.as_mut()
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/safe-abstraction/examples/raw-ptr.rs | lib/safe-abstraction/examples/raw-ptr.rs | use safe_abstraction::raw_ptr::{assume_safe, RawPtr, SafetyAssured, SafetyChecked};
struct MyStruct {
data: i32,
}
impl MyStruct {
fn new() -> Self {
Self { data: 0 }
}
fn set(&mut self, data: i32) {
self.data = data;
}
fn print(&self) {
println!("Data: {:X}", self.data);
}
}
/*
* To apply Safe Abstraction, three traits must be implemented.
*
* These traits serve to either veify or proof that the safety rules are checked.
*/
const ASSUMED_SAFE_BY_DEVELOPER: bool = true;
impl RawPtr for MyStruct {}
impl SafetyChecked for MyStruct {}
// Assume that the developer has assured it.
impl SafetyAssured for MyStruct {
fn is_initialized(&self) -> bool {
ASSUMED_SAFE_BY_DEVELOPER
}
fn verify_ownership(&self) -> bool {
ASSUMED_SAFE_BY_DEVELOPER
}
}
fn mock_get_addr_of_instance_from_external() -> usize {
let object = Box::new(MyStruct::new());
let ptr = Box::into_raw(object);
ptr as usize
}
fn without_safe_abstraction() {
// This approach works, but consider the potential side effects
// if the implementation of the mock function is not verifiable,
// or if the developer uses `unsafe` solely for functionality
// without due consideration for Memory Safety.
//
// Imagine the consequences of neglecting Memory Safety in pursuit of mere operation.
let addr = mock_get_addr_of_instance_from_external();
unsafe {
let raw_ptr = &mut *(addr as *mut MyStruct);
raw_ptr.set(0xABC);
raw_ptr.print();
}
}
fn with_safe_abstraction() {
// We can apply Safe Abstraction for accessing instances
// that have been checked and assured by three traits.
// This approach encapsulates unsafe code
// but still allows for analysis of the behavior at the MIR stage.
//
// Additioanlly, in client crates, the `#![forbid(unsafe_code)]` attribute can be used
// to prohibit the use of unsafe code.
let addr = mock_get_addr_of_instance_from_external();
let mut my_struct = assume_safe::<MyStruct>(addr).expect("Memory Safety Violation!");
my_struct.set(0xDEF);
my_struct.print();
}
fn main() {
without_safe_abstraction();
with_safe_abstraction();
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/io/src/lib.rs | lib/io/src/lib.rs | #![no_std]
#![warn(rust_2018_idioms)]
extern crate alloc;
pub mod error;
use alloc::boxed::Box;
pub use error::{Error, ErrorKind};
use spinning_top::{Spinlock, SpinlockGuard};
pub type Result<T> = core::result::Result<T, Error>;
pub trait Device {
fn initialize(&mut self) -> Result<()>;
fn initialized(&self) -> bool;
}
pub trait Write {
fn write_all(&mut self, buf: &[u8]) -> Result<()>;
}
pub trait ConsoleWriter: Device + Write + Send {}
pub struct Stdout {
device: Option<Box<dyn ConsoleWriter>>,
}
impl Stdout {
pub const fn new() -> Self {
Self { device: None }
}
pub fn attach(&mut self, mut device: Box<dyn ConsoleWriter>) -> Result<()> {
if !device.initialized() {
device.initialize()?;
}
self.device.replace(device);
Ok(())
}
}
impl Write for Stdout {
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
self.device
.as_mut()
.map(|dev| dev.write_all(buf))
.unwrap_or(Err(Error::new(ErrorKind::NotConnected)))
}
}
pub fn stdout() -> SpinlockGuard<'static, Stdout> {
static STDOUT: Spinlock<Stdout> = Spinlock::new(Stdout::new());
STDOUT.lock()
}
#[cfg(test)]
pub mod test {
extern crate alloc;
use super::{ConsoleWriter, Device, Result, Stdout, Write};
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::cell::RefCell;
pub struct MockDevice {
buffer: RefCell<Vec<u8>>,
ready: bool,
}
impl MockDevice {
pub const fn new() -> Self {
MockDevice {
buffer: RefCell::new(Vec::new()),
ready: false,
}
}
pub fn output(&self) -> String {
String::from_utf8(self.buffer.borrow().to_vec()).unwrap()
}
pub fn clear(&mut self) {
self.buffer.borrow_mut().clear()
}
}
impl Device for MockDevice {
fn initialize(&mut self) -> Result<()> {
self.ready = true;
Ok(())
}
fn initialized(&self) -> bool {
self.ready
}
}
impl Write for MockDevice {
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
self.buffer.borrow_mut().extend_from_slice(buf);
Ok(())
}
}
impl ConsoleWriter for MockDevice {}
#[test]
fn attach_and_ready() {
let mock = Box::new(MockDevice::new());
let mock_ptr = mock.as_ref() as *const MockDevice;
let mut stdout = Stdout::new();
assert!(!mock.initialized());
stdout.attach(mock).ok().unwrap();
assert!(unsafe { (*mock_ptr).initialized() });
}
#[test]
fn write() {
let mock = Box::new(MockDevice::new());
let mock_ptr = mock.as_ref() as *const MockDevice;
let mut stdout = Stdout::new();
stdout.attach(mock).ok().unwrap();
stdout.write_all("Hello ".as_bytes()).ok().unwrap();
stdout.write_all("World!".as_bytes()).ok().unwrap();
assert_eq!(unsafe { (*mock_ptr).output() }, "Hello World!");
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/io/src/error.rs | lib/io/src/error.rs | #[derive(Clone, Copy, Debug, PartialEq)]
pub enum ErrorKind {
NotConnected,
AlreadyExists,
Unsupported,
Other,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}
impl Error {
pub fn new(kind: ErrorKind) -> Error {
Error { kind }
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
}
impl From<Error> for &'static str {
fn from(error: Error) -> Self {
match error.kind() {
ErrorKind::NotConnected => "Communication error: NotConnected",
ErrorKind::AlreadyExists => "Communication error: AlreadyExists",
ErrorKind::Unsupported => "Communication error: Unsupported",
ErrorKind::Other => "Communication error: Other",
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/autopadding/src/lib.rs | lib/autopadding/src/lib.rs | #![no_std]
pub extern crate paste;
// Unfortunately, [$t: ty; $size: expr] does not matches with array type...
// instead, matches all integer primitves here.
#[macro_export]
macro_rules! type_check_and_init {
(u8) => {
0
};
(i8) => {
0
};
(u16) => {
0
};
(i16) => {
0
};
(u32) => {
0
};
(i32) => {
0
};
(u64) => {
0
};
(i64) => {
0
};
(u128) => {
0
};
(i128) => {
0
};
(usize) => {
0
};
(isize) => {
0
};
($t:ty) => {
[0; <$t>::LEN]
};
}
#[macro_export]
macro_rules! pad_field_and_impl_default {
// entry point.
(@root $(#[$attr_struct:meta])* $vis:vis $name:ident { $($input:tt)* } ) => {
pad_field_and_impl_default!(
@munch (
$($input)*
) -> {
$vis struct $(#[$attr_struct])* $name
}
);
};
// TODO: Remove the zero-sized paddings added where no padding is required
(@guard ($current_offset:expr) -> {$(#[$attr:meta])* $vis:vis struct $name:ident $(($amount:expr, $vis_field:vis $id:ident: $ty:ty))*}) => {
$crate::paste::paste! {
#[repr(C)]
#[derive(Clone, Copy)]
$(#[$attr])* $vis struct $name { $($vis_field $id: $ty, [<_pad $id>]: [u8;$amount]),* }
}
$crate::paste::paste!{
impl Default for $name {
fn default() -> Self {
Self {
$($id: type_check_and_init!($ty), [<_pad $id>]: [0;$amount]),*
}
}
}
}
};
// Print the struct once all fields have been munched.
(@munch
(
$(#[$attr:meta])*
$offset_start:literal $vis:vis $field:ident: $ty:ty,
$(#[$attr_next:meta])*
$offset_end:literal => @END,
)
-> {$($output:tt)*}
) => {
pad_field_and_impl_default!(
@guard (
0
) -> {
$($output)*
($offset_end - $offset_start - core::mem::size_of::<$ty>(), $vis $field: $ty)
}
);
};
// Munch padding.
(@munch
(
$(#[$attr:meta])*
$offset_start:literal $vis:vis $field:ident: $ty:ty,
$(#[$attr_next:meta])*
$offset_end:literal $vis_next:vis $field_next:ident: $ty_next:ty,
$($after:tt)*
)
-> {$($output:tt)*}
) => {
pad_field_and_impl_default!(
@munch (
$(#[$attr_next])*
$offset_end $vis_next $field_next: $ty_next,
$($after)*
) -> {
$($output)*
($offset_end - $offset_start - core::mem::size_of::<$ty>(), $vis $field: $ty)
}
);
};
}
#[macro_export]
macro_rules! pad_struct_and_impl_default {
(
$(#[$attr:meta])* $vis:vis struct $name:ident {$($fields:tt)*}
) => {
$crate::pad_field_and_impl_default!(@root $(#[$attr])* $vis $name { $($fields)* } );
};
}
pub trait ArrayLength {
const LEN: usize;
}
impl<T, const LENGTH: usize> ArrayLength for [T; LENGTH] {
const LEN: usize = LENGTH;
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/page.rs | lib/vmsa/src/page.rs | use super::address::{align_down, Address};
use core::marker::PhantomData;
/// A generic interface to support all possible page sizes.
//
/// This is defined as a subtrait of Copy to enable #[derive(Clone, Copy)] for Page.
/// Currently, deriving implementations for these traits only works if all dependent types implement it as well.
pub trait PageSize: Copy {
/// The page size in bytes.
const SIZE: usize;
/// The page table level at which a page of this size is mapped
const MAP_TABLE_LEVEL: usize;
/// Any extra flag that needs to be set to map a page of this size.
const MAP_EXTRA_FLAG: u64;
}
/// A memory page of the size given by S.
#[derive(Clone, Copy)]
pub struct Page<S: PageSize, A: Address> {
addr: A,
size: PhantomData<S>,
}
impl<S: PageSize, A: Address> Page<S, A> {
/// Return the stored virtual address.
pub fn address(&self) -> A {
self.addr
}
/// Flushes this page from the TLB of this CPU.
pub fn flush_from_tlb(&self) {
unimplemented!()
}
/// Returns a Page including the given virtual address.
/// That means, the address is rounded down to a page size boundary.
pub fn including_address(addr: A) -> Self {
Self {
addr: align_down(addr.into(), S::SIZE).into(),
size: PhantomData,
}
}
/// Returns a PageIter to iterate from the given first Page to the given last Page (inclusive).
pub fn range(first: Self, last: Self) -> PageIter<S, A> {
assert!(first.addr <= last.addr);
PageIter {
current: first,
last,
}
}
pub fn range_with_size(addr: A, size: usize) -> PageIter<S, A> {
let first_page = Page::<S, A>::including_address(addr);
let last_page = Page::<S, A>::including_address((addr.into() + size - 1).into());
Page::range(first_page, last_page)
}
}
/// An iterator to walk through a range of pages of size S.
pub struct PageIter<S: PageSize, A: Address> {
current: Page<S, A>,
last: Page<S, A>,
}
impl<S: PageSize, A: Address> Iterator for PageIter<S, A> {
type Item = Page<S, A>;
fn next(&mut self) -> Option<Page<S, A>> {
if self.current.addr <= self.last.addr {
let p = self.current;
self.current.addr += S::SIZE.into();
Some(p)
} else {
None
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/guard.rs | lib/vmsa/src/guard.rs | use core::ops::{Deref, DerefMut};
use spinning_top::SpinlockGuard;
use super::error::Error;
use safe_abstraction::raw_ptr;
/// EntryGuard provides a secure interface to access Entry while holding the corresponding lock.
/// Also, it is used as a means of accessing "content" placed at the address of Entry under the lock.
pub struct EntryGuard<'a, E> {
/// inner type for Entry, which corresponds to Entry::Inner
inner: SpinlockGuard<'a, E>,
/// address that this Entry holds
addr: usize,
/// flags of Entry
#[allow(dead_code)]
flags: u64,
}
impl<'a, E> EntryGuard<'a, E> {
pub fn new(inner: SpinlockGuard<'a, E>, addr: usize, flags: u64) -> Self {
Self { inner, addr, flags }
}
/// content placed at the `addr`. (e.g., Rec, DataPage, ...)
/// access to this content is protected under the entry-level lock that "inner" holds.
/// T is a target struct that `addr` maps to.
pub fn content<T>(&self) -> Result<raw_ptr::SafetyAssumed<T>, Error>
where
T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured,
{
// Note: flag can be used here for validation checks.
// e.g., `if T::FLAGS != self.flags { error }`
// for example of Granule, T::FLAGS is Rd while self.flags at run-time is not Rd.
raw_ptr::assume_safe::<T>(self.addr).or(Err(Error::MmErrorOthers))
}
pub fn content_mut<T>(&mut self) -> Result<raw_ptr::SafetyAssumed<T>, Error>
where
T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured,
{
raw_ptr::assume_safe::<T>(self.addr).or(Err(Error::MmErrorOthers))
}
pub fn new_uninit_with<T>(&mut self, value: T) -> Result<raw_ptr::SafetyAssumed<T>, Error>
where
T: Content + raw_ptr::SafetyChecked + raw_ptr::SafetyAssured,
{
raw_ptr::assume_safe_uninit_with::<T>(self.addr, value).or(Err(Error::MmErrorOthers))
}
}
impl<'a, E> Deref for EntryGuard<'a, E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, E> DerefMut for EntryGuard<'a, E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub trait Content {}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/lib.rs | lib/vmsa/src/lib.rs | #![no_std]
#![allow(incomplete_features)]
#![feature(specialization)]
#![feature(generic_const_exprs)]
#![warn(rust_2018_idioms)]
pub mod address;
pub mod error;
pub mod guard;
pub mod page;
pub mod page_table;
use armv9a::{define_bitfield, define_bits, define_mask};
define_bits!(
RawGPA, // ref. K6.1.2
L0Index[47 - 39],
L1Index[38 - 30],
L2Index[29 - 21],
L3Index[20 - 12]
);
impl From<usize> for RawGPA {
fn from(addr: usize) -> Self {
Self(addr as u64)
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/address.rs | lib/vmsa/src/address.rs | use core::fmt;
use core::ops::{Add, AddAssign, BitAnd, BitOr, Sub, SubAssign};
pub trait Address: Add + AddAssign + Copy + From<usize> + Into<usize> + PartialOrd {}
/// Align address downwards.
///
/// Returns the greatest x with alignment `align` so that x <= addr.
/// The alignment must be a power of 2.
#[inline(always)]
pub fn align_down(addr: usize, align: usize) -> usize {
addr & !(align - 1)
}
/// Align address upwards.
///
/// Returns the smallest x with alignment `align` so that x >= addr.
/// The alignment must be a power of 2.
#[inline(always)]
pub fn align_up(addr: usize, align: usize) -> usize {
let align_mask = align - 1;
if addr & align_mask == 0 {
addr
} else {
(addr | align_mask) + 1
}
}
//TODO Change to proc_macro
#[macro_export]
macro_rules! impl_addr {
($T:tt) => {
impl Add for $T {
type Output = Self;
fn add(self, other: Self) -> Self {
$T(self.0 + other.0)
}
}
impl AddAssign for $T {
fn add_assign(&mut self, other: Self) {
self.0 = self.0 + other.0;
}
}
impl Sub for $T {
type Output = Self;
fn sub(self, other: Self) -> Self {
$T(self.0 - other.0)
}
}
impl SubAssign for $T {
fn sub_assign(&mut self, other: Self) {
self.0 = self.0 - other.0;
}
}
impl BitAnd for $T {
type Output = Self;
fn bitand(self, other: Self) -> Self {
$T(self.0 & other.0)
}
}
impl BitOr for $T {
type Output = Self;
fn bitor(self, other: Self) -> Self {
$T(self.0 | other.0)
}
}
impl<T: Sized> From<*mut T> for $T {
fn from(raw_ptr: *mut T) -> $T {
$T(raw_ptr as usize)
}
}
impl<T: Sized> From<*const T> for $T {
fn from(raw_ptr: *const T) -> $T {
$T(raw_ptr as usize)
}
}
impl From<usize> for $T {
fn from(raw_ptr: usize) -> Self {
$T(raw_ptr)
}
}
impl Into<usize> for $T {
fn into(self) -> usize {
self.0
}
}
impl From<u64> for $T {
fn from(raw_ptr: u64) -> Self {
$T(raw_ptr as usize)
}
}
impl Into<u64> for $T {
fn into(self) -> u64 {
self.0 as u64
}
}
impl $T {
pub fn as_u64(&self) -> u64 {
self.0 as u64
}
pub fn as_usize(&self) -> usize {
self.0
}
pub const fn zero() -> Self {
$T(0)
}
}
impl fmt::Debug for $T {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(stringify!($T))
.field("", &format_args!("{:#016x}", self.0))
.finish()
}
}
impl Address for $T {}
};
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysAddr(usize);
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct VirtAddr(usize);
impl_addr!(VirtAddr);
impl_addr!(PhysAddr);
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/page_table.rs | lib/vmsa/src/page_table.rs | extern crate alloc;
use super::address::{Address, PhysAddr};
use super::error::Error;
use super::guard::EntryGuard;
use super::page::{Page, PageIter, PageSize};
use alloc::alloc::Layout;
use core::marker::PhantomData;
use core::slice::Iter;
// Safety/TODO:
// - As of now, concurrency safety for RTT and Realm page table is achieved by a big lock.
// - If we want to use entry-level locking for a better efficiency, several pieces of codes in this file should be modified accordingly.
pub trait Level {
const THIS_LEVEL: usize;
const TABLE_SIZE: usize;
const TABLE_ALIGN: usize;
const NUM_ENTRIES: usize;
}
pub trait HasSubtable: Level {
type NextLevel;
}
pub trait Entry {
/// Inner represents a inner type encapsulated in Entry (e.g., Inner=u64 for struct Entry<u64>)
type Inner;
fn new() -> Self;
fn is_valid(&self) -> bool;
fn clear(&mut self);
fn pte(&self) -> u64;
fn mut_pte(&mut self) -> &mut Self::Inner;
fn address(&self, level: usize) -> Option<PhysAddr>;
fn set(&mut self, addr: PhysAddr, flags: u64) -> Result<(), Error>;
fn point_to_subtable(&mut self, index: usize, addr: PhysAddr) -> Result<(), Error>;
// returns EntryGuard which allows accessing what's inside Entry while holding a proper lock.
fn lock(&self) -> Result<Option<EntryGuard<'_, Self::Inner>>, Error> {
Err(Error::MmUnimplemented)
}
fn index<L: Level>(addr: usize) -> usize;
// This duplicates with address()
fn as_subtable(&self, _index: usize, level: usize) -> Result<usize, Error> {
match self.address(level) {
Some(addr) => Ok(addr.as_usize()),
_ => Err(Error::MmInvalidAddr),
}
}
fn points_to_table_or_page(&self) -> bool;
}
pub trait MemAlloc {
/// Allocates memory according to the given layout.
///
/// # Safety
///
/// - The `layout` must have a non-zero size.
/// - The caller must ensure that the returned pointer is properly deallocated using `deallocate`.
/// - If allocation fails, a null pointer is returned; the caller must handle this case.
unsafe fn allocate(&self, layout: Layout) -> *mut u8 {
alloc::alloc::alloc(layout)
}
/// Deallocates memory at the given pointer and layout.
///
/// # Safety
///
/// - `ptr` must have been allocated by `allocate` with the same `layout`.
/// - `ptr` must be non-null and properly aligned.
/// - The memory at `ptr` must not have been deallocated already.
unsafe fn deallocate(&self, ptr: *mut u8, layout: Layout) {
alloc::alloc::dealloc(ptr, layout);
}
}
pub struct DefaultMemAlloc {}
impl MemAlloc for DefaultMemAlloc {}
pub struct PageTable<A, L, E: Entry, const N: usize> {
entries: [E; N],
level: PhantomData<L>,
address: PhantomData<A>,
}
impl<A: Address, L: Level, E: Entry, const N: usize> MemAlloc for PageTable<A, L, E, N> {}
impl<A: Address, L: HasSubtable, E: Entry, const N: usize> MemAlloc for PageTable<A, L, E, N> {}
pub trait PageTableMethods<A: Address, L, E: Entry, const N: usize> {
/// Sets multiple page table entries
///
/// (input)
/// guest : an iterator of target guest addresses to modify their page table entry mapping
/// phys : an iterator of target physical addresses to be mapped
/// flags : flags to attach
fn set_pages<S: PageSize>(
&mut self,
guest: PageIter<S, A>,
phys: PageIter<S, PhysAddr>,
flags: u64,
) -> Result<(), Error>;
/// Sets a single page table entry
///
/// (input)
/// guest : a target guest address to modify its page table entry mapping
/// phys : a target physical address to be mapped
/// flags : flags to attach
fn set_page<S: PageSize>(
&mut self,
guest: Page<S, A>,
phys: Page<S, PhysAddr>,
flags: u64,
) -> Result<(), Error>;
/// Traverses page table entries recursively and calls the callback for the lastly reached entry
///
/// (input)
/// guest: a target guest page to translate
/// level: the intended page-table level to reach
/// no_valid_check: (if on) omits a validity check which is irrelevant in stage 2 TTE
/// func : the callback to be processed
///
/// (output)
/// if exists,
/// A tuple of
/// ((EntryGuard), the lastly reached page-table level (usize))
/// else,
/// None
fn entry<
'a,
S: PageSize + 'a,
F: FnMut(&mut E) -> Result<Option<EntryGuard<'_, E::Inner>>, Error>,
>(
&'a mut self,
guest: Page<S, A>,
level: usize,
no_valid_check: bool,
func: F,
) -> Result<(Option<EntryGuard<'_, E::Inner>>, usize), Error>;
/// Traverses page tables from the root and locate the page table at a specific level.
///
/// (input)
/// page: a target page to translate
/// level: the intended page-table level to reach
///
/// (output)
/// if exists,
/// A tuple of
/// (entry array iterartor, the lastly reached page-table level (usize))
/// else,
/// None
fn table_entries<'a, S: PageSize + 'a>(
&'a self,
page: Page<S, A>,
level: usize,
) -> Result<(Iter<'a, E>, usize), Error>;
fn drop(&mut self);
fn unset_page<S: PageSize>(&mut self, guest: Page<S, A>);
}
impl<A: Address, L: Level, E: Entry, const N: usize> PageTable<A, L, E, N> {
pub fn new_in(alloc: &dyn MemAlloc) -> Result<&mut PageTable<A, L, E, N>, Error> {
assert_eq!(N, L::NUM_ENTRIES);
let table = unsafe {
alloc.allocate(Layout::from_size_align(L::TABLE_SIZE, L::TABLE_ALIGN).unwrap())
} as *mut PageTable<A, L, E, N>;
if table as usize == 0 {
return Err(Error::MmAllocFail);
}
unsafe {
for entry in (*table).entries.iter_mut() {
// In general .write is required to avoid attempting to destruct
// the (uninitialized) previous contents of `entry`,
// though for the simple Entry with u64 would have worked using
// (*entry) = E::new();
// See https://github.com/zakarumych/allocator-api2/blob/main/src/stable/boxed.rs#L905
let e = E::new();
core::ptr::copy_nonoverlapping(&e, entry, 1);
core::mem::forget(e);
}
(*table).level = PhantomData::<L>;
(*table).address = PhantomData::<A>;
Ok(&mut *table)
}
}
pub fn new_init_in(
alloc: &dyn MemAlloc,
mut func: impl FnMut(&mut [E; N]),
) -> Result<*mut PageTable<A, L, E, N>, Error> {
assert_eq!(N, L::NUM_ENTRIES);
let table = unsafe {
alloc.allocate(Layout::from_size_align(L::TABLE_SIZE, L::TABLE_ALIGN).unwrap())
} as *mut PageTable<A, L, E, N>;
if table as usize == 0 {
return Err(Error::MmAllocFail);
}
unsafe {
func(&mut (*table).entries);
(*table).level = PhantomData::<L>;
(*table).address = PhantomData::<A>;
}
Ok(table)
}
}
impl<A: Address, L: Level, E: Entry, const N: usize> PageTableMethods<A, L, E, N>
for PageTable<A, L, E, N>
{
fn set_pages<S: PageSize>(
&mut self,
guest: PageIter<S, A>,
phys: PageIter<S, PhysAddr>,
flags: u64,
) -> Result<(), Error> {
let mut phys = phys;
for guest in guest {
let phys = phys.next().unwrap();
match self.set_page(guest, phys, flags) {
Ok(_) => {}
Err(e) => {
return Err(e);
}
}
}
Ok(())
}
default fn set_page<S: PageSize>(
&mut self,
guest: Page<S, A>,
phys: Page<S, PhysAddr>,
flags: u64,
) -> Result<(), Error> {
assert!(L::THIS_LEVEL == S::MAP_TABLE_LEVEL);
let index = E::index::<L>(guest.address().into());
self.entries[index].set(phys.address(), flags | S::MAP_EXTRA_FLAG)
}
default fn entry<
'a,
S: PageSize + 'a,
F: FnMut(&mut E) -> Result<Option<EntryGuard<'_, E::Inner>>, Error>,
>(
&'a mut self,
guest: Page<S, A>,
level: usize,
no_valid_check: bool,
mut func: F,
) -> Result<(Option<EntryGuard<'_, E::Inner>>, usize), Error> {
assert!(L::THIS_LEVEL == S::MAP_TABLE_LEVEL);
if level > S::MAP_TABLE_LEVEL {
return Err(Error::MmInvalidLevel);
}
// TODO: remove the level param out of the entry() and don't check this
if level != L::THIS_LEVEL {
return Err(Error::MmInvalidLevel);
}
// TODO: check if the index is within the total number of entries
let index = E::index::<L>(guest.address().into());
if no_valid_check {
Ok((func(&mut self.entries[index])?, L::THIS_LEVEL))
} else {
match self.entries[index].is_valid() {
true => Ok((func(&mut self.entries[index])?, L::THIS_LEVEL)),
false => Err(Error::MmNoEntry),
}
}
}
default fn table_entries<'a, S: PageSize + 'a>(
&'a self,
_page: Page<S, A>,
_level: usize,
) -> Result<(Iter<'a, E>, usize), Error> {
Ok((self.entries.iter(), L::THIS_LEVEL))
}
default fn drop(&mut self) {
unsafe {
// FIXME: need to use allocator that is used at new_in()
let allocator = DefaultMemAlloc {};
allocator.deallocate(
self as *mut PageTable<A, L, E, N> as *mut u8,
Layout::from_size_align(L::TABLE_SIZE, L::TABLE_ALIGN).unwrap(),
);
}
}
default fn unset_page<S: PageSize>(&mut self, guest: Page<S, A>) {
let index = E::index::<L>(guest.address().into());
if self.entries[index].is_valid() {
let _res = self.entry(guest, S::MAP_TABLE_LEVEL, false, |e| {
e.clear();
Ok(None)
});
}
}
}
/// This overrides default PageTableMethods for PageTables with subtable.
/// (L0Table, L1Table, L2Table)
/// PageTableMethods for L3 Table remains unmodified.
impl<A: Address, L: HasSubtable, E: Entry, const N: usize> PageTableMethods<A, L, E, N>
for PageTable<A, L, E, N>
where
L::NextLevel: Level,
[E; L::NextLevel::NUM_ENTRIES]: Sized,
{
fn entry<
'a,
S: PageSize + 'a,
F: FnMut(&mut E) -> Result<Option<EntryGuard<'_, E::Inner>>, Error>,
>(
&'a mut self,
page: Page<S, A>,
level: usize,
no_valid_check: bool,
mut func: F,
) -> Result<(Option<EntryGuard<'_, E::Inner>>, usize), Error> {
assert!(L::THIS_LEVEL <= S::MAP_TABLE_LEVEL);
if level > S::MAP_TABLE_LEVEL {
return Err(Error::MmInvalidLevel);
}
let index = E::index::<L>(page.address().into());
if no_valid_check {
if L::THIS_LEVEL < level && self.entries[index].points_to_table_or_page() {
// Need to go deeper (recursive)
match self.subtable::<S>(page) {
Ok(subtable) => subtable.entry(page, level, no_valid_check, func),
Err(_e) => Ok((None, L::THIS_LEVEL)),
}
} else {
// The page is either LargePage or HugePage
Ok((func(&mut self.entries[index])?, L::THIS_LEVEL))
}
} else {
match self.entries[index].is_valid() {
true => {
if L::THIS_LEVEL < level && self.entries[index].points_to_table_or_page() {
// Need to go deeper (recursive)
match self.subtable::<S>(page) {
Ok(subtable) => subtable.entry(page, level, no_valid_check, func),
Err(_e) => Ok((None, L::THIS_LEVEL)),
}
} else {
// The page is either LargePage or HugePage
Ok((func(&mut self.entries[index])?, L::THIS_LEVEL))
}
}
false => Err(Error::MmNoEntry),
}
}
}
default fn table_entries<'a, S: PageSize + 'a>(
&'a self,
page: Page<S, A>,
level: usize,
) -> Result<(Iter<'a, E>, usize), Error> {
assert!(L::THIS_LEVEL <= S::MAP_TABLE_LEVEL);
if level > S::MAP_TABLE_LEVEL {
return Err(Error::MmInvalidLevel);
}
if L::THIS_LEVEL < level {
match self.subtable::<S>(page) {
Ok(subtable) => subtable.table_entries(page, level),
Err(_e) => Ok((self.entries.iter(), L::THIS_LEVEL)),
}
} else {
Ok((self.entries.iter(), L::THIS_LEVEL))
}
}
fn set_page<S: PageSize>(
&mut self,
guest: Page<S, A>,
phys: Page<S, PhysAddr>,
flags: u64,
) -> Result<(), Error> {
assert!(L::THIS_LEVEL <= S::MAP_TABLE_LEVEL);
let index = E::index::<L>(guest.address().into());
if L::THIS_LEVEL < S::MAP_TABLE_LEVEL {
// map the page in the subtable (recursive)
let subtable = match self.subtable::<S>(guest) {
Ok(table) => table,
Err(_) => {
let table =
PageTable::<A, L::NextLevel, E, { L::NextLevel::NUM_ENTRIES }>::new_in(
&DefaultMemAlloc {},
)?;
self.entries[index]
.point_to_subtable(index, PhysAddr::from(core::ptr::from_ref(table)))?;
table
}
};
subtable.set_page(guest, phys, flags)
} else if L::THIS_LEVEL == S::MAP_TABLE_LEVEL {
// Map page in this level page table
self.entries[index].set(phys.address(), flags | S::MAP_EXTRA_FLAG)
} else {
Err(Error::MmInvalidLevel)
}
}
fn drop(&mut self) {
for entry in self.entries.iter() {
//if L::THIS_LEVEL < S::MAP_TABLE_LEVEL && entry.points_to_table_or_page() {
// if a table which can have subtables points to a table or a page, it should be a table.
if entry.points_to_table_or_page() {
let subtable_addr = entry.address(L::THIS_LEVEL).unwrap();
let subtable: &mut PageTable<A, L::NextLevel, E, N> = unsafe {
&mut *(subtable_addr.as_usize() as *mut PageTable<A, L::NextLevel, E, N>)
};
subtable.drop();
}
}
unsafe {
let allocator = DefaultMemAlloc {};
allocator.deallocate(
self as *mut PageTable<A, L, E, N> as *mut u8,
Layout::from_size_align(L::TABLE_SIZE, L::TABLE_SIZE).unwrap(),
);
}
}
fn unset_page<S: PageSize>(&mut self, guest: Page<S, A>) {
let index = E::index::<L>(guest.address().into());
if self.entries[index].is_valid() {
let _res = self.entry(guest, S::MAP_TABLE_LEVEL, false, |e| {
e.clear();
Ok(None)
});
}
}
}
impl<A: Address, L: HasSubtable, E: Entry, const N: usize> PageTable<A, L, E, N>
where
L::NextLevel: Level,
{
/// Returns the next subtable for the given page in the page table hierarchy.
fn subtable<S: PageSize>(
&self,
page: Page<S, A>,
) -> Result<&mut PageTable<A, L::NextLevel, E, { L::NextLevel::NUM_ENTRIES }>, Error> {
assert!(L::THIS_LEVEL < S::MAP_TABLE_LEVEL);
let index = E::index::<L>(page.address().into());
if !self.entries[index].points_to_table_or_page() {
return Err(Error::MmSubtableError);
}
match self.entries[index].as_subtable(index, L::THIS_LEVEL) {
Ok(table_addr) => Ok(unsafe {
&mut *(table_addr
as *mut PageTable<A, L::NextLevel, E, { L::NextLevel::NUM_ENTRIES }>)
}),
Err(_) => Err(Error::MmSubtableError),
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/lib/vmsa/src/error.rs | lib/vmsa/src/error.rs | #[derive(Debug, PartialEq)]
pub enum Error {
MmStateError,
MmInvalidAddr,
MmInvalidLevel,
MmNoEntry,
MmAllocFail,
MmRustError,
MmUnimplemented,
MmIsInUse,
MmRefcountError,
MmWrongParentChild,
MmSubtableError,
MmErrorOthers,
}
impl From<Error> for usize {
fn from(err: Error) -> Self {
match err {
Error::MmStateError => 1,
Error::MmInvalidAddr => 2,
Error::MmInvalidLevel => 11,
Error::MmNoEntry => 12,
Error::MmAllocFail => 13,
Error::MmRustError => 14,
Error::MmUnimplemented => 15,
Error::MmIsInUse => 16,
Error::MmRefcountError => 17,
Error::MmWrongParentChild => 18,
Error::MmSubtableError => 19,
Error::MmErrorOthers => 99,
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/realm/rsi-test/src/panic.rs | realm/rsi-test/src/panic.rs | #[panic_handler]
pub fn panic_handler(_info: &core::panic::PanicInfo<'_>) -> ! {
loop {}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/realm/rsi-test/src/stack.rs | realm/rsi-test/src/stack.rs | const STACK_SIZE: usize = 0x1000;
#[no_mangle]
#[link_section = ".stack"]
static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/realm/rsi-test/src/mock.rs | realm/rsi-test/src/mock.rs | use core::arch::asm;
use core::ptr::addr_of;
// TODO:
// Detach rmm-spec(data structures & commands) to newly crate.
// And use it both rmm and realm
const RSI_HOST_CALL: usize = 0xC400_0199;
const CMD_GET_SHARED_BUF: u16 = 1;
const CMD_SUCCESS: u16 = 2;
#[repr(C)]
struct HostCall {
pub imm: u16,
pub padding: u16,
}
static mut HOST_CALL: HostCall = HostCall { imm: 0, padding: 0 };
unsafe fn smc(cmd: usize, arg: [usize; 4]) -> [usize; 8] {
let mut ret: [usize; 8] = [0usize; 8];
asm! {
"smc #0x0",
inlateout("x0") cmd => ret[0],
inlateout("x1") arg[0] => ret[1],
inlateout("x2") arg[1] => ret[2],
inlateout("x3") arg[2] => ret[3],
inlateout("x4") arg[3] => ret[4],
out("x5") ret[5],
out("x6") ret[6],
out("x7") ret[7],
}
ret
}
pub unsafe fn get_ns_buffer() {
// CHECK:
// HOST_CALL is not initialized when use tf-rmm
// HOST_CALL is initialized when use islet-rmm
HOST_CALL.padding = 0;
HOST_CALL.imm = CMD_GET_SHARED_BUF;
let arg = [
addr_of!(HOST_CALL) as *const _ as usize,
HOST_CALL.imm as usize,
0,
0,
];
let _ = smc(RSI_HOST_CALL, arg);
}
pub unsafe fn exit_to_host() {
HOST_CALL.imm = CMD_SUCCESS;
let arg = [
addr_of!(HOST_CALL) as *const _ as usize,
HOST_CALL.imm as usize,
0,
0,
];
let _ = smc(RSI_HOST_CALL, arg);
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/realm/rsi-test/src/main.rs | realm/rsi-test/src/main.rs | #![no_std]
#![no_main]
#![feature(asm_const)]
#![warn(rust_2018_idioms)]
mod entry;
mod mock;
mod panic;
mod stack;
#[no_mangle]
pub unsafe fn main() -> ! {
mock::get_ns_buffer();
mock::exit_to_host();
loop {}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/realm/rsi-test/src/entry.rs | realm/rsi-test/src/entry.rs | use core::ptr::addr_of_mut;
#[link_section = ".head.text"]
#[no_mangle]
unsafe extern "C" fn _entry() -> ! {
core::arch::asm!(
"
ldr x0, =__STACK_END__
mov sp, x0
bl setup
1:
bl main
b 1b",
options(noreturn)
)
}
#[no_mangle]
unsafe fn setup() {
extern "C" {
static mut __BSS_START__: usize;
static mut __BSS_SIZE__: usize;
}
clear_bss(addr_of_mut!(__BSS_START__), addr_of_mut!(__BSS_SIZE__));
}
unsafe fn clear_bss(mut sbss: *mut usize, ebss: *mut usize) {
while sbss < ebss {
core::ptr::write_volatile(sbss, core::mem::zeroed());
sbss = sbss.offset(1);
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/build.rs | sdk/build.rs | extern crate cbindgen;
use std::env;
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let mut config: cbindgen::Config = Default::default();
config.header = Some(
"/*
* Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the \"License\");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an \"AS IS\" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the language governing permissions and
* limitations under the License
*/"
.to_string(),
);
config.pragma_once = true;
config.documentation = true;
config.documentation_style = cbindgen::DocumentationStyle::Cxx;
config.export.include = vec!["islet_status_t".to_string()];
config.enumeration.enum_class = false;
cbindgen::Builder::new()
.with_crate(crate_dir)
.with_config(config)
.generate()
.expect("Unable to generate bindings.")
.write_to_file("include/islet.h");
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/config.rs | sdk/src/config.rs | pub const TOKEN_COUNT: u64 = 2;
pub const TOKEN_PLAT: u16 = 44234;
pub const TOKEN_REALM: u16 = 44241;
pub const CLAIM_COUNT_REALM_TOKEN: usize = 7;
pub const CLAIM_COUNT_PLATFORM_TOKEN: usize = 8;
pub const CLAIM_COUNT_SW_COMPONENT: usize = 4;
pub const TAG_CCA_TOKEN: u64 = 399;
pub const TAG_COSE_SIGN1: u64 = 18;
pub const TAG_REALM_CHALLENGE: u16 = 10;
pub const TAG_REALM_PERSONALIZATION_VALUE: u16 = 44235;
pub const TAG_REALM_HASH_ALGO_ID: u16 = 44240;
pub const TAG_REALM_PUB_KEY_HASH_ALGO_ID: u16 = 44236;
pub const TAG_REALM_PUB_KEY: u16 = 44237;
pub const TAG_REALM_INITIAL_MEASUREMENT: u16 = 44238;
pub const TAG_REALM_EXTENTIBLE_MEASUREMENTS: u16 = 44239;
pub const TAG_PLAT_CHALLENGE: u16 = 10;
pub const TAG_PLAT_VERIFICATION_SERVICE: u16 = 2400;
pub const TAG_PLAT_PROFILE: u16 = 265;
pub const TAG_PLAT_INSTANCE_ID: u16 = 256;
pub const TAG_PLAT_IMPLEMENTATION_ID: u16 = 2396;
pub const TAG_PLAT_SECURITY_LIFECYCLE: u16 = 2395;
pub const TAG_PLAT_CONFIGURATION: u16 = 2401;
pub const TAG_PLAT_HASH_ALGO_ID: u16 = 2402;
pub const TAG_PLAT_SW_COMPONENTS: u16 = 2399;
pub const TAG_UNASSIGINED: u16 = 0;
pub const STR_REALM_SIGNATURE: &str = "Realm Signature";
pub const STR_PLAT_SIGNATURE: &str = "Platform Signature";
pub const STR_USER_DATA: &str = "User data";
pub const STR_REALM_CHALLENGE: &str = "Realm challenge";
pub const STR_REALM_PERSONALIZATION_VALUE: &str = "Realm personalization value";
pub const STR_REALM_HASH_ALGO_ID: &str = "Realm hash algo id";
pub const STR_REALM_PUB_KEY_HASH_ALGO_ID: &str = "Realm public key hash algo id";
pub const STR_REALM_PUB_KEY: &str = "Realm signing public key";
pub const STR_REALM_INITIAL_MEASUREMENT: &str = "Realm initial measurement";
pub const STR_REALM_EXTENTIBLE_MEASUREMENTS: &str = "Realm extentible measurements";
pub const STR_PLAT_CHALLENGE: &str = "Challenge";
pub const STR_PLAT_VERIFICATION_SERVICE: &str = "Verification service";
pub const STR_PLAT_PROFILE: &str = "Profile";
pub const STR_PLAT_INSTANCE_ID: &str = "Instance ID";
pub const STR_PLAT_IMPLEMENTATION_ID: &str = "Implementation ID";
pub const STR_PLAT_SECURITY_LIFECYCLE: &str = "Lifecycle";
pub const STR_PLAT_CONFIGURATION: &str = "Configuration";
pub const STR_PLAT_HASH_ALGO_ID: &str = "Platform hash algo";
pub const STR_PLAT_SW_COMPONENTS: &str = "Platform sw components";
pub fn to_label(title: &'static str) -> u16 {
match title {
STR_USER_DATA | STR_REALM_CHALLENGE => TAG_REALM_CHALLENGE,
STR_REALM_PERSONALIZATION_VALUE => TAG_REALM_PERSONALIZATION_VALUE,
STR_REALM_HASH_ALGO_ID => TAG_REALM_HASH_ALGO_ID,
STR_REALM_PUB_KEY_HASH_ALGO_ID => TAG_REALM_PUB_KEY_HASH_ALGO_ID,
STR_REALM_PUB_KEY => TAG_REALM_PUB_KEY,
STR_REALM_INITIAL_MEASUREMENT => TAG_REALM_INITIAL_MEASUREMENT,
STR_REALM_EXTENTIBLE_MEASUREMENTS => TAG_REALM_EXTENTIBLE_MEASUREMENTS,
STR_PLAT_CHALLENGE => TAG_PLAT_CHALLENGE,
STR_PLAT_VERIFICATION_SERVICE => TAG_PLAT_VERIFICATION_SERVICE,
STR_PLAT_PROFILE => TAG_PLAT_PROFILE,
STR_PLAT_INSTANCE_ID => TAG_PLAT_INSTANCE_ID,
STR_PLAT_IMPLEMENTATION_ID => TAG_PLAT_IMPLEMENTATION_ID,
STR_PLAT_SECURITY_LIFECYCLE => TAG_PLAT_SECURITY_LIFECYCLE,
STR_PLAT_CONFIGURATION => TAG_PLAT_CONFIGURATION,
STR_PLAT_HASH_ALGO_ID => TAG_PLAT_HASH_ALGO_ID,
STR_PLAT_SW_COMPONENTS => TAG_PLAT_SW_COMPONENTS,
_ => TAG_UNASSIGINED,
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/report.rs | sdk/src/report.rs | use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Report {
pub buffer: Vec<u8>,
pub user_data: Vec<u8>,
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/prelude.rs | sdk/src/prelude.rs | pub use crate::attester::attest;
pub use crate::error::Error;
pub use crate::parser::{parse, print_claims};
pub use crate::report::Report;
pub use crate::sealing::{seal, unseal};
pub use crate::verifier::verify;
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/lib.rs | sdk/src/lib.rs | #![deny(warnings)]
#![feature(vec_into_raw_parts)]
#![warn(rust_2018_idioms)]
pub mod attester;
pub mod c_api;
pub mod error;
pub mod prelude;
pub mod report;
pub mod sealing;
pub mod verifier;
#[cfg(target_arch = "x86_64")]
mod mock;
mod parser;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
pub struct AttestationClaims {
pub origin: rust_rsi::AttestationClaims,
pub user_data: Vec<u8>, // The requirement of Certifier: Simulated Version on x86
}
} else {
pub use rust_rsi::AttestationClaims;
}
}
#[cfg(test)]
mod tests {
use super::prelude::*;
#[test]
fn attest_verify() {
let user_data = b"User data";
let report = attest(user_data).unwrap();
let claims = verify(&report).unwrap();
let (realm_claims, plat_claims) = parse(&claims).unwrap();
assert_eq!(user_data, &realm_claims.challenge[..user_data.len()]);
assert_eq!("http://arm.com/CCA-SSD/1.0.0", plat_claims.profile);
}
#[test]
fn sealing() {
use super::sealing::{seal, unseal};
let plaintext = b"Plaintext";
let sealed = seal(plaintext).unwrap();
let unsealed = unseal(&sealed).unwrap();
assert_eq!(plaintext, &unsealed[..]);
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/c_api.rs | sdk/src/c_api.rs | use crate::prelude::*;
use bincode::{deserialize, serialize};
use std::ffi::{c_char, c_int, c_uchar, CStr};
use std::slice::{from_raw_parts, from_raw_parts_mut};
const STR_REALM_CHALLENGE: &str = "Realm challenge";
const STR_REALM_INITIAL_MEASUREMENT: &str = "Realm initial measurement";
const STR_USER_DATA: &str = "User data";
const STR_PLAT_PROFILE: &str = "Profile";
#[allow(non_camel_case_types)]
#[repr(C)]
pub enum islet_status_t {
ISLET_SUCCESS = 0,
ISLET_FAILURE = -1,
ISLET_ERROR_INPUT = -2,
ISLET_ERROR_WRONG_REPORT = -3,
ISLET_ERROR_WRONG_CLAIMS = -4,
ISLET_ERROR_FEATURE_NOT_SUPPORTED = -5,
}
/// Get an attestation report(token).
///
/// # Note
/// This API currently returns hard-coded report to simulate attest operation.
/// In future, this will be finalized to support reports signed by RMM.
/// `User data` could be used as nonce to prevent reply attack.
#[no_mangle]
pub unsafe extern "C" fn islet_attest(
user_data: *const c_uchar,
user_data_len: c_int,
report_out: *mut c_uchar,
report_out_len: *mut c_int,
) -> islet_status_t {
if user_data_len > 64 {
return islet_status_t::ISLET_ERROR_INPUT;
}
let do_attest = || -> Result<(), Error> {
let user_data = from_raw_parts(user_data as *const u8, user_data_len as usize);
let report = attest(user_data)?;
let encoded = serialize(&report).or(Err(Error::Serialize))?;
*report_out_len = encoded.len() as c_int;
let out = from_raw_parts_mut(report_out, encoded.len());
out.copy_from_slice(&encoded[..]);
Ok(())
};
match do_attest() {
Ok(()) => islet_status_t::ISLET_SUCCESS,
Err(_) => islet_status_t::ISLET_FAILURE,
}
}
/// Verify the attestation report and returns attestation claims if succeeded.
#[no_mangle]
pub unsafe extern "C" fn islet_verify(
report: *const c_uchar,
report_len: c_int,
claims_out: *mut c_uchar,
claims_out_len: *mut c_int,
) -> islet_status_t {
let do_verify = || -> Result<(), Error> {
let encoded = from_raw_parts(report as *const u8, report_len as usize);
let decoded: Report = deserialize(encoded).or(Err(Error::Report))?;
let _claims = verify(&decoded)?;
// Encode the report instead of the claims.
// Because the claims couldn't serialize now.
let out = std::slice::from_raw_parts_mut(claims_out, encoded.len());
out.copy_from_slice(&encoded[..]);
*claims_out_len = out.len() as c_int;
Ok(())
};
match do_verify() {
Ok(()) => islet_status_t::ISLET_SUCCESS,
Err(Error::Report) => islet_status_t::ISLET_ERROR_WRONG_REPORT,
Err(_) => islet_status_t::ISLET_FAILURE,
}
}
/// Parse the claims with the given title and returns the claim if succeeded.
#[no_mangle]
pub unsafe extern "C" fn islet_parse(
title: *const c_char,
claims: *const c_uchar,
claims_len: c_int,
value_out: *mut c_uchar,
value_out_len: *mut c_int,
) -> islet_status_t {
let do_parse = || -> Result<(), Error> {
// Actually the report is passed instead of the claims
// ref. islet_verify()
let encoded = from_raw_parts(claims as *const u8, claims_len as usize);
let decoded: Report = deserialize(encoded).or(Err(Error::Report))?;
let claims = verify(&decoded)?;
let title = CStr::from_ptr(title).to_str().or(Err(Error::Decoding))?;
let (realm_claims, plat_claims) = parse(&claims)?;
let value = if title == STR_USER_DATA || title == STR_REALM_CHALLENGE {
Ok(realm_claims.challenge.clone())
} else if title == STR_REALM_INITIAL_MEASUREMENT {
Ok(realm_claims.rim.clone())
} else if title == STR_PLAT_PROFILE {
Ok(plat_claims.profile.as_bytes().to_vec())
} else {
Err(Error::NotSupported)
}?;
*value_out_len = value.len() as c_int;
let out = from_raw_parts_mut(value_out, value.len());
out.copy_from_slice(&value[..]);
Ok(())
};
match do_parse() {
Ok(()) => islet_status_t::ISLET_SUCCESS,
Err(Error::Claims) => islet_status_t::ISLET_ERROR_WRONG_CLAIMS,
Err(_) => islet_status_t::ISLET_FAILURE,
}
}
/// Print all claims including Realm Token and Platform Token.
#[no_mangle]
pub unsafe extern "C" fn islet_print_claims(claims: *const c_uchar, claims_len: c_int) {
// Actually the report is passed instead of the claims
// ref. islet_verify()
let encoded = from_raw_parts(claims as *const u8, claims_len as usize);
let decoded: Result<Report, Error> = deserialize(encoded).or(Err(Error::Report));
if decoded.is_err() {
println!("Wrong claims.");
}
match verify(&decoded.unwrap()) {
Ok(claims) => crate::parser::print_claims(&claims),
Err(error) => println!("Wrong claims {:?}", error),
}
}
/// Seals the plaintext given into the binary slice
///
/// # Note
/// This API currently seals with a hard-coded key, to simulate seal operation.
/// In future, this will be finalized to support keys derived from HES.
#[no_mangle]
pub unsafe extern "C" fn islet_seal(
plaintext: *const c_uchar,
plaintext_len: c_int,
sealed_out: *mut c_uchar,
sealed_out_len: *mut c_int,
) -> islet_status_t {
let do_seal = || -> Result<(), Error> {
let plaintext = from_raw_parts(plaintext as *const u8, plaintext_len as usize);
let sealed = seal(plaintext)?;
*sealed_out_len = sealed.len() as c_int;
let out = from_raw_parts_mut(sealed_out, sealed.len());
out.copy_from_slice(&sealed[..]);
Ok(())
};
match do_seal() {
Ok(()) => islet_status_t::ISLET_SUCCESS,
Err(_) => islet_status_t::ISLET_FAILURE,
}
}
/// Unseals into plaintext the sealed binary provided.
///
/// # Note
/// This API currently unseals with a hard-coded key, to simulate unseal operation.
/// In future, this will be finalized to support keys derived from HES.
#[no_mangle]
pub unsafe extern "C" fn islet_unseal(
sealed: *const c_uchar,
sealed_len: c_int,
plaintext_out: *mut c_uchar,
plaintext_out_len: *mut c_int,
) -> islet_status_t {
let do_unseal = || -> Result<(), Error> {
let sealed = from_raw_parts(sealed as *const u8, sealed_len as usize);
let plaintext = unseal(sealed)?;
*plaintext_out_len = plaintext.len() as c_int;
let out = from_raw_parts_mut(plaintext_out, plaintext.len());
out.copy_from_slice(&plaintext[..]);
Ok(())
};
match do_unseal() {
Ok(()) => islet_status_t::ISLET_SUCCESS,
Err(_) => islet_status_t::ISLET_FAILURE,
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/parser.rs | sdk/src/parser.rs | use crate::error::Error;
use crate::AttestationClaims;
use rust_rsi::{print_token, PlatClaims, RealmClaims};
pub fn parse(claims: &AttestationClaims) -> Result<(RealmClaims, PlatClaims), Error> {
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
let mut realm_claims = RealmClaims::from_raw_claims(
&claims.origin.realm_claims.token_claims,
&claims.origin.realm_claims.measurement_claims)?;
realm_claims.challenge = claims.user_data.clone();
let plat_claims = PlatClaims::from_raw_claims(
&claims.origin.platform_claims.token_claims)?;
Ok((realm_claims, plat_claims))
} else {
let realm_claims = RealmClaims::from_raw_claims(
&claims.realm_claims.token_claims,
&claims.realm_claims.measurement_claims)?;
let plat_claims = PlatClaims::from_raw_claims(
&claims.platform_claims.token_claims)?;
Ok((realm_claims, plat_claims))
}
}
}
pub fn print_claims(claims: &AttestationClaims) {
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
print_token(&claims.origin);
} else {
print_token(&claims);
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/attester.rs | sdk/src/attester.rs | use crate::error::Error;
use crate::report::Report;
#[cfg(target_arch = "x86_64")]
fn attest_x86_64(user_data: &[u8]) -> Result<Report, Error> {
println!("Simulated attestation operation on x86_64.");
Ok(Report {
buffer: crate::mock::REPORT.to_vec(),
user_data: user_data.to_vec(), // Hold user_data temporarily
})
}
#[cfg(target_arch = "aarch64")]
fn attest_aarch64(user_data: &[u8]) -> Result<Report, Error> {
println!("Getting an attestation report on aarch64.");
const LEN: usize = rust_rsi::CHALLENGE_LEN as usize;
if user_data.len() > LEN {
println!("Length of user_data cannot over CHALLENGE_LEN[{}]", LEN);
return Err(Error::InvalidArgument);
}
let mut challenge: [u8; LEN] = [0; LEN];
challenge[..user_data.len()].clone_from_slice(&user_data);
match rust_rsi::attestation_token(&challenge) {
Ok(token) => Ok(Report {
buffer: token,
user_data: Vec::new(), // Dummy field
}),
Err(error) => {
println!("Failed to get an attestation report. {:?}", error);
Err(Error::Report)
}
}
}
pub fn attest(user_data: &[u8]) -> Result<Report, Error> {
// Encode user_data to challenge claim in the realm token
cfg_if::cfg_if! {
if #[cfg(target_arch="x86_64")] {
attest_x86_64(user_data)
} else {
attest_aarch64(user_data)
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/error.rs | sdk/src/error.rs | use rust_rsi::TokenError;
#[derive(Debug)]
pub enum Error {
CCAToken(TokenError),
Claims,
Decoding,
InvalidArgument,
NotSupported,
Report,
Sealing,
SealingKey,
Serialize,
}
impl From<TokenError> for Error {
fn from(err: TokenError) -> Self {
Error::CCAToken(err)
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/mock.rs | sdk/src/mock.rs | const REPORT_LEN: usize = 1737;
pub const REPORT: [u8; REPORT_LEN] = [
0xD9, 0x01, 0x8F, 0xA2, 0x19, 0xAC, 0xCA, 0x59, 0x04, 0x96, 0xD2, 0x84, 0x44, 0xA1, 0x01, 0x38,
0x22, 0xA0, 0x59, 0x04, 0x29, 0xA9, 0x0A, 0x58, 0x20, 0x07, 0xA5, 0x9E, 0xA9, 0xA2, 0x24, 0x9F,
0x68, 0x0A, 0x1B, 0xE8, 0xE0, 0xB2, 0xF0, 0xAD, 0xBE, 0x34, 0xEA, 0x94, 0x26, 0x75, 0x06, 0x8E,
0xB2, 0x9D, 0x87, 0xF4, 0xF1, 0x5A, 0x54, 0x81, 0xCA, 0x19, 0x01, 0x00, 0x58, 0x21, 0x01, 0x1B,
0xE9, 0xC3, 0x36, 0xD7, 0xA7, 0x0B, 0x66, 0x13, 0x82, 0x93, 0x4A, 0x26, 0x01, 0x92, 0x35, 0x1A,
0xC6, 0x1D, 0x24, 0xE2, 0x0D, 0x88, 0x2F, 0x49, 0x4A, 0xBE, 0xE8, 0x7F, 0x8A, 0x1E, 0x98, 0x19,
0x01, 0x09, 0x78, 0x1C, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x61, 0x72, 0x6D, 0x2E, 0x63,
0x6F, 0x6D, 0x2F, 0x43, 0x43, 0x41, 0x2D, 0x53, 0x53, 0x44, 0x2F, 0x31, 0x2E, 0x30, 0x2E, 0x30,
0x19, 0x09, 0x5B, 0x19, 0x30, 0x00, 0x19, 0x09, 0x5C, 0x58, 0x20, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC,
0xCC, 0xCC, 0xCC, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0x19, 0x09, 0x5F, 0x89, 0xA5,
0x01, 0x63, 0x42, 0x4C, 0x31, 0x06, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58,
0x20, 0x69, 0x7D, 0xE4, 0x40, 0x7D, 0xAE, 0x45, 0xC0, 0x75, 0x06, 0xD1, 0xF0, 0x0B, 0x3D, 0xBF,
0x5C, 0xE1, 0xDB, 0x41, 0xF6, 0x9E, 0x17, 0x50, 0xA3, 0x11, 0xF9, 0x1D, 0x21, 0x3E, 0x11, 0x98,
0x89, 0x04, 0x65, 0x30, 0x2E, 0x31, 0x2E, 0x30, 0x05, 0x58, 0x20, 0xC6, 0xC3, 0x2A, 0x95, 0x7D,
0xF4, 0xC6, 0x69, 0x8C, 0x55, 0x0B, 0x69, 0x5D, 0x02, 0x2E, 0xD5, 0x18, 0x0C, 0xAE, 0x71, 0xF8,
0xB4, 0x9C, 0xBB, 0x75, 0xE6, 0x06, 0x1C, 0x2E, 0xF4, 0x97, 0xE1, 0xA5, 0x01, 0x63, 0x42, 0x4C,
0x32, 0x06, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x35, 0x31, 0x32, 0x02, 0x58, 0x40, 0x8E, 0x17, 0x5A,
0x1D, 0xCD, 0x79, 0xB8, 0xB5, 0x1C, 0xE9, 0xE2, 0x59, 0xC2, 0x56, 0x83, 0x05, 0xB7, 0x3F, 0x5F,
0x26, 0xF5, 0x67, 0x3A, 0x8C, 0xF7, 0x81, 0xA9, 0x45, 0x98, 0xE4, 0x4F, 0x67, 0xFD, 0xF4, 0x92,
0x68, 0x69, 0xEE, 0x76, 0x67, 0xE9, 0x12, 0x0B, 0x5C, 0x1B, 0x97, 0x62, 0x5C, 0xC9, 0x6D, 0x34,
0x7C, 0x23, 0xCE, 0x3C, 0x5F, 0x76, 0x3B, 0xF1, 0xD9, 0xB5, 0x47, 0x81, 0xF6, 0x04, 0x67, 0x31,
0x2E, 0x39, 0x2E, 0x30, 0x2B, 0x30, 0x05, 0x58, 0x20, 0xA0, 0x64, 0xB1, 0xAD, 0x60, 0xFA, 0x18,
0x33, 0x94, 0xDD, 0xA5, 0x78, 0x91, 0x35, 0x7F, 0x97, 0x2E, 0x4F, 0xE7, 0x22, 0x78, 0x2A, 0xDF,
0xF1, 0x85, 0x4C, 0x8B, 0x2A, 0x14, 0x2C, 0x04, 0x10, 0xA5, 0x01, 0x69, 0x46, 0x57, 0x5F, 0x43,
0x4F, 0x4E, 0x46, 0x49, 0x47, 0x06, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58,
0x20, 0xD2, 0x24, 0x49, 0xEB, 0x85, 0x3A, 0xA1, 0xF6, 0xFA, 0x8C, 0xCA, 0x74, 0xA5, 0xBA, 0x4F,
0xD0, 0xDF, 0xAB, 0xBE, 0x31, 0x35, 0xC6, 0x72, 0x94, 0x7E, 0x69, 0x69, 0xD2, 0x02, 0x71, 0xB4,
0xA4, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5, 0x01, 0x6C, 0x54, 0x42, 0x5F, 0x46, 0x57, 0x5F, 0x43,
0x4F, 0x4E, 0x46, 0x49, 0x47, 0x06, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58,
0x20, 0xC7, 0xF9, 0x9E, 0x45, 0xBB, 0x76, 0xF3, 0x3F, 0xFA, 0x37, 0x27, 0x44, 0x88, 0xFC, 0x00,
0x19, 0xAB, 0x5B, 0xA5, 0x26, 0xA2, 0x7B, 0x29, 0x1E, 0x2B, 0x14, 0xE1, 0x76, 0x2A, 0xA0, 0xC1,
0xEB, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5, 0x01, 0x64, 0x42, 0x4C, 0x5F, 0x32, 0x06, 0x67, 0x73,
0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58, 0x20, 0xEA, 0xD3, 0x15, 0xA9, 0x05, 0x38, 0x38,
0x0B, 0x4B, 0xF3, 0x5D, 0x65, 0xEE, 0x0D, 0x5F, 0x97, 0x85, 0x1A, 0xBD, 0x55, 0x1D, 0x95, 0x83,
0xE2, 0x89, 0xCA, 0x07, 0x62, 0x12, 0xEE, 0x53, 0x4A, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5, 0x01,
0x6D, 0x53, 0x45, 0x43, 0x55, 0x52, 0x45, 0x5F, 0x52, 0x54, 0x5F, 0x45, 0x4C, 0x33, 0x06, 0x67,
0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58, 0x20, 0x2A, 0x70, 0x2D, 0xCE, 0x8B, 0x46,
0xBD, 0x52, 0xFC, 0x30, 0x38, 0x23, 0xDC, 0x81, 0xD4, 0xBC, 0x63, 0x26, 0xD2, 0xE4, 0x6F, 0x97,
0xF4, 0x2A, 0x4C, 0x2A, 0x85, 0x7B, 0x86, 0x99, 0x7E, 0xEF, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5,
0x01, 0x69, 0x48, 0x57, 0x5F, 0x43, 0x4F, 0x4E, 0x46, 0x49, 0x47, 0x06, 0x67, 0x73, 0x68, 0x61,
0x2D, 0x32, 0x35, 0x36, 0x02, 0x58, 0x20, 0xAF, 0xCF, 0xC2, 0x71, 0x36, 0x29, 0xF1, 0xF4, 0x63,
0x9B, 0xE2, 0xE0, 0xA7, 0x4B, 0x44, 0xAA, 0xC1, 0xE4, 0x4F, 0xB1, 0x84, 0x49, 0x6B, 0x12, 0x88,
0xA6, 0x76, 0xA0, 0x06, 0x7C, 0x47, 0x50, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5, 0x01, 0x6D, 0x53,
0x4F, 0x43, 0x5F, 0x46, 0x57, 0x5F, 0x43, 0x4F, 0x4E, 0x46, 0x49, 0x47, 0x06, 0x67, 0x73, 0x68,
0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58, 0x20, 0xB5, 0x96, 0x80, 0xED, 0xC2, 0x21, 0x01, 0x68,
0x63, 0x00, 0xD9, 0xC4, 0xCB, 0x79, 0x28, 0x2F, 0xAA, 0x63, 0x5C, 0x0A, 0x3A, 0x3C, 0x6F, 0xD0,
0xC3, 0x73, 0x5A, 0xA1, 0xFF, 0xA4, 0x81, 0x8F, 0x04, 0x60, 0x05, 0x58, 0x20, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA5, 0x01, 0x63,
0x52, 0x4D, 0x4D, 0x06, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x02, 0x58, 0x20, 0x98,
0x49, 0x8D, 0xE2, 0x05, 0x56, 0xF8, 0xF5, 0x5C, 0xB6, 0x71, 0x34, 0xE3, 0x69, 0x49, 0x66, 0x64,
0xD7, 0x02, 0xF3, 0xE9, 0x2F, 0x34, 0xF3, 0x7F, 0x6E, 0xB8, 0xB2, 0xC6, 0x2A, 0x29, 0xAF, 0x04,
0x60, 0x05, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x19, 0x09, 0x60, 0x73, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x77,
0x68, 0x61, 0x74, 0x65, 0x76, 0x65, 0x72, 0x2E, 0x63, 0x6F, 0x6D, 0x19, 0x09, 0x61, 0x44, 0xEF,
0xBE, 0xAD, 0xDE, 0x19, 0x09, 0x62, 0x67, 0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x58, 0x60,
0x24, 0x0E, 0xF9, 0xF0, 0x48, 0x53, 0x86, 0xD6, 0xC3, 0x11, 0x97, 0xA5, 0xF9, 0x0E, 0xDF, 0x5A,
0xAE, 0xDB, 0x28, 0xB5, 0x6B, 0x5B, 0xB1, 0x30, 0xD1, 0x56, 0x89, 0x0C, 0x67, 0x3C, 0xAD, 0x75,
0xC5, 0xE1, 0xB0, 0x42, 0xA1, 0xC1, 0x4F, 0xA8, 0xF7, 0x1C, 0xFA, 0x2B, 0x00, 0x6A, 0xCB, 0x1C,
0x18, 0x4B, 0x97, 0x29, 0x22, 0xC7, 0xA9, 0x8C, 0x36, 0x30, 0x5B, 0x96, 0x22, 0xC6, 0x12, 0x13,
0xE9, 0xDC, 0x54, 0x39, 0x3A, 0xA8, 0x32, 0x5E, 0x95, 0x51, 0x93, 0xA6, 0x3B, 0xE8, 0x47, 0x06,
0x33, 0x8C, 0x99, 0x45, 0x94, 0x29, 0xE7, 0x3C, 0x7C, 0xF6, 0xFD, 0x11, 0x47, 0x89, 0x25, 0x93,
0x19, 0xAC, 0xD1, 0x59, 0x02, 0x23, 0xD2, 0x84, 0x44, 0xA1, 0x01, 0x38, 0x22, 0xA0, 0x59, 0x01,
0xB6, 0xA7, 0x0A, 0x58, 0x40, 0x55, 0x73, 0x65, 0x72, 0x20, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xAC, 0xCB, 0x58, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xAC, 0xCE, 0x58, 0x20, 0x58,
0x0B, 0xD7, 0x70, 0x74, 0xF7, 0x89, 0xF3, 0x48, 0x41, 0xEA, 0x99, 0x20, 0x57, 0x9F, 0xF2, 0x9A,
0x59, 0xB9, 0x45, 0x2B, 0x60, 0x6F, 0x73, 0x81, 0x11, 0x32, 0xB3, 0x1C, 0x68, 0x9D, 0xA9, 0x19,
0xAC, 0xCF, 0x84, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xAC, 0xCC, 0x67, 0x73,
0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x19, 0xAC, 0xCD, 0x58, 0x61, 0x04, 0x46, 0xD8, 0x17, 0x72,
0xC6, 0xEF, 0x21, 0x54, 0x15, 0xF0, 0x70, 0x85, 0xEA, 0x4D, 0x87, 0xF6, 0xF3, 0x3E, 0x26, 0xB2,
0x43, 0xC3, 0xF8, 0x53, 0x5B, 0xBE, 0xEF, 0x11, 0x6A, 0x63, 0x3E, 0xB3, 0xD6, 0xD7, 0x0B, 0x42,
0xA5, 0x3B, 0x6E, 0x00, 0xE1, 0x7C, 0x32, 0xCA, 0xA1, 0xB7, 0x7C, 0x56, 0xF4, 0x73, 0xC3, 0x15,
0xC6, 0x74, 0x79, 0xA7, 0xE7, 0xB5, 0xB3, 0x60, 0x95, 0x1F, 0xE6, 0xA4, 0x3D, 0x8D, 0x66, 0x7D,
0x04, 0x7B, 0x09, 0x89, 0x50, 0x42, 0xC9, 0x6C, 0x86, 0xA2, 0xF8, 0xF3, 0xD8, 0x81, 0x7E, 0xF7,
0x88, 0x8B, 0x57, 0xE9, 0x7C, 0x26, 0x35, 0x4D, 0x7E, 0x9E, 0x19, 0xD3, 0x19, 0xAC, 0xD0, 0x67,
0x73, 0x68, 0x61, 0x2D, 0x32, 0x35, 0x36, 0x58, 0x60, 0xF0, 0x1B, 0xE8, 0x57, 0x34, 0xB1, 0x55,
0x5D, 0x38, 0x17, 0xDD, 0x5B, 0x80, 0x8F, 0xFA, 0x7A, 0x67, 0xF8, 0xE1, 0x06, 0xF8, 0x38, 0x8D,
0xE5, 0x43, 0xAC, 0x41, 0x2F, 0x4C, 0x4D, 0x6E, 0x38, 0x26, 0x8F, 0x20, 0xC0, 0xB2, 0x1D, 0x74,
0xFF, 0x7E, 0x2C, 0x6B, 0x22, 0x04, 0x74, 0x10, 0xE1, 0x8F, 0xA3, 0x2E, 0x5B, 0x44, 0xD8, 0xF5,
0x26, 0x91, 0xE4, 0x19, 0xFE, 0x81, 0x7F, 0x24, 0xEF, 0x4A, 0x49, 0xB2, 0xCE, 0xFD, 0x02, 0xD4,
0x0D, 0xED, 0x19, 0x98, 0x57, 0xF8, 0x65, 0x68, 0x6A, 0xC5, 0x38, 0x0D, 0x37, 0x47, 0xD0, 0xB9,
0x5C, 0xB9, 0x21, 0xF1, 0xD4, 0x3A, 0xDA, 0xE7, 0x76,
];
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/sealing.rs | sdk/src/sealing.rs | use crate::error::Error;
use openssl::rand::rand_bytes;
use openssl::symm::{decrypt_aead, encrypt_aead, Cipher};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
// These seal and unseal functions are implemented similarly as in the VMWare's Certifier Framework.
// Here are the main assumptions:
// - The requested symmetric Sealing Key is bound to the platform, firmware and the Realm Initial Measurement (RIM).
// Thus, any change of the platform, firmware, or a realm image will result in a different key.
// - AES-256-GCM is used as an encryption algorithm; the AAD is not set
// - The plaintext is encrypted and put into a sealed data structure. This strucure is comprised of
// the header and the ciphertext, the header contains the IV and the authentication TAG.
// The whole structure is serialized using serde and bincode crates to produce binary object, that then can
// be saved in a file on the host side.
// We take VHUK_M (Measurement based Virtual Hardware Unique Key) and RIM
// as a key material during the sealing key derivation process
#[cfg(target_arch = "aarch64")]
const UNIQUE_SEALING_KEY: u64 =
rust_rsi::RSI_SEALING_KEY_FLAGS_KEY | rust_rsi::RSI_SEALING_KEY_FLAGS_RIM;
const AES_GCM_256_IV_LEN: usize = 12;
const AES_GCM_256_TAG_LEN: usize = 16;
const SEALING_KEY_LEN: usize = 32;
// An embedded sealing key used on the simulated platform
#[cfg(target_arch = "x86_64")]
const SEALING_KEY: [u8; SEALING_KEY_LEN] = [
0x63, 0x10, 0xc1, 0xf0, 0x53, 0xd5, 0x52, 0x40, 0x29, 0xfa, 0x7f, 0x7d, 0xcd, 0x9e, 0x28, 0x2c,
0x4a, 0x93, 0x9d, 0x55, 0xb9, 0x89, 0x15, 0x44, 0x45, 0xa3, 0x86, 0x1e, 0x1f, 0xa1, 0xe2, 0xce,
];
#[derive(Serialize, Deserialize)]
struct Header {
tag: [u8; AES_GCM_256_TAG_LEN],
iv: [u8; AES_GCM_256_IV_LEN],
}
impl Header {
fn new() -> Result<Self, Error> {
let mut instance = Self {
tag: [0u8; AES_GCM_256_TAG_LEN],
iv: [0u8; AES_GCM_256_IV_LEN],
};
rand_bytes(&mut instance.iv).map_err(|_| Error::Sealing)?;
Ok(instance)
}
}
#[derive(Serialize, Deserialize)]
struct SealedData {
header: Header,
ciphertext: Vec<u8>,
}
fn sealing_key() -> Result<[u8; SEALING_KEY_LEN], Error> {
cfg_if::cfg_if! {
// Return the embedded sealing key for simulated platform
if #[cfg(target_arch="x86_64")] {
Ok(SEALING_KEY)
} else {
rust_rsi::sealing_key(UNIQUE_SEALING_KEY, 0).or(Err(Error::SealingKey))
}
}
}
pub fn seal(plaintext: &[u8]) -> Result<Vec<u8>, Error> {
let mut header = Header::new()?;
let cipher = Cipher::aes_256_gcm();
let sealing_key = Zeroizing::new(sealing_key().map_err(|_| Error::SealingKey)?);
let enc_res = encrypt_aead(
cipher,
sealing_key.as_ref(),
Some(&header.iv),
&[],
plaintext,
&mut header.tag,
);
let sealed_data = SealedData {
header: header,
ciphertext: enc_res.map_err(|_| Error::Sealing)?,
};
bincode::serialize(&sealed_data).map_err(|_| Error::Sealing)
}
pub fn unseal(sealed: &[u8]) -> Result<Vec<u8>, Error> {
let sealed_data: SealedData = bincode::deserialize(sealed).map_err(|_| Error::Sealing)?;
let cipher = Cipher::aes_256_gcm();
let sealing_key = Zeroizing::new(sealing_key().map_err(|_| Error::SealingKey)?);
let dec_res = decrypt_aead(
cipher,
sealing_key.as_ref(),
Some(&sealed_data.header.iv),
&[],
&sealed_data.ciphertext,
&sealed_data.header.tag,
);
dec_res.map_err(|_| Error::Sealing)
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/src/verifier.rs | sdk/src/verifier.rs | use crate::report::Report;
use crate::AttestationClaims;
use rust_rsi::{verify_token, TokenError};
pub fn verify(report: &Report) -> Result<AttestationClaims, TokenError> {
let claims = verify_token(&report.buffer, None)?;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
Ok(AttestationClaims {
origin: claims,
user_data: report.user_data.clone()
})
} else {
Ok(claims)
}
}
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
islet-project/islet | https://github.com/islet-project/islet/blob/5f541377a34c5daaf01aa148e406370e304fb661/sdk/examples/attest_n_seal.rs | sdk/examples/attest_n_seal.rs | use islet_sdk::prelude::*;
fn attestation() -> Result<(), Error> {
let user_data = b"User data";
let report = attest(user_data)?;
let claims = verify(&report)?;
print_claims(&claims);
let (realm_claims, plat_claims) = parse(&claims).unwrap();
assert_eq!(&realm_claims.challenge[..user_data.len()], user_data);
assert_eq!(plat_claims.profile, "http://arm.com/CCA-SSD/1.0.0");
Ok(())
}
fn sealing() -> Result<(), Error> {
let plaintext = b"\
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ornare lacinia accumsan. Nam eleifend vel nisl et
commodo. Quisque in tortor non risus dictum varius. Curabitur pulvinar tellus vitae sapien gravida dapibus. Ut nec
imperdiet sem, eu ornare turpis. Donec a lectus vitae enim malesuada aliquam sed ac turpis. Mauris turpis massa, mollis
et ex vitae, tempor gravida odio. Maecenas erat urna, laoreet et ornare auctor, faucibus nec elit. In luctus turpis
sapien, vel posuere libero pulvinar et. Donec maximus sollicitudin condimentum. Mauris condimentum ex vel purus
scelerisque faucibus. Donec dapibus viverra massa ut iaculis.
Maecenas eget sollicitudin lorem. Aenean euismod ultricies dui quis fringilla. Pellentesque sit amet dapibus metus.
Vivamus tincidunt convallis lectus eget lacinia. Aliquam ac nisl vel erat pulvinar accumsan. Aliquam ut ante id nunc
molestie rutrum. Pellentesque facilisis venenatis erat, ac ornare elit posuere in. Integer porttitor sit amet tortor at
lobortis. Morbi imperdiet rutrum metus sed malesuada. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices
posuere cubilia curae; Vestibulum lacinia eu justo nec auctor. Vivamus suscipit a erat in ultricies. Curabitur sit amet
egestas turpis. Sed semper nunc at diam varius, in congue nisl pretium. Proin aliquam magna mi.
Ut imperdiet diam ut nisi consequat tincidunt. Sed imperdiet purus vel fermentum dignissim. Etiam at cursus libero. In
leo metus, sagittis at dictum vel, mattis quis quam. Pellentesque in erat purus. Suspendisse in pretium urna, sed
tincidunt felis. Sed dapibus sed ipsum ut mattis. Pellentesque iaculis, dui eget congue hendrerit, velit est
sollicitudin leo, ac ullamcorper diam ligula quis felis. Etiam fermentum magna quis enim pretium, sed rhoncus metus
dignissim.
Integer dignissim hendrerit enim, nec blandit massa. Aliquam porttitor dolor vel congue commodo. Donec maximus dui non
neque congue, et aliquet odio pharetra. Integer varius magna vitae dolor efficitur aliquam. Aenean suscipit quam et
lectus tincidunt congue. Aliquam vitae libero dolor. Class aptent taciti sociosqu ad litora torquent per conubia
nostra, per inceptos himenaeos.
Donec et ultrices diam, vitae vulputate ligula. Fusce tempor pellentesque commodo. Fusce quam eros, ultrices quis nibh
in, fermentum laoreet tortor. Nam eget tortor et purus dignissim placerat. Etiam eu tellus et leo imperdiet tempor et
porttitor diam. Etiam risus enim, viverra non euismod at, eleifend eu elit. Mauris posuere est lacus, at interdum felis
semper in. Aliquam varius euismod velit, eu iaculis felis malesuada et. Fusce laoreet ac est a euismod. Phasellus vel
sapien dolor. Maecenas vehicula lorem ac orci luctus, vel sodales libero sollicitudin. Nunc id orci mattis, rutrum nunc
id, luctus mauris. Sed sem arcu, pretium quis pellentesque sed, bibendum vel tellus. Integer dapibus pretium ligula, at
rhoncus ante iaculis vel. Proin feugiat enim ut diam mollis, at vestibulum libero vestibulum.";
let sealed = seal(plaintext)?;
let unsealed = unseal(&sealed)?;
assert_eq!(plaintext, &unsealed[..]);
Ok(())
}
fn main() {
println!("Attestation result {:?}", attestation());
println!("Sealing result {:?}", sealing());
}
| rust | Apache-2.0 | 5f541377a34c5daaf01aa148e406370e304fb661 | 2026-01-04T20:21:26.369655Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/main.rs | src/main.rs | use std::env;
use core::utils::TimeEstimation;
use database::{DatabaseGenerator, DatabaseLoader};
use env_logger::Env;
use log::{info};
use server::{FootballSimulatorServer, GameAppData};
use std::sync::Arc;
use tokio::sync::RwLock;
#[tokio::main]
async fn main() {
color_eyre::install().unwrap();
env_logger::Builder::from_env(Env::default()
.default_filter_or("debug")
).init();
let is_one_shot_game = env::var("MODE") == Ok(String::from("ONESHOT"));
let (database, estimated) = TimeEstimation::estimate(DatabaseLoader::load);
info!("database loaded: {} ms", estimated);
if is_one_shot_game {
info!("one shot game started");
}
let game_data = DatabaseGenerator::generate(&database);
let data = GameAppData {
database: Arc::new(database),
data: Arc::new(RwLock::new(Some(game_data))),
is_one_shot_game
};
FootballSimulatorServer::new(data).run().await;
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/dev/neural/src/main.rs | src/dev/neural/src/main.rs | #![recursion_limit = "256"]
use burn::backend::{Autodiff, NdArray};
use burn::config::Config;
use burn::data::dataloader::batcher::Batcher;
use burn::data::dataloader::DataLoaderBuilder;
use burn::data::dataset::InMemDataset;
use burn::nn::loss::MseLoss;
use burn::nn::loss::Reduction::Mean;
use burn::optim::AdamConfig;
use burn::prelude::{Backend, Module, Tensor};
use burn::record::{BinFileRecorder, FullPrecisionSettings};
use burn::tensor::backend::AutodiffBackend;
use burn::train::metric::LossMetric;
use burn::train::{LearnerBuilder, RegressionOutput, TrainOutput, TrainStep, ValidStep};
use neural::{MidfielderPassingNeural, MidfielderPassingNeuralConfig};
use std::path::PathBuf;
use burn::backend::ndarray::NdArrayDevice;
type NeuralNetworkDevice = NdArrayDevice;
type NeuralNetworkBackend = NdArray;
type NeuralNetworkAutodiffBackend = Autodiff<NeuralNetworkBackend>;
type NeuralNetwork<B> = MidfielderPassingNeural<B>;
type NeuralNetworkConfig = MidfielderPassingNeuralConfig;
type NeuralNetworkAutoDiff = MidfielderPassingNeural<NeuralNetworkAutodiffBackend>;
fn main() {
let device = NeuralNetworkDevice::default();
let training_data = vec![
(70f64, 0f64, 88.0f64),
(70f64, 0f64, 137.0f64),
(32f64, 4f64, 137.0f64),
(22f64, 8f64, 137.0f64),
(77f64, 3f64, 555.0f64),
(30f64, 1f64, 137.0f64),
(87f64, 6f64, 111.0f64)
];
let training_additional_data = vec![
// (4f64, 4f64, 0f64),
// (20f64, 8f64, 0f64),
// (44f64, 4f64, 0f64),
// (19f64, 4f64, 0f64),
// (90f64, 2f64, 0f64),
];
let model: NeuralNetworkAutoDiff = train::<NeuralNetworkAutodiffBackend>(
"artifacts",
TrainingConfig {
num_epochs: 15000,
learning_rate: 1e-3,
momentum: 1e-2,
seed: 43,
batch_size: 1,
},
training_data.clone(),
device.clone(),
);
for item in training_data.iter().chain(&training_additional_data) {
let tensor = Tensor::from_data([[item.0, item.1]], &device);
let result = model.forward(tensor);
let tensor_data_string = result
.to_data()
.iter()
.map(|x: f32| format!("{:.4}", x))
.collect::<Vec<String>>()
.join(", ");
println!(
"INPUT: {},{}, RESULT: {:.32}",
item.0, item.1, tensor_data_string
);
}
let path = PathBuf::from_iter(["artifacts", "model.bin"]);
let recorder = BinFileRecorder::<FullPrecisionSettings>::new();
model
.save_file(PathBuf::from_iter(&path), &recorder)
.expect("Should be able to save the model");
}
#[derive(Config)]
pub struct TrainingConfig {
#[config(default = 1000)]
pub num_epochs: usize,
#[config(default = 1e-3)]
pub learning_rate: f64,
#[config(default = 1e-2)]
pub momentum: f64,
#[config(default = 42)]
pub seed: u64,
#[config(default = 2)]
pub batch_size: usize,
}
#[derive(Debug, Clone)]
struct BinaryDataBatcher<B: Backend> {
device: B::Device,
}
impl<B: Backend> BinaryDataBatcher<B> {
pub fn new(device: B::Device) -> Self {
BinaryDataBatcher {
device: device.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct TrainingBatch<B: Backend> {
pub inputs: Tensor<B, 2>,
pub targets: Tensor<B, 1>,
}
type BatcherItem = (f64, f64, f64);
impl<B: Backend> Batcher<B, BatcherItem, TrainingBatch<B>> for BinaryDataBatcher<B> {
fn batch(&self, items: Vec<BatcherItem>, _device: &B::Device) -> TrainingBatch<B> {
let mut inputs: Vec<Tensor<B, 2>> = Vec::new();
for item in items.iter() {
inputs.push(Tensor::from_floats([[item.0, item.1]], &self.device))
}
let inputs = Tensor::cat(inputs, 0);
let targets = items
.iter()
.map(|item| Tensor::<B, 1>::from_floats([item.2], &self.device))
.collect();
let targets = Tensor::cat(targets, 0);
TrainingBatch { inputs, targets }
}
}
fn create_artifact_dir(artifact_dir: &str) {
std::fs::remove_dir_all(artifact_dir).ok();
std::fs::create_dir_all(artifact_dir).ok();
}
impl<B: AutodiffBackend> TrainStep<TrainingBatch<B>, RegressionOutput<B>> for NeuralNetwork<B> {
fn step(&self, item: TrainingBatch<B>) -> TrainOutput<RegressionOutput<B>> {
let output = self.forward_step(item);
TrainOutput::new(self, output.loss.backward(), output)
}
}
impl<B: Backend> ValidStep<TrainingBatch<B>, RegressionOutput<B>> for NeuralNetwork<B> {
fn step(&self, item: TrainingBatch<B>) -> RegressionOutput<B> {
self.forward_step(item)
}
}
pub fn train<B: AutodiffBackend>(
artifact_dir: &str,
config: TrainingConfig,
training_data: Vec<(f64, f64, f64)>,
device: B::Device,
) -> NeuralNetwork<B> {
create_artifact_dir(artifact_dir);
config
.save(format!("{artifact_dir}/config.json"))
.expect("Config should be saved successfully");
B::seed(config.seed);
let model: NeuralNetwork<B> = NeuralNetworkConfig::init(&device);
let optimizer = AdamConfig::new().init();
let train_dataset = InMemDataset::new(training_data.clone());
let train_data = DataLoaderBuilder::new(BinaryDataBatcher::new(device.clone()))
.batch_size(1)
.build(train_dataset);
let valid_dataset = InMemDataset::new(training_data);
let valid_data = DataLoaderBuilder::new(BinaryDataBatcher::new(device.clone()))
.batch_size(1)
.build(valid_dataset);
let learner = LearnerBuilder::new(artifact_dir)
.metric_train_numeric(LossMetric::new())
.metric_valid_numeric(LossMetric::new())
//.with_file_checkpointer(CompactRecorder::new())
.devices(vec![device.clone()])
.num_epochs(config.num_epochs)
.summary()
.build(model, optimizer, config.learning_rate);
learner.fit(train_data, valid_data)
}
trait NeuralTrait<B: Backend> {
fn forward_step(&self, item: TrainingBatch<B>) -> RegressionOutput<B>;
}
impl<B: Backend> NeuralTrait<B> for NeuralNetwork<B> {
fn forward_step(&self, item: TrainingBatch<B>) -> RegressionOutput<B> {
let targets: Tensor<B, 2> = item.targets.unsqueeze_dim(1);
let output: Tensor<B, 2> = self.forward(item.inputs);
let loss = MseLoss::new().forward(output.clone(), targets.clone(), Mean);
RegressionOutput {
loss,
output,
targets,
}
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/dev/graphics/src/main.rs | src/dev/graphics/src/main.rs | //tactics
use core::club::player::Player;
use core::club::player::PlayerPositionType;
use core::club::team::tactics::{MatchTacticType, Tactics};
use core::r#match::ball::Ball;
use core::r#match::player::strategies::MatchBallLogic;
use core::r#match::player::MatchPlayer;
use core::r#match::FootballEngine;
use core::r#match::MatchContext;
use core::r#match::MatchField;
use core::r#match::MatchPlayerCollection;
use core::r#match::MatchSquad;
use core::r#match::ResultMatchPositionData;
use core::r#match::VectorExtensions;
use core::Vector3;
use env_logger::Env;
use macroquad::prelude::*;
use std::time::Duration;
use std::time::Instant;
use core::r#match::PlayerSide;
use core::r#match::Score;
use core::r#match::GOAL_WIDTH;
use core::staff_contract_mod::NaiveDate;
use core::PlayerGenerator;
/// Tracks pass target for visualization
#[derive(Debug, Clone)]
struct PassTargetInfo {
target_player_id: u32,
timestamp: u64,
}
const INNER_FIELD_WIDTH: f32 = 840.0;
const INNER_FIELD_HEIGHT: f32 = 545.0;
#[derive(Debug, Clone, Copy, PartialEq)]
enum MatchSpeed {
Percent100 = 1,
Percent50 = 2,
Percent10 = 10,
Percent1 = 100,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum PlayMode {
Live, // Running simulation in real-time
Replay, // Playing back recorded positions
}
impl MatchSpeed {
fn label(&self) -> &'static str {
match self {
MatchSpeed::Percent100 => "100%",
MatchSpeed::Percent50 => "50%",
MatchSpeed::Percent10 => "10%",
MatchSpeed::Percent1 => "1%",
}
}
fn all() -> [MatchSpeed; 4] {
[
MatchSpeed::Percent100,
MatchSpeed::Percent50,
MatchSpeed::Percent10,
MatchSpeed::Percent1,
]
}
}
#[macroquad::main(window_conf)]
async fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("debug")).init();
let width = screen_width() - 30.0;
let height = screen_height();
let window_aspect_ratio = width / height;
let field_aspect_ratio = INNER_FIELD_WIDTH / INNER_FIELD_HEIGHT;
let (field_width, field_height, scale) = if window_aspect_ratio > field_aspect_ratio {
let scale = height / INNER_FIELD_HEIGHT;
(INNER_FIELD_WIDTH * scale, height, scale)
} else {
let scale = width / INNER_FIELD_WIDTH;
(width, INNER_FIELD_HEIGHT * scale, scale)
};
let offset_x = (width - field_width) / 2.0 + 20.0;
let offset_y = (height - field_height) / 2.0 + 10.0;
let home_squad = get_home_squad();
let away_squad = get_away_squad();
let players = MatchPlayerCollection::from_squads(&home_squad, &away_squad);
let mut field = MatchField::new(
INNER_FIELD_WIDTH as usize,
INNER_FIELD_HEIGHT as usize,
home_squad,
away_squad,
);
let score = Score::new(1, 2);
let mut context = MatchContext::new(&field, players, score);
context.enable_logging();
let mut current_frame = 0u64;
let mut tick_frame = 0u64;
// Use new_with_tracking() to enable pass event tracking for visualization
let mut match_data = ResultMatchPositionData::new_with_tracking();
let mut left_mouse_pressed;
let mut selected_speed = MatchSpeed::Percent100;
let mut play_mode = PlayMode::Live;
let mut is_paused = false;
let mut replay_time: u64 = 0;
let mut max_live_time: u64 = 0; // Track maximum time reached in Live mode
let mut pass_target: Option<PassTargetInfo> = None; // Track current pass target
loop {
current_frame += 1;
clear_background(Color::new(255.0, 238.0, 7.0, 65.0));
let field_color = Color::from_rgba(132, 240, 207, 255);
let border_color = Color::from_rgba(51, 184, 144, 255);
let border_width = 5.0;
draw_rectangle_ex(
offset_x,
offset_y,
field_width,
field_height,
DrawRectangleParams {
color: field_color,
offset: Vec2 { x: 0.0, y: 0.0 },
rotation: 0.0,
},
);
draw_rectangle_lines_ex(
offset_x - border_width / 2.0,
offset_y - border_width / 2.0,
field_width + border_width,
field_height + border_width,
border_width,
DrawRectangleParams {
color: border_color,
offset: Vec2 { x: 0.0, y: 0.0 },
rotation: 0.0,
},
);
// Speed control UI at the top right corner
draw_speed_control(offset_x, offset_y, field_width, &mut selected_speed);
// Time slider and play/pause controls (at the bottom)
let slider_y = screen_height() - 50.0;
draw_time_slider(
20.0, // Start from left edge with padding
slider_y,
screen_width() - 40.0, // Full width with padding
&match_data,
&mut play_mode,
&mut is_paused,
&mut replay_time,
max_live_time,
);
let start = Instant::now();
// Execute game tick or update replay based on mode
match play_mode {
PlayMode::Live if !is_paused => {
// Only execute game tick based on selected speed
let should_tick = tick_frame % (selected_speed as u64) == 0;
tick_frame += 1;
if should_tick {
// Increment time before game tick (like the engine does)
context.increment_time();
FootballEngine::<840, 545>::game_tick(&mut field, &mut context, &mut match_data);
}
// Update replay_time to current match time for slider display
replay_time = context.total_match_time;
// Track the maximum time reached in live mode
max_live_time = max_live_time.max(replay_time);
}
PlayMode::Live if is_paused => {
// Paused in live mode - keep current time
replay_time = context.total_match_time;
// Track the maximum time reached in live mode
max_live_time = max_live_time.max(replay_time);
}
PlayMode::Replay if !is_paused => {
// Auto-advance replay time using same speed as live mode
let should_advance = tick_frame % (selected_speed as u64) == 0;
tick_frame += 1;
if should_advance {
// Increment by 10ms to match live mode speed (MATCH_TIME_INCREMENT_MS)
replay_time += 10;
// Use max_live_time as the limit (highest time reached in Live mode)
if replay_time > max_live_time {
replay_time = max_live_time;
is_paused = true;
}
}
// Update field positions from recorded data
update_positions_from_replay(&mut field, &match_data, replay_time);
}
_ => {
// Paused in replay mode
if play_mode == PlayMode::Replay {
// Make sure positions are set to current replay time
update_positions_from_replay(&mut field, &match_data, replay_time);
}
}
}
let elapsed = start.elapsed();
// Get recent pass event from match data (show for 2 seconds)
if let Some(recent_pass) = match_data.get_recent_pass_at(context.total_match_time) {
// Only show passes from last 2 seconds
if context.total_match_time - recent_pass.timestamp <= 2000 {
pass_target = Some(PassTargetInfo {
target_player_id: recent_pass.to_player_id,
timestamp: recent_pass.timestamp,
});
} else {
pass_target = None;
}
} else {
pass_target = None;
}
draw_goals(offset_x, offset_y, &context, field_width, scale);
draw_waypoints(offset_x, offset_y, &field, scale);
draw_players(offset_x, offset_y, &field, field.ball.current_owner, pass_target.as_ref(), scale);
draw_ball(offset_x, offset_y, &field.ball, scale);
draw_player_list(
offset_x + 20.0,
offset_y + field_height + 10.0,
field.players.iter().filter(|p| p.team_id == 2).collect(),
field.ball.current_owner,
scale,
);
draw_player_list(
offset_x + 20.0,
offset_y - 50.0,
field.players.iter().filter(|p| p.team_id == 1).collect(),
field.ball.current_owner,
scale,
);
// FPS
const AVERAGE_FPS_BUCKET_SIZE: usize = 50;
let mut max_fps: u128 = 0;
let mut fps_data = [0u128; AVERAGE_FPS_BUCKET_SIZE];
let fps_data_current_idx = (current_frame % AVERAGE_FPS_BUCKET_SIZE as u64) as usize;
let elapsed_mcs = elapsed.as_micros();
fps_data[fps_data_current_idx] = elapsed.as_micros();
if current_frame > 100 && elapsed_mcs > max_fps {
max_fps = elapsed_mcs;
}
draw_fps(offset_x, offset_y, &fps_data, max_fps);
left_mouse_pressed = is_mouse_button_down(MouseButton::Left);
if left_mouse_pressed {
std::thread::sleep(Duration::from_millis(500));
}
next_frame().await;
}
}
const TRACKING_PLAYER_ID: u32 = 0;
pub fn get_home_squad() -> MatchSquad {
let players = [
get_player(101, PlayerPositionType::Goalkeeper),
get_player(102, PlayerPositionType::DefenderLeft),
get_player(103, PlayerPositionType::DefenderCenterLeft),
get_player(104, PlayerPositionType::DefenderCenterRight),
get_player(105, PlayerPositionType::DefenderRight),
get_player(106, PlayerPositionType::MidfielderLeft),
get_player(107, PlayerPositionType::MidfielderCenterLeft),
get_player(108, PlayerPositionType::MidfielderCenterRight),
get_player(109, PlayerPositionType::MidfielderRight),
get_player(110, PlayerPositionType::ForwardLeft),
get_player(111, PlayerPositionType::ForwardRight),
];
let match_players: Vec<MatchPlayer> = players
.iter()
.map(|player| {
MatchPlayer::from_player(
1,
player,
player.position(),
player.id == TRACKING_PLAYER_ID,
)
})
.collect();
let home_squad = MatchSquad {
team_id: 1,
team_name: String::from("123"),
tactics: Tactics::new(MatchTacticType::T442),
main_squad: match_players,
substitutes: Vec::new(),
captain_id: None,
vice_captain_id: None,
penalty_taker_id: None,
free_kick_taker_id: None,
};
home_squad
}
pub fn get_away_squad() -> MatchSquad {
let players = [
get_player(113, PlayerPositionType::Goalkeeper),
get_player(114, PlayerPositionType::DefenderLeft),
get_player(115, PlayerPositionType::DefenderCenterLeft),
get_player(116, PlayerPositionType::DefenderCenterRight),
get_player(117, PlayerPositionType::DefenderRight),
get_player(118, PlayerPositionType::MidfielderLeft),
get_player(119, PlayerPositionType::MidfielderCenterLeft),
get_player(120, PlayerPositionType::MidfielderCenterRight),
get_player(121, PlayerPositionType::MidfielderRight),
get_player(122, PlayerPositionType::ForwardLeft),
get_player(123, PlayerPositionType::ForwardRight),
];
let match_players: Vec<MatchPlayer> = players
.iter()
.map(|player| {
MatchPlayer::from_player(
2,
player,
player.position(),
player.id == TRACKING_PLAYER_ID,
)
})
.collect();
MatchSquad {
team_id: 2,
team_name: String::from("321"),
tactics: Tactics::new(MatchTacticType::T442),
main_squad: match_players,
substitutes: Vec::new(),
captain_id: None,
vice_captain_id: None,
penalty_taker_id: None,
free_kick_taker_id: None,
}
}
fn get_player(id: u32, position: PlayerPositionType) -> Player {
let mut player = PlayerGenerator::generate(
1,
NaiveDate::from_ymd_opt(2023, 1, 1).unwrap(),
position,
20,
);
player.id = id;
player
}
fn average(numbers: &[u128]) -> u128 {
let sum: u128 = numbers.iter().sum();
let count = numbers.len() as u128;
sum / count
}
fn player_state(player: &MatchPlayer) -> String {
let state = player.state.to_string();
let cleaned_state = state.split(':').nth(1).unwrap_or(&state).trim();
cleaned_state.to_string()
}
fn distance(a: &Vector3<f32>, b: &Vector3<f32>) -> usize {
((a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2)).sqrt() as usize
}
pub fn is_towards_player(
ball_position: &Vector3<f32>,
ball_velocity: &Vector3<f32>,
player_position: &Vector3<f32>,
) -> (bool, f32) {
MatchBallLogic::is_heading_towards_player(ball_position, ball_velocity, player_position, 0.95)
}
#[cfg(target_os = "macos")]
const WINDOW_WIDTH: i32 = 1040;
#[cfg(target_os = "macos")]
const WINDOW_HEIGHT: i32 = 900;
#[cfg(target_os = "linux")]
const WINDOW_WIDTH: i32 = 1948;
#[cfg(target_os = "linux")]
const WINDOW_HEIGHT: i32 = 1721;
#[cfg(target_os = "windows")]
const WINDOW_WIDTH: i32 = 1948;
#[cfg(target_os = "windows")]
const WINDOW_HEIGHT: i32 = 1721;
fn window_conf() -> Conf {
Conf {
window_title: "OpenFootball Match Development".to_owned(),
window_width: WINDOW_WIDTH,
window_height: WINDOW_HEIGHT,
window_resizable: false,
fullscreen: false,
high_dpi: true,
..Default::default()
}
}
// draw
fn draw_fps(offset_x: f32, offset_y: f32, fps_data: &[u128], max_fps: u128) {
draw_text(
&format!("FPS AVG: {} mcs", average(&fps_data)),
offset_x + 10.0,
offset_y + 20.0,
20.0,
BLACK,
);
draw_text(
&format!("FPS MAX: {} mcs", max_fps),
offset_x + 10.0,
offset_y + 40.0,
20.0,
BLACK,
);
}
fn draw_speed_control(offset_x: f32, offset_y: f32, field_width: f32, selected_speed: &mut MatchSpeed) {
// All sizes reduced by 50%, then widths reduced by additional 40%
let label_width = 36.0; // Was 60.0 (60% of 60.0)
let button_width = 24.0; // Was 40.0 (60% of 40.0)
let button_height = 15.0; // Was 30.0 (height unchanged)
let button_spacing = 3.0; // Was 5.0 (60% of 5.0)
let font_size = 10.0; // Was 20.0 (unchanged)
let speeds = MatchSpeed::all();
let num_buttons = speeds.len() as f32;
// Calculate total width of the control
let total_width = label_width + (button_width * num_buttons) + (button_spacing * (num_buttons - 1.0));
// Position at top right corner
let x = offset_x + field_width - total_width - 10.0; // 10.0 padding from right edge
let y = offset_y - 25.0; // Position above the field
let mut current_x = x + label_width;
for speed in &speeds {
let is_selected = *selected_speed == *speed;
// Draw radio button background
let bg_color = if is_selected {
Color::from_rgba(100, 200, 100, 255) // Green when selected
} else {
Color::from_rgba(200, 200, 200, 255) // Gray when not selected
};
draw_rectangle(current_x, y, button_width, button_height, bg_color);
// Draw button border
let border_color = if is_selected {
Color::from_rgba(50, 150, 50, 255)
} else {
Color::from_rgba(100, 100, 100, 255)
};
draw_rectangle_lines(current_x, y, button_width, button_height, 1.0, border_color);
// Draw button text (centered)
let text = speed.label();
let text_width = 15.0; // Approximate width for smaller font
let text_x = current_x + (button_width - text_width) / 2.0;
let text_y = y + button_height / 2.0 + 3.0;
draw_text(text, text_x, text_y, font_size, BLACK);
// Check if button is clicked
if is_mouse_button_pressed(MouseButton::Left) {
let (mouse_x, mouse_y) = mouse_position();
if mouse_x >= current_x
&& mouse_x <= current_x + button_width
&& mouse_y >= y
&& mouse_y <= y + button_height
{
*selected_speed = *speed;
}
}
current_x += button_width + button_spacing;
}
}
fn draw_waypoints(offset_x: f32, offset_y: f32, field: &MatchField, scale: f32) {
field.players.iter().for_each(|player| {
let waypoints = player.get_waypoints_as_vectors();
if waypoints.is_empty() {
return;
}
// Determine color based on team
let waypoint_color = if player.side == Some(PlayerSide::Left) {
Color::from_rgba(0, 184, 186, 100) // Semi-transparent cyan for left team
} else {
Color::from_rgba(208, 139, 255, 100) // Semi-transparent purple for right team
};
let line_color = if player.side == Some(PlayerSide::Left) {
Color::from_rgba(0, 184, 186, 180) // More opaque line
} else {
Color::from_rgba(208, 139, 255, 180)
};
// Draw lines connecting waypoints
for i in 0..waypoints.len() {
let current = &waypoints[i];
let current_x = offset_x + current.x * scale;
let current_y = offset_y + current.y * scale;
// Draw line to next waypoint
if i < waypoints.len() - 1 {
let next = &waypoints[i + 1];
let next_x = offset_x + next.x * scale;
let next_y = offset_y + next.y * scale;
draw_line(
current_x,
current_y,
next_x,
next_y,
1.5 * scale,
line_color,
);
}
// Draw waypoint circle
let radius = 3.0 * scale;
draw_circle(current_x, current_y, radius, waypoint_color);
// Highlight current waypoint
if i == player.waypoint_manager.current_index && !player.waypoint_manager.path_completed {
draw_circle_lines(current_x, current_y, radius + 2.0 * scale, 2.0, RED);
}
}
// Draw line from player to current waypoint
if !player.waypoint_manager.path_completed {
let current_waypoint_idx = player.waypoint_manager.current_index;
if current_waypoint_idx < waypoints.len() {
let waypoint = &waypoints[current_waypoint_idx];
let waypoint_x = offset_x + waypoint.x * scale;
let waypoint_y = offset_y + waypoint.y * scale;
let player_x = offset_x + player.position.x * scale;
let player_y = offset_y + player.position.y * scale;
draw_line(
player_x,
player_y,
waypoint_x,
waypoint_y,
1.0 * scale,
Color::from_rgba(255, 100, 100, 150), // Red dashed-looking line
);
}
}
});
}
fn draw_goals(offset_x: f32, offset_y: f32, context: &MatchContext, field_width: f32, scale: f32) {
let color = Color::from_rgba(0, 184, 186, 255);
draw_line(
offset_x,
offset_y + context.goal_positions.left.y * scale - GOAL_WIDTH * scale,
offset_x,
offset_y + context.goal_positions.left.y * scale + GOAL_WIDTH * scale,
15.0,
color,
);
draw_line(
offset_x + field_width,
offset_y + context.goal_positions.right.y * scale - GOAL_WIDTH * scale,
offset_x + field_width,
offset_y + context.goal_positions.right.y * scale + GOAL_WIDTH * scale,
15.0,
color,
);
}
fn draw_players(
offset_x: f32,
offset_y: f32,
field: &MatchField,
ball_owner_id: Option<u32>,
pass_target: Option<&PassTargetInfo>,
scale: f32,
) {
field.players.iter().for_each(|player| {
let translated_x = offset_x + player.position.x * scale;
let translated_y = offset_y + player.position.y * scale;
let mut color = if player.side == Some(PlayerSide::Left) {
Color::from_rgba(0, 184, 186, 255)
} else {
Color::from_rgba(208, 139, 255, 255)
};
if player.tactical_position.current_position == PlayerPositionType::Goalkeeper {
color = YELLOW;
}
let circle_radius = 15.0 * scale;
// Draw the player circle
draw_circle(translated_x, translated_y, circle_radius, color);
// Draw red circle around pass target player
if let Some(target_info) = pass_target {
if player.id == target_info.target_player_id {
draw_circle_lines(
translated_x,
translated_y,
circle_radius + 8.0 * scale,
4.0,
RED,
);
}
}
if Some(player.id) == ball_owner_id {
draw_circle_lines(
translated_x,
translated_y,
circle_radius + scale - 2.0,
5.0,
ORANGE,
);
}
// Player position
let position = &player.tactical_position.current_position.get_short_name();
let position_font_size = 17.0 * scale;
let position_text_dimensions = measure_text(position, None, position_font_size as u16, 1.0);
draw_text(
position,
translated_x - position_text_dimensions.width / 2.0,
translated_y + position_text_dimensions.height / 3.0,
position_font_size,
BLACK,
);
// Player ID
let id_text = &player.id.to_string();
let id_font_size = 9.0 * scale;
let id_text_dimensions = measure_text(id_text, None, id_font_size as u16, 1.0);
draw_text(
id_text,
translated_x - id_text_dimensions.width / 2.0,
translated_y + position_text_dimensions.height + id_text_dimensions.height / 2.0,
id_font_size,
DARKGRAY,
);
// Player state and distance
let distance = distance(&field.ball.position, &player.position);
let state_distance_text = &format!("{} ({})", player_state(player), distance);
let state_distance_font_size = 13.0 * scale;
let state_distance_text_dimensions = measure_text(
state_distance_text,
None,
state_distance_font_size as u16,
1.0,
);
draw_text(
state_distance_text,
translated_x - state_distance_text_dimensions.width / 2.5,
translated_y + circle_radius + state_distance_text_dimensions.height + 0.0,
state_distance_font_size,
DARKGRAY,
);
// ID
let max_speed = player.skills.max_speed_with_condition(player.player_attributes.condition);
let distance_to_opponent_goal = &format!("c = {} ({})", player.player_attributes.condition, max_speed);
let distance_to_opponent_goal_font_size = 13.0 * scale;
let distance_to_opponent_goal_text_dimensions = measure_text(
distance_to_opponent_goal,
None,
distance_to_opponent_goal_font_size as u16,
1.0,
);
draw_text(
distance_to_opponent_goal,
translated_x - distance_to_opponent_goal_text_dimensions.width / 2.5,
translated_y + circle_radius + distance_to_opponent_goal_text_dimensions.height + 15.0,
distance_to_opponent_goal_font_size,
DARKGRAY,
);
});
}
fn draw_ball(offset_x: f32, offset_y: f32, ball: &Ball, scale: f32) {
let translated_x = offset_x + ball.position.x * scale;
let translated_y = offset_y + ball.position.y * scale;
// Calculate visual scale based on height (perspective effect)
// The higher the ball, the larger it appears (simulating it being closer to camera)
let height_scale = 1.0 + (ball.position.z / 15.0).min(0.4);
let ball_radius = (7.0 / 1.5) * scale * height_scale;
// Draw the ball at its elevated position
// Adjust y-position to simulate 3D height (isometric-like projection)
let visual_y_offset = ball.position.z * scale * 0.5; // Scale z-height for visual effect
let ball_visual_y = translated_y - visual_y_offset;
// Draw simple white ball with black border
draw_circle(translated_x, ball_visual_y, ball_radius, WHITE);
draw_circle_lines(translated_x, ball_visual_y, ball_radius, 2.0, BLACK);
// Draw black filled circle in the center
let center_circle_radius = ball_radius * 0.3;
draw_circle(translated_x, ball_visual_y, center_circle_radius, BLACK);
draw_text(
&format!(
"BALL POS: x:{:.1}, y:{:.1}, z:{:.1}, IS_OUTSIDE: {:?}, IS_STANDS_OUTSIDE: {:?}, NOTIFIED: {:?}",
ball.position.x,
ball.position.y,
ball.position.z,
ball.is_ball_outside(),
ball.is_stands_outside(),
ball.take_ball_notified_players
),
20.0,
15.0,
15.0,
BLACK,
);
draw_text(
&format!("BALL VEL: x:{:.1}, y:{:.1}, z:{:.1}", ball.velocity.x, ball.velocity.y, ball.velocity.z),
20.0,
30.0,
15.0,
BLACK,
);
}
fn draw_player_list(
offset_x: f32,
offset_y: f32,
players: Vec<&MatchPlayer>,
ball_owner_id: Option<u32>,
scale: f32,
) {
let player_width = 25.0 * scale;
let player_height = 25.0 * scale;
let player_spacing = 40.0 * scale;
players.iter().enumerate().for_each(|(index, player)| {
let player_x = offset_x + index as f32 * (player_width + player_spacing);
let player_y = offset_y;
// Draw player circle
let player_color: Color =
if player.tactical_position.current_position == PlayerPositionType::Goalkeeper {
YELLOW
} else if player.team_id == 1 {
Color::from_rgba(0, 184, 186, 255)
} else {
Color::from_rgba(208, 139, 255, 255)
};
let circle_radius = player_width / 2.0;
draw_circle(
player_x + circle_radius,
player_y + circle_radius,
circle_radius,
player_color,
);
if Some(player.id) == ball_owner_id {
draw_circle_lines(
player_x + circle_radius,
player_y + circle_radius,
circle_radius + scale - 2.0,
5.0,
ORANGE,
);
}
// Draw player number
let player_number = player.id.to_string();
let number_font_size = 14.0 * scale;
let number_dimensions = measure_text(&player_number, None, number_font_size as u16, 1.0);
draw_text(
&player_number,
player_x + circle_radius - number_dimensions.width / 2.0,
player_y + circle_radius + number_dimensions.height / 4.0,
number_font_size,
BLACK,
);
// Draw player state
let state_text = player_state(player);
let state_font_size = 12.0 * scale;
let state_dimensions = measure_text(&state_text, None, state_font_size as u16, 1.0);
draw_text(
&state_text,
player_x + circle_radius - state_dimensions.width / 2.0,
player_y + player_height + state_dimensions.height / 2.0 + 5.0,
state_font_size,
BLACK,
);
});
}
/// Update field positions from replay data at a specific timestamp
fn update_positions_from_replay(field: &mut MatchField, match_data: &ResultMatchPositionData, timestamp: u64) {
// Update ball position
if let Some(ball_pos) = match_data.get_ball_position_at(timestamp) {
field.ball.position = ball_pos;
}
// Update all player positions
for player in field.players.iter_mut() {
if let Some(player_pos) = match_data.get_player_position_at(player.id, timestamp) {
player.position = player_pos;
}
}
}
/// Draw time slider and playback controls (simple design)
fn draw_time_slider(
offset_x: f32,
offset_y: f32,
total_width: f32,
match_data: &ResultMatchPositionData,
play_mode: &mut PlayMode,
is_paused: &mut bool,
replay_time: &mut u64,
max_live_time: u64,
) {
// Use max_live_time as the maximum time for the slider
// This represents the furthest point the simulation has reached
let max_time = max_live_time;
// Play/Pause button on the left
let button_size = 30.0;
let button_x = offset_x;
let button_y = offset_y;
// Get mouse position once
let (mouse_x, mouse_y) = mouse_position();
let button_color = Color::from_rgba(100, 200, 100, 255);
// Draw button circle
let button_center_x = button_x + button_size / 2.0;
let button_center_y = button_y + button_size / 2.0;
draw_circle(button_center_x, button_center_y, button_size / 2.0, button_color);
draw_circle_lines(button_center_x, button_center_y, button_size / 2.0, 2.0, BLACK);
// Draw play/pause icon
if *is_paused {
// Play triangle
let size = 8.0;
draw_triangle(
Vec2::new(button_center_x - size / 2.0, button_center_y - size),
Vec2::new(button_center_x - size / 2.0, button_center_y + size),
Vec2::new(button_center_x + size, button_center_y),
BLACK,
);
} else {
// Pause bars
let bar_width = 3.0;
let bar_height = 10.0;
let bar_spacing = 4.0;
draw_rectangle(button_center_x - bar_spacing - bar_width, button_center_y - bar_height / 2.0, bar_width, bar_height, BLACK);
draw_rectangle(button_center_x + bar_spacing, button_center_y - bar_height / 2.0, bar_width, bar_height, BLACK);
}
// Only check button click when mouse is actually pressed
if is_mouse_button_pressed(MouseButton::Left) {
let button_rect = Rect::new(button_x, button_y, button_size, button_size);
if button_rect.contains(Vec2::new(mouse_x, mouse_y)) {
*is_paused = !*is_paused;
}
}
// Slider bar
let slider_padding = 10.0;
let slider_x = offset_x + button_size + slider_padding;
let slider_width = total_width - button_size - slider_padding - 100.0; // Leave space for time text
let slider_height = 4.0;
let slider_y = offset_y + button_size / 2.0 - slider_height / 2.0;
// Draw background bar (gray)
draw_rectangle(slider_x, slider_y, slider_width, slider_height, GRAY);
// Draw progress bar (blue)
if max_time > 0 {
let progress = (*replay_time as f32 / max_time as f32).clamp(0.0, 1.0);
draw_rectangle(
slider_x,
slider_y,
slider_width * progress,
slider_height,
BLUE,
);
// Draw circle handle
let handle_x = slider_x + slider_width * progress;
let handle_y = slider_y + slider_height / 2.0;
let handle_radius = 8.0;
draw_circle(handle_x, handle_y, handle_radius, WHITE);
draw_circle_lines(handle_x, handle_y, handle_radius, 2.0, BLUE);
}
// Handle mouse interaction with slider (only when mouse is pressed)
if max_time > 0 && is_mouse_button_down(MouseButton::Left) {
let mouse_on_slider = mouse_x >= slider_x - 10.0
&& mouse_x <= slider_x + slider_width + 10.0
&& mouse_y >= slider_y - 15.0
&& mouse_y <= slider_y + slider_height + 15.0;
if mouse_on_slider {
// User is dragging the slider
let relative_x = (mouse_x - slider_x).clamp(0.0, slider_width);
let new_progress = relative_x / slider_width;
*replay_time = (new_progress * max_time as f32) as u64;
// Switch to replay mode when dragging
if *play_mode == PlayMode::Live {
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/neural/src/lib.rs | src/neural/src/lib.rs | #![recursion_limit = "256"]
mod r#match;
use burn::backend::NdArray;
use burn::backend::ndarray::NdArrayDevice;
pub use burn::prelude::*;
pub use r#match::*;
// DEFAULTS
pub type DefaultNeuralBackend = NdArray;
pub const DEFAULT_NEURAL_DEVICE: NdArrayDevice = NdArrayDevice::Cpu;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/neural/src/match/mod.rs | src/neural/src/match/mod.rs | pub mod midfielder;
pub use midfielder::*; | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/neural/src/match/midfielder/mod.rs | src/neural/src/match/midfielder/mod.rs | mod passing;
pub use passing::*; | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/neural/src/match/midfielder/passing.rs | src/neural/src/match/midfielder/passing.rs | use burn::config::Config;
use burn::nn::Initializer;
use burn::nn::{Linear, LinearConfig, Relu};
use std::sync::LazyLock;
use crate::{DefaultNeuralBackend, DEFAULT_NEURAL_DEVICE};
use burn::prelude::{Backend, Module};
use burn::record::{BinBytesRecorder, FullPrecisionSettings, Recorder};
use burn::tensor::Tensor;
static MODEL_BYTES: &[u8] = include_bytes!("model.bin");
pub static MIDFIELDER_PASSING_NEURAL_NETWORK: LazyLock<
MidfielderPassingNeural<DefaultNeuralBackend>,
> = LazyLock::new(|| {
let record = BinBytesRecorder::<FullPrecisionSettings>::default()
.load(MODEL_BYTES.to_vec(), &DEFAULT_NEURAL_DEVICE)
.expect("nn model load failed");
MidfielderPassingNeuralConfig::init(&DEFAULT_NEURAL_DEVICE).load_record(record)
});
#[derive(Module, Debug)]
pub struct MidfielderPassingNeural<B: Backend> {
linear_a: Linear<B>,
linear_b: Linear<B>,
linear_c: Linear<B>,
linear_d: Linear<B>,
activation: Relu,
}
unsafe impl<B> Sync for MidfielderPassingNeural<B> where B: Backend {}
impl<B: Backend> MidfielderPassingNeural<B> {
pub fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> {
let out = self.activation.forward(self.linear_a.forward(input));
let out = self.activation.forward(self.linear_b.forward(out));
let out = self.activation.forward(self.linear_c.forward(out));
let out = self.activation.forward(self.linear_d.forward(out));
out
}
}
#[derive(Debug, Config)]
pub struct MidfielderPassingNeuralConfig {
linear_a: LinearConfig,
linear_b: LinearConfig,
linear_c: LinearConfig,
linear_d: LinearConfig,
}
impl MidfielderPassingNeuralConfig {
pub fn init<B: Backend>(device: &B::Device) -> MidfielderPassingNeural<B> {
MidfielderPassingNeural {
linear_a: LinearConfig::new(2, 32)
.with_initializer(Initializer::Uniform { min: 0.0, max: 1.0 })
.with_bias(true)
.init(device),
linear_b: LinearConfig::new(32, 32)
.with_initializer(Initializer::Uniform { min: 0.0, max: 1.0 })
.with_bias(true)
.init(device),
linear_c: LinearConfig::new(32,16)
.with_initializer(Initializer::Uniform { min: 0.0, max: 1.0 })
.with_bias(true)
.init(device),
linear_d: LinearConfig::new(16, 1)
.with_initializer(Initializer::Uniform { min: 0.0, max: 1.0 })
.with_bias(true)
.init(device),
activation: Relu::new().to_owned(),
}
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/lib.rs | src/core/src/lib.rs | pub mod simulator;
pub use simulator::*;
pub mod club;
pub mod context;
pub mod continent;
pub mod country;
pub mod league;
pub mod r#match;
pub mod transfers;
pub mod shared;
pub mod utils;
// Re-export club items
pub use club::{
// Modules
academy, board, mood, transfers as club_transfers,
// Person exports
Person, PersonAttributes, PersonBehaviour, PersonBehaviourState,
// Club itself
Club, ClubBoard, ClubResult,
ClubContext,
// Finance exports
ClubFinances, ClubFinancialBalance, ClubFinancialBalanceHistory,
ClubSponsorship, ClubSponsorshipContract,
ClubFinanceContext, ClubFinanceResult,
// Relations exports
Relations, PlayerRelation, StaffRelation, ChemistryFactors,
ChangeType, MentorshipType, InfluenceLevel, ConflictType, ConflictSeverity,
RelationshipChange, ConflictInfo,
// Transfers exports
ClubTransferStrategy,
// Player exports
Player, PlayerCollection, PlayerBuilder,
PlayerAttributes, PlayerContext,
PlayerPreferredFoot, PlayerPositionType, PlayerFieldPositionGroup, PlayerStatusType,
PlayerSkills, Technical, Mental, Physical,
PlayerPositions, PlayerPosition, PlayerStatus, StatusData,
PlayerStatistics, PlayerStatisticsHistory, PlayerStatisticsHistoryItem,
PlayerHappiness, PositiveHappiness, NegativeHappiness,
PlayerClubContract, ContractType, PlayerSquadStatus, PlayerTransferStatus,
ContractBonusType, ContractBonus, ContractClauseType, ContractClause,
PlayerMailbox, PlayerMessage, PlayerMessageType, PlayerContractProposal, PlayerMailboxResult,
AcceptContractHandler, ProcessContractHandler, handlers,
PlayerTraining, PlayerTrainingHistory, TrainingRecord, PlayerTrainingResult,
PlayerResult, PlayerCollectionResult, PlayerContractResult,
PlayerValueCalculator, PlayerGenerator, PlayerUtils,
player_context, player_attributes_mod, player_contract_mod, player_builder_mod,
CONDITION_MAX_VALUE,
// Staff exports
Staff, StaffCollection, StaffStub,
StaffAttributes, StaffContext,
StaffCoaching, StaffGoalkeeperCoaching, StaffMental,
StaffKnowledge, StaffDataAnalysis, StaffMedical,
StaffClubContract, StaffPosition, StaffStatus,
CoachFocus, TechnicalFocusType, MentalFocusType, PhysicalFocusType,
StaffResponsibility, BoardResponsibility, RecruitmentResponsibility,
IncomingTransfersResponsibility, OutgoingTransfersResponsibility,
ContractRenewalResponsibility, ScoutingResponsibility, TrainingResponsibility,
StaffPerformance, CoachingStyle,
StaffResult, StaffCollectionResult, StaffContractResult, StaffTrainingResult,
StaffWarning, StaffMoraleEvent, ResignationReason, HealthIssue,
RelationshipEvent, StaffLicenseType, StaffTrainingSession,
staff_context, staff_attributes_mod, staff_contract_mod,
// Team exports
Team, TeamCollection, TeamType, TeamBuilder, TeamContext,
TeamResult,
TeamBehaviour, TeamBehaviourResult, PlayerBehaviourResult, PlayerRelationshipChangeResult,
Tactics, TacticalStyle, MatchTacticType, TacticSelectionReason, TacticsSelector,
TacticalDecisionEngine, TacticalDecisionResult, FormationChange, SquadAnalysis,
TacticalRecommendation, RecommendationPriority, RecommendationCategory,
TeamTraining, TeamTrainingResult, TrainingSchedule, TrainingType,
TrainingSession, TrainingIntensity, WeeklyTrainingPlan, PeriodizationPhase,
TrainingEffects, PhysicalGains, TechnicalGains, MentalGains,
IndividualTrainingPlan, TrainingFocus, SkillType, SpecialInstruction,
CoachingPhilosophy, TacticalFocus, TrainingIntensityPreference, RotationPreference,
TrainingFacilities, FacilityQuality, TrainingLoadManager, PlayerTrainingLoad,
Transfers, TransferItem,
MatchHistory, MatchHistoryItem,
TeamReputation, ReputationLevel, ReputationTrend, Achievement, AchievementType,
MatchResultInfo, MatchOutcome, ReputationRequirements,
team_context, team_builder_mod, team_training_mod, team_transfers_mod,
behaviour, collection, matches, reputation, tactics,
TACTICS_POSITIONS,
TeamCompetitionType,
// Status & mood
ClubStatus, ClubMood,
};
// Re-export country items
pub use country::{
Country, CountryResult, CountryContext,
CountryEconomicFactors, InternationalCompetition, MediaCoverage,
MediaStory, StoryType, CountryRegulations, CountryGeneratorData,
PeopleNameGeneratorData,
};
// Namespace conflicting CompetitionType enums
// Country's CompetitionType is for continental competitions (ChampionsLeague, etc.)
pub use country::CompetitionType as ContinentalCompetitionType;
pub use nalgebra::*;
pub use utils::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/simulator.rs | src/core/src/simulator.rs | use crate::context::{GlobalContext, SimulationContext};
use crate::continent::{Continent, ContinentResult};
use crate::league::League;
use crate::r#match::MatchResult;
use crate::shared::{SimulatorDataIndexes, TeamData};
use crate::transfers::TransferPool;
use crate::utils::Logging;
use crate::{Club, Country, Player, Team};
use chrono::{Duration, NaiveDateTime};
pub struct FootballSimulator;
impl FootballSimulator {
pub fn simulate(data: &mut SimulatorData) -> SimulationResult {
let mut result = SimulationResult::new();
let current_data = data.date;
Logging::estimate(
|| {
let ctx = GlobalContext::new(SimulationContext::new(data.date));
let results: Vec<ContinentResult> = data
.continents
.iter_mut()
.map(|continent| continent.simulate(ctx.with_continent(continent.id)))
.collect();
for continent_result in results {
continent_result.process(data, &mut result);
}
data.next_date();
},
&format!("simulate date {}", current_data),
);
result
}
}
pub struct SimulatorData {
pub continents: Vec<Continent>,
pub date: NaiveDateTime,
pub transfer_pool: TransferPool<Player>,
pub indexes: Option<SimulatorDataIndexes>,
pub match_played: bool
}
impl SimulatorData {
pub fn new(date: NaiveDateTime, continents: Vec<Continent>) -> Self {
let mut data = SimulatorData {
continents,
date,
transfer_pool: TransferPool::new(),
indexes: None,
match_played: false
};
let mut indexes = SimulatorDataIndexes::new();
indexes.refresh(&data);
data.indexes = Some(indexes);
data
}
pub fn next_date(&mut self) {
self.date += Duration::days(1);
}
pub fn continent(&self, id: u32) -> Option<&Continent> {
self.continents.iter().find(|c| c.id == id)
}
pub fn continent_mut(&mut self, id: u32) -> Option<&mut Continent> {
self.continents.iter_mut().find(|c| c.id == id)
}
pub fn country(&self, id: u32) -> Option<&Country> {
self.continents
.iter()
.flat_map(|c| &c.countries)
.find(|c| c.id == id)
}
pub fn country_mut(&mut self, id: u32) -> Option<&mut Country> {
self.continents
.iter_mut()
.flat_map(|c| &mut c.countries)
.find(|c| c.id == id)
}
pub fn league(&self, id: u32) -> Option<&League> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_league_location(id))
.and_then(|(league_continent_id, league_country_id)| {
self.continent(league_continent_id)
.and_then(|continent| {
continent
.countries
.iter()
.find(|country| country.id == league_country_id)
})
.and_then(|country| {
country
.leagues
.leagues
.iter()
.find(|league| league.id == id)
})
})
}
pub fn league_mut(&mut self, id: u32) -> Option<&mut League> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_league_location(id))
.and_then(|(league_continent_id, league_country_id)| {
self.continent_mut(league_continent_id)
.and_then(|continent| {
continent
.countries
.iter_mut()
.find(|country| country.id == league_country_id)
})
.and_then(|country| {
country
.leagues
.leagues
.iter_mut()
.find(|league| league.id == id)
})
})
}
pub fn team_data(&self, id: u32) -> Option<&TeamData> {
self.indexes.as_ref().unwrap().get_team_data(id)
}
pub fn club(&self, id: u32) -> Option<&Club> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_club_location(id))
.and_then(|(club_continent_id, club_country_id)| {
self.continent(club_continent_id).and_then(|continent| {
continent
.countries
.iter()
.find(|country| country.id == club_country_id)
})
})
.and_then(|country| country.clubs.iter().find(|club| club.id == id))
}
pub fn club_mut(&mut self, id: u32) -> Option<&mut Club> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_club_location(id))
.and_then(|(club_continent_id, club_country_id)| {
self.continent_mut(club_continent_id).and_then(|continent| {
continent
.countries
.iter_mut()
.find(|country| country.id == club_country_id)
})
})
.and_then(|country| country.clubs.iter_mut().find(|club| club.id == id))
}
pub fn team(&self, id: u32) -> Option<&Team> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_team_location(id))
.and_then(|(team_continent_id, team_country_id, team_club_id)| {
self.continent(team_continent_id)
.and_then(|continent| {
continent
.countries
.iter()
.find(|country| country.id == team_country_id)
})
.and_then(|country| country.clubs.iter().find(|club| club.id == team_club_id))
.and_then(|club| club.teams.teams.iter().find(|team| team.id == id))
})
}
pub fn team_mut(&mut self, id: u32) -> Option<&mut Team> {
self.indexes
.as_ref()
.and_then(|indexes| indexes.get_team_location(id))
.and_then(|(team_continent_id, team_country_id, team_club_id)| {
self.continent_mut(team_continent_id)
.and_then(|continent| {
continent
.countries
.iter_mut()
.find(|country| country.id == team_country_id)
})
.and_then(|country| {
country
.clubs
.iter_mut()
.find(|club| club.id == team_club_id)
})
.and_then(|club| club.teams.teams.iter_mut().find(|team| team.id == id))
})
}
pub fn player(&self, id: u32) -> Option<&Player> {
let (player_continent_id, player_country_id, player_club_id, player_team_id) = self
.indexes
.as_ref()
.and_then(|indexes| indexes.get_player_location(id))?;
self.continent(player_continent_id)
.and_then(|continent| {
continent
.countries
.iter()
.find(|country| country.id == player_country_id)
})
.and_then(|country| country.clubs.iter().find(|club| club.id == player_club_id))
.and_then(|club| {
club.teams
.teams
.iter()
.find(|team| team.id == player_team_id)
})
.and_then(|team| team.players.players.iter().find(|c| c.id == id))
}
pub fn player_mut(&mut self, id: u32) -> Option<&mut Player> {
let (player_continent_id, player_country_id, player_club_id, player_team_id) = self
.indexes
.as_ref()
.and_then(|indexes| indexes.get_player_location(id))?;
self.continent_mut(player_continent_id)
.and_then(|continent| {
continent
.countries
.iter_mut()
.find(|country| country.id == player_country_id)
})
.and_then(|country| {
country
.clubs
.iter_mut()
.find(|club| club.id == player_club_id)
})
.and_then(|club| {
club.teams
.teams
.iter_mut()
.find(|team| team.id == player_team_id)
})
.and_then(|team| team.players.players.iter_mut().find(|c| c.id == id))
}
}
pub struct SimulationResult {
pub match_results: Vec<MatchResult>,
}
impl SimulationResult {
pub fn new() -> Self {
SimulationResult {
match_results: Vec::new(),
}
}
pub fn has_match_results(&self) -> bool {
!self.match_results.is_empty()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/context.rs | src/core/src/context.rs | pub use chrono::prelude::*;
use crate::club::{BoardContext, ClubContext, ClubFinanceContext, PlayerContext, StaffContext};
use crate::continent::ContinentContext;
use crate::country::CountryContext;
use crate::league::LeagueContext;
use crate::TeamContext;
#[derive(Clone)]
pub struct GlobalContext<'gc> {
pub simulation: SimulationContext,
pub continent: Option<ContinentContext>,
pub country: Option<CountryContext>,
pub league: Option<LeagueContext<'gc>>,
pub club: Option<ClubContext<'gc>>,
pub team: Option<TeamContext>,
pub finance: Option<ClubFinanceContext>,
pub board: Option<BoardContext>,
pub player: Option<PlayerContext>,
pub staff: Option<StaffContext>,
}
impl<'gc> GlobalContext<'gc> {
pub fn new(simulation_ctx: SimulationContext) -> Self {
GlobalContext {
simulation: simulation_ctx,
continent: None,
country: None,
league: None,
club: None,
team: None,
finance: None,
board: None,
player: None,
staff: None,
}
}
pub fn with_continent(&self, continent_id: u32) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.continent = Some(ContinentContext::new(continent_id));
ctx
}
pub fn with_country(&self, country_id: u32) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.country = Some(CountryContext::new(country_id));
ctx
}
pub fn with_league(&self, league_id: u32, league_slug: String, team_ids: &'gc [u32]) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.league = Some(LeagueContext::new(league_id, league_slug, team_ids));
ctx
}
pub fn with_club(&self, club_id: u32, club_name: &'gc str) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.club = Some(ClubContext::new(club_id, club_name));
ctx
}
pub fn with_team(&self, team_id: u32) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.team = Some(TeamContext::new(team_id));
ctx
}
pub fn with_board(&self) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.board = Some(BoardContext::new());
ctx
}
pub fn with_player(&self, player_id: Option<u32>) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.player = Some(PlayerContext::new(player_id));
ctx
}
pub fn with_staff(&self, staff_id: Option<u32>) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.staff = Some(StaffContext::new(staff_id));
ctx
}
pub fn with_finance(&self) -> Self {
let mut ctx = GlobalContext::clone(self);
ctx.finance = Some(ClubFinanceContext::new());
ctx
}
}
#[derive(Clone)]
pub struct SimulationContext {
pub date: NaiveDateTime,
pub day: u8,
pub hour: u8,
}
impl SimulationContext {
pub fn new(date: NaiveDateTime) -> Self {
SimulationContext {
date,
day: date.day() as u8,
hour: date.hour() as u8,
}
}
#[inline]
pub fn is_week_beginning(&self) -> bool {
self.date.weekday() == Weekday::Mon && self.date.hour() == 0
}
#[inline]
pub fn is_month_beginning(&self) -> bool {
self.day == 1u8
}
#[inline]
pub fn is_year_beginning(&self) -> bool {
self.day == 1u8 && self.date.month() == 1
}
#[inline]
pub fn check_contract_expiration(&self) -> bool {
self.hour == 0
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDate;
#[test]
fn test_simulation_context() {
// Create a new simulation context
let date = NaiveDate::from_ymd_opt(2024, 3, 16)
.unwrap()
.and_hms_opt(12, 30, 0)
.unwrap();
let sim_ctx = SimulationContext::new(date);
// Test if the date and time are set correctly
assert_eq!(sim_ctx.date, date);
assert_eq!(sim_ctx.day, 16);
assert_eq!(sim_ctx.hour, 12);
// Test the helper functions
assert!(!sim_ctx.is_week_beginning()); // Not Monday
assert!(!sim_ctx.is_month_beginning()); // Not the first day of the month
assert!(!sim_ctx.is_year_beginning()); // Not the first day of the year
assert!(!sim_ctx.check_contract_expiration()); // Not midnight
// Create a new simulation context at the beginning of the week
let monday_date = NaiveDate::from_ymd_opt(2024, 3, 18)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap();
let monday_sim_ctx = SimulationContext::new(monday_date);
// Test if the week beginning is detected correctly
assert!(monday_sim_ctx.is_week_beginning());
// Create a new simulation context at the beginning of the month
let first_of_month_date = NaiveDate::from_ymd_opt(2024, 3, 1)
.unwrap()
.and_hms_opt(12, 30, 0)
.unwrap();
let first_of_month_sim_ctx = SimulationContext::new(first_of_month_date);
// Test if the month beginning is detected correctly
assert!(first_of_month_sim_ctx.is_month_beginning());
// Create a new simulation context at the beginning of the year
let first_of_year_date = NaiveDate::from_ymd_opt(2024, 1, 1)
.unwrap()
.and_hms_opt(12, 30, 0)
.unwrap();
let first_of_year_sim_ctx = SimulationContext::new(first_of_year_date);
// Test if the year beginning is detected correctly
assert!(first_of_year_sim_ctx.is_year_beginning());
// Create a new simulation context at midnight
let midnight_date = NaiveDate::from_ymd_opt(2024, 3, 16)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap();
let midnight_sim_ctx = SimulationContext::new(midnight_date);
// Test if contract expiration is checked correctly at midnight
assert!(midnight_sim_ctx.check_contract_expiration());
}
#[test]
fn test_global_context() {
// Create a new simulation context
let date = NaiveDate::from_ymd_opt(2024, 3, 16)
.unwrap()
.and_hms_opt(12, 30, 0)
.unwrap();
let sim_ctx = SimulationContext::new(date);
// Create a global context with the simulation context
let global_ctx = GlobalContext::new(sim_ctx.clone());
// Test if the simulation context is set correctly
assert_eq!(global_ctx.simulation.date, sim_ctx.date);
assert_eq!(global_ctx.simulation.day, sim_ctx.day);
assert_eq!(global_ctx.simulation.hour, sim_ctx.hour);
// Test if other contexts are initially set to None
assert!(global_ctx.continent.is_none());
assert!(global_ctx.country.is_none());
assert!(global_ctx.league.is_none());
assert!(global_ctx.club.is_none());
assert!(global_ctx.team.is_none());
assert!(global_ctx.finance.is_none());
assert!(global_ctx.board.is_none());
assert!(global_ctx.player.is_none());
assert!(global_ctx.staff.is_none());
// Test if contexts can be added
let updated_global_ctx = global_ctx
.with_continent(1)
.with_country(1)
.with_league(1, "slug".to_owned(), &[1, 2])
.with_club(1, "Test Club")
.with_team(1)
.with_finance()
.with_board()
.with_player(Some(1))
.with_staff(Some(1));
// Test if the added contexts are set correctly
assert!(updated_global_ctx.continent.is_some());
assert!(updated_global_ctx.country.is_some());
assert!(updated_global_ctx.league.is_some());
assert!(updated_global_ctx.club.is_some());
assert!(updated_global_ctx.team.is_some());
assert!(updated_global_ctx.finance.is_some());
assert!(updated_global_ctx.board.is_some());
assert!(updated_global_ctx.player.is_some());
assert!(updated_global_ctx.staff.is_some());
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/state.rs | src/core/src/match/state.rs | use crate::r#match::MatchState;
pub struct GameState {
pub match_state: MatchState,
}
impl GameState {
pub fn new() -> Self {
GameState {
match_state: MatchState::Initial,
}
}
pub fn set(&mut self, match_state: MatchState) {
self.match_state = match_state;
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/result.rs | src/core/src/match/result.rs | use nalgebra::Vector3;
use serde::Serialize;
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize)]
pub struct PassEventData {
pub timestamp: u64,
pub from_player_id: u32,
pub to_player_id: u32,
}
impl PassEventData {
pub fn new(timestamp: u64, from_player_id: u32, to_player_id: u32) -> Self {
PassEventData {
timestamp,
from_player_id,
to_player_id,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ResultPositionDataItem {
pub timestamp: u64,
pub position: Vector3<f32>,
}
impl ResultPositionDataItem {
pub fn new(timestamp: u64, position: Vector3<f32>) -> Self {
ResultPositionDataItem {
timestamp,
position,
}
}
}
impl PartialEq<ResultPositionDataItem> for ResultPositionDataItem {
fn eq(&self, other: &Self) -> bool {
self.timestamp == other.timestamp && self.position == other.position
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ResultMatchPositionData {
ball: Vec<ResultPositionDataItem>,
players: HashMap<u32, Vec<ResultPositionDataItem>>,
passes: Vec<PassEventData>,
#[serde(skip)]
track_events: bool,
}
impl ResultMatchPositionData {
pub fn new() -> Self {
ResultMatchPositionData {
ball: Vec::new(),
players: HashMap::with_capacity(22 * 2 * 9000),
passes: Vec::new(),
track_events: false,
}
}
pub fn new_with_tracking() -> Self {
ResultMatchPositionData {
ball: Vec::new(),
players: HashMap::with_capacity(22 * 2 * 9000),
passes: Vec::new(),
track_events: true,
}
}
pub fn compress(&mut self) {}
/// Split the data into chunks based on time ranges
/// Returns a vector of chunks, each containing data for a specific time window
pub fn split_into_chunks(&self, chunk_duration_ms: u64) -> Vec<ResultMatchPositionData> {
if self.ball.is_empty() {
return vec![self.clone()];
}
let max_timestamp = self.max_timestamp();
let num_chunks = ((max_timestamp as f64 / chunk_duration_ms as f64).ceil() as usize).max(1);
let mut chunks = Vec::with_capacity(num_chunks);
for chunk_idx in 0..num_chunks {
let start_time = chunk_idx as u64 * chunk_duration_ms;
let end_time = start_time + chunk_duration_ms;
let mut chunk = ResultMatchPositionData {
ball: Vec::new(),
players: HashMap::new(),
passes: Vec::new(),
track_events: self.track_events,
};
// Filter ball positions for this time window
chunk.ball = self.ball.iter()
.filter(|item| item.timestamp >= start_time && item.timestamp < end_time)
.cloned()
.collect();
// Filter player positions for this time window
for (player_id, positions) in &self.players {
let filtered_positions: Vec<ResultPositionDataItem> = positions.iter()
.filter(|item| item.timestamp >= start_time && item.timestamp < end_time)
.cloned()
.collect();
if !filtered_positions.is_empty() {
chunk.players.insert(*player_id, filtered_positions);
}
}
// Filter passes for this time window
if self.track_events {
chunk.passes = self.passes.iter()
.filter(|pass| pass.timestamp >= start_time && pass.timestamp < end_time)
.cloned()
.collect();
}
chunks.push(chunk);
}
chunks
}
/// Check if event tracking is enabled
#[inline]
pub fn is_tracking_events(&self) -> bool {
self.track_events
}
pub fn add_player_positions(&mut self, player_id: u32, timestamp: u64, position: Vector3<f32>) {
if let Some(player_data) = self.players.get_mut(&player_id) {
let last_data = player_data.last().unwrap();
if last_data.position.x != position.x
|| last_data.position.y != position.y
|| last_data.position.z != position.z
{
let position_data = ResultPositionDataItem::new(timestamp, position);
player_data.push(position_data);
}
} else {
self.players
.insert(player_id, vec![ResultPositionDataItem::new(timestamp, position)]);
}
}
pub fn add_ball_positions(&mut self, timestamp: u64, position: Vector3<f32>) {
let position = ResultPositionDataItem::new(timestamp, position);
if let Some(last_position) = self.ball.last() {
if last_position != &position {
self.ball.push(position);
}
} else {
self.ball.push(position);
}
}
/// Get the maximum timestamp in the recorded data
pub fn max_timestamp(&self) -> u64 {
self.ball.last().map(|item| item.timestamp).unwrap_or(0)
}
/// Get ball position at a specific timestamp (uses nearest neighbor)
pub fn get_ball_position_at(&self, timestamp: u64) -> Option<Vector3<f32>> {
if self.ball.is_empty() {
return None;
}
// Binary search for the closest timestamp
let idx = self.ball.binary_search_by_key(×tamp, |item| item.timestamp)
.unwrap_or_else(|idx| {
if idx == 0 {
0
} else if idx >= self.ball.len() {
self.ball.len() - 1
} else {
// Choose nearest between idx-1 and idx
let before = &self.ball[idx - 1];
let after = &self.ball[idx];
if timestamp - before.timestamp < after.timestamp - timestamp {
idx - 1
} else {
idx
}
}
});
Some(self.ball[idx].position)
}
/// Get player position at a specific timestamp (uses nearest neighbor)
pub fn get_player_position_at(&self, player_id: u32, timestamp: u64) -> Option<Vector3<f32>> {
let player_data = self.players.get(&player_id)?;
if player_data.is_empty() {
return None;
}
// Binary search for the closest timestamp
let idx = player_data.binary_search_by_key(×tamp, |item| item.timestamp)
.unwrap_or_else(|idx| {
if idx == 0 {
0
} else if idx >= player_data.len() {
player_data.len() - 1
} else {
// Choose nearest between idx-1 and idx
let before = &player_data[idx - 1];
let after = &player_data[idx];
if timestamp - before.timestamp < after.timestamp - timestamp {
idx - 1
} else {
idx
}
}
});
Some(player_data[idx].position)
}
/// Get all player IDs that have recorded positions
pub fn get_player_ids(&self) -> Vec<u32> {
self.players.keys().copied().collect()
}
/// Add a pass event (only if event tracking is enabled)
pub fn add_pass_event(&mut self, timestamp: u64, from_player_id: u32, to_player_id: u32) {
if self.track_events {
self.passes.push(PassEventData::new(timestamp, from_player_id, to_player_id));
}
}
/// Get the most recent pass event at or before a timestamp
pub fn get_recent_pass_at(&self, timestamp: u64) -> Option<&PassEventData> {
// Find most recent pass that occurred at or before this timestamp
self.passes.iter()
.rev() // Search from most recent
.find(|pass| pass.timestamp <= timestamp)
}
/// Get all passes that occurred within a time window around the timestamp
pub fn get_passes_in_window(&self, timestamp: u64, window_ms: u64) -> Vec<&PassEventData> {
let start = timestamp.saturating_sub(window_ms);
let end = timestamp + window_ms;
self.passes.iter()
.filter(|pass| pass.timestamp >= start && pass.timestamp <= end)
.collect()
}
}
pub trait VectorExtensions {
fn length(&self) -> f32;
fn distance_to(&self, other: &Vector3<f32>) -> f32;
}
impl VectorExtensions for Vector3<f32> {
#[inline]
fn length(&self) -> f32 {
(self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
}
#[inline]
fn distance_to(&self, other: &Vector3<f32>) -> f32 {
let diff = self - other;
diff.dot(&diff).sqrt()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/game.rs | src/core/src/match/game.rs | use super::engine::FootballEngine;
use crate::r#match::{MatchResult, MatchSquad};
use log::debug;
#[derive(Debug, Clone)]
pub struct Match {
id: String,
league_id: u32,
league_slug: String,
pub home_squad: MatchSquad,
pub away_squad: MatchSquad,
}
impl Match {
pub fn make(
id: String,
league_id: u32,
league_slug: &str,
home_squad: MatchSquad,
away_squad: MatchSquad,
) -> Self {
Match {
id,
league_id,
league_slug: String::from(league_slug),
home_squad,
away_squad,
}
}
pub fn play(self) -> MatchResult {
let home_team_id = self.home_squad.team_id;
let home_team_name = String::from(&self.home_squad.team_name);
let away_team_id = self.away_squad.team_id;
let away_team_name = String::from(&self.away_squad.team_name);
let match_result = FootballEngine::<840, 545>::play(self.home_squad, self.away_squad);
let score = match_result.score.as_ref().expect("no score");
debug!(
"match played: {} {}:{} {}",
home_team_name,
score.home_team.get(),
away_team_name,
score.away_team.get(),
);
MatchResult {
id: self.id,
league_id: self.league_id,
league_slug: String::from(&self.league_slug),
home_team_id,
away_team_id,
score: score.clone(),
details: Some(match_result),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/mod.rs | src/core/src/match/mod.rs | pub mod engine;
pub mod game;
pub mod result;
pub mod squad;
pub mod state;
pub use engine::*;
pub use game::*;
pub use result::*;
pub use squad::*;
pub use state::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/field.rs | src/core/src/match/engine/field.rs | use crate::r#match::ball::Ball;
use crate::r#match::{FieldSquad, MatchFieldSize, MatchPlayer, MatchSquad, PlayerSide, PositionType, POSITION_POSITIONING};
use crate::Tactics;
use nalgebra::Vector3;
pub struct MatchField {
pub size: MatchFieldSize,
pub ball: Ball,
pub players: Vec<MatchPlayer>,
pub substitutes: Vec<MatchPlayer>,
pub home_team_id: u32,
pub away_team_id: u32,
pub left_side_players: Option<FieldSquad>,
pub left_team_tactics: Tactics,
pub right_side_players: Option<FieldSquad>,
pub right_team_tactics: Tactics,
}
impl MatchField {
pub fn new(
width: usize,
height: usize,
left_team_squad: MatchSquad,
right_team_squad: MatchSquad,
) -> Self {
let home_team_id = left_team_squad.team_id;
let away_team_id = right_team_squad.team_id;
let left_squad = FieldSquad::from_team(&left_team_squad);
let away_squad = FieldSquad::from_team(&right_team_squad);
let left_tactics = left_team_squad.tactics.clone();
let right_tactics = right_team_squad.tactics.clone();
let (players_on_field, substitutes) =
setup_player_on_field(left_team_squad, right_team_squad);
MatchField {
size: MatchFieldSize::new(width, height),
ball: Ball::with_coord(width as f32, height as f32),
players: players_on_field,
substitutes,
home_team_id,
away_team_id,
left_side_players: Some(left_squad),
left_team_tactics: left_tactics,
right_side_players: Some(away_squad),
right_team_tactics: right_tactics,
}
}
pub fn reset_players_positions(&mut self) {
self.players.iter_mut().for_each(|p| {
p.position = p.start_position;
p.velocity = Vector3::zeros();
p.set_default_state();
});
}
pub fn swap_squads(&mut self) {
std::mem::swap(&mut self.left_side_players, &mut self.right_side_players);
self.players.iter_mut().for_each(|p| {
if let Some(side) = &p.side {
let new_side = match side {
PlayerSide::Left => PlayerSide::Right,
PlayerSide::Right => PlayerSide::Left,
};
p.side = Some(new_side);
p.tactical_position.regenerate_waypoints(Some(new_side));
}
});
}
pub fn get_player(&mut self, id: u32) -> Option<&MatchPlayer> {
self.players.iter().find(|p| p.id == id)
}
pub fn get_player_mut(&mut self, id: u32) -> Option<&mut MatchPlayer> {
self.players.iter_mut().find(|p| p.id == id)
}
}
fn setup_player_on_field(
left_team_squad: MatchSquad,
right_team_squad: MatchSquad,
) -> (Vec<MatchPlayer>, Vec<MatchPlayer>) {
let setup_squad = |squad: MatchSquad, side: PlayerSide| {
let mut players = Vec::new();
let mut subs = Vec::new();
for mut player in squad.main_squad {
player.side = Some(side);
player.tactical_position.regenerate_waypoints(Some(side));
if let Some(position) = get_player_position(&player, side) {
player.position = position;
player.start_position = position;
players.push(player);
}
}
for mut player in squad.substitutes {
player.side = Some(side);
player.tactical_position.regenerate_waypoints(Some(side));
player.position = Vector3::new(1.0, 1.0, 0.0);
subs.push(player);
}
(players, subs)
};
let (left_players, left_subs) = setup_squad(left_team_squad, PlayerSide::Left);
let (right_players, right_subs) = setup_squad(right_team_squad, PlayerSide::Right);
(
[left_players, right_players].concat(),
[left_subs, right_subs].concat(),
)
}
fn get_player_position(player: &MatchPlayer, side: PlayerSide) -> Option<Vector3<f32>> {
POSITION_POSITIONING
.iter()
.find(|(pos, _, _)| *pos == player.tactical_position.current_position)
.and_then(|(_, home, away)| match side {
PlayerSide::Left => {
if let PositionType::Home(x, y) = home {
Some((*x as f32, *y as f32))
} else {
None
}
}
PlayerSide::Right => {
if let PositionType::Away(x, y) = away {
Some((*x as f32, *y as f32))
} else {
None
}
}
})
.map(|(x, y)| Vector3::new(x, y, 0.0))
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/engine.rs | src/core/src/match/engine/engine.rs | use crate::r#match::ball::events::GoalSide;
use crate::r#match::engine::events::dispatcher::EventCollection;
use crate::r#match::events::EventDispatcher;
use crate::r#match::field::MatchField;
use crate::r#match::result::ResultMatchPositionData;
use crate::r#match::{GameTickContext, MatchContext, MatchPlayer, MatchResultRaw, MatchSquad, Score, StateManager};
use crate::Tactics;
use nalgebra::Vector3;
use std::collections::HashMap;
pub struct FootballEngine<const W: usize, const H: usize> {}
impl<const W: usize, const H: usize> Default for FootballEngine<W, H> {
fn default() -> Self {
Self::new()
}
}
impl<const W: usize, const H: usize> FootballEngine<W, H> {
pub fn new() -> Self {
FootballEngine {}
}
pub fn play(left_squad: MatchSquad, right_squad: MatchSquad) -> MatchResultRaw {
let score = Score::new(left_squad.team_id, right_squad.team_id);
let players = MatchPlayerCollection::from_squads(&left_squad, &right_squad);
let mut match_position_data = ResultMatchPositionData::new();
let mut field = MatchField::new(W, H, left_squad, right_squad);
let mut context = MatchContext::new(&field, players, score);
let mut state_manager = StateManager::new();
while let Some(state) = state_manager.next() {
context.state.set(state);
let play_state_result =
Self::play_inner(&mut field, &mut context, &mut match_position_data);
StateManager::handle_state_finish(&mut context, &mut field, play_state_result);
}
let mut result = MatchResultRaw::with_match_time(context.total_match_time);
context.fill_details();
result.score = Some(context.score.clone());
// Assign squads based on team IDs, not field positions
// left_team_players and right_team_players in result represent home and away teams
let left_side_squad = field.left_side_players.expect("left team players");
let right_side_squad = field.right_side_players.expect("right team players");
// Check which field side has the home team using FieldSquad's team_id
if left_side_squad.team_id == field.home_team_id {
// Home team is on the left side
result.left_team_players = left_side_squad;
result.right_team_players = right_side_squad;
} else {
// Home team is on the right side (after swap)
result.left_team_players = right_side_squad;
result.right_team_players = left_side_squad;
}
result.position_data = match_position_data;
result
}
fn play_inner(
field: &mut MatchField,
context: &mut MatchContext,
match_data: &mut ResultMatchPositionData,
) -> PlayMatchStateResult {
let result = PlayMatchStateResult::default();
while context.increment_time() {
Self::game_tick(field, context, match_data);
}
result
}
pub fn game_tick(
field: &mut MatchField,
context: &mut MatchContext,
match_data: &mut ResultMatchPositionData,
) {
let game_tick_context = GameTickContext::new(field);
let mut events = EventCollection::new();
Self::play_ball(field, context, &game_tick_context, &mut events);
Self::play_players(field, context, &game_tick_context, &mut events);
// dispatch events
EventDispatcher::dispatch(events.to_vec(), field, context, match_data, true);
// Use total cumulative match time for positions
Self::write_match_positions(field, context.total_match_time, match_data);
}
pub fn write_match_positions(
field: &mut MatchField,
timestamp: u64,
match_data: &mut ResultMatchPositionData,
) {
// player positions
field.players.iter().for_each(|player| {
match_data.add_player_positions(player.id, timestamp, player.position);
});
// player positions
field.substitutes.iter().for_each(|sub_player| {
match_data.add_player_positions(sub_player.id, timestamp, sub_player.position);
});
// write positions
match_data.add_ball_positions(timestamp, field.ball.position);
}
fn play_ball(
field: &mut MatchField,
context: &MatchContext,
tick_context: &GameTickContext,
events: &mut EventCollection,
) {
field
.ball
.update(context, &field.players, tick_context, events);
}
fn play_players(
field: &mut MatchField,
context: &mut MatchContext,
tick_context: &GameTickContext,
events: &mut EventCollection,
) {
field
.players
.iter_mut()
.map(|player| player.update(context, tick_context, events))
.collect()
}
}
pub enum MatchEvent {
MatchPlayed(u32, bool, u8),
Goal(u32),
Assist(u32),
Injury(u32),
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum BallSide {
Left,
Right,
}
impl From<BallSide> for u8 {
fn from(side: BallSide) -> Self {
match side {
BallSide::Left => 0,
BallSide::Right => 1,
}
}
}
#[derive(Clone)]
pub struct TeamsTactics {
pub left: Tactics,
pub right: Tactics,
}
impl TeamsTactics {
pub fn from_field(field: &MatchField) -> Self {
TeamsTactics {
left: field.left_team_tactics.clone(),
right: field.right_team_tactics.clone(),
}
}
}
#[derive(Clone)]
pub struct GoalPosition {
pub left: Vector3<f32>,
pub right: Vector3<f32>,
}
impl From<&MatchFieldSize> for GoalPosition {
fn from(value: &MatchFieldSize) -> Self {
// Left goal at x = 0, centered on width
let left_goal = Vector3::new(0.0, value.height as f32 / 2.0, 0.0);
// Right goal at x = length, centered on width
let right_goal = Vector3::new(value.width as f32, (value.height / 2usize) as f32, 0.0);
GoalPosition {
left: left_goal,
right: right_goal,
}
}
}
pub const GOAL_WIDTH: f32 = 60.0;
impl GoalPosition {
pub fn is_goal(&self, ball_position: Vector3<f32>) -> Option<GoalSide> {
const EPSILON: f32 = 0.5;
if (ball_position.x - self.left.x).abs() < EPSILON {
let top_goal_bound = self.left.y - GOAL_WIDTH;
let bottom_goal_bound = self.left.y + GOAL_WIDTH;
if ball_position.y >= top_goal_bound && ball_position.y <= bottom_goal_bound {
return Some(GoalSide::Home);
}
}
if (ball_position.x - self.right.x).abs() < EPSILON {
let top_goal_bound = self.right.y - GOAL_WIDTH;
let bottom_goal_bound = self.right.y + GOAL_WIDTH;
if ball_position.y >= top_goal_bound && ball_position.y <= bottom_goal_bound {
return Some(GoalSide::Away);
}
}
None
}
}
#[derive(Clone)]
pub struct MatchFieldSize {
pub width: usize,
pub height: usize,
pub half_width: usize,
}
impl MatchFieldSize {
pub fn new(width: usize, height: usize) -> Self {
MatchFieldSize {
width,
height,
half_width: width / 2,
}
}
}
pub struct MatchPlayerCollection {
pub players: HashMap<u32, MatchPlayer>,
}
impl MatchPlayerCollection {
pub fn from_squads(home_squad: &MatchSquad, away_squad: &MatchSquad) -> Self {
let mut result = HashMap::new();
// home_main
for hs_m in &home_squad.main_squad {
result.insert(hs_m.id, hs_m.clone());
}
// home_subs
for hs_s in &home_squad.substitutes {
result.insert(hs_s.id, hs_s.clone());
}
// home_main
for as_m in &away_squad.main_squad {
result.insert(as_m.id, as_m.clone());
}
// home_subs
for as_s in &away_squad.substitutes {
result.insert(as_s.id, as_s.clone());
}
MatchPlayerCollection { players: result }
}
pub fn by_id(&self, player_id: u32) -> Option<&MatchPlayer> {
self.players.get(&player_id)
}
pub fn raw_players(&self) -> Vec<&MatchPlayer> {
self.players.values().collect()
}
}
#[cfg(debug_assertions)]
pub const MATCH_HALF_TIME_MS: u64 = 5 * 60 * 1000;
#[cfg(not(debug_assertions))]
pub const MATCH_HALF_TIME_MS: u64 = 45 * 60 * 1000;
pub const MATCH_TIME_MS: u64 = MATCH_HALF_TIME_MS * 2;
pub struct MatchTime {
pub time: u64,
}
impl MatchTime {
pub fn new() -> Self {
MatchTime { time: 0 }
}
#[inline]
pub fn increment(&mut self, val: u64) -> u64 {
self.time += val;
self.time
}
pub fn is_running_out(&self) -> bool {
self.time > (2 * MATCH_TIME_MS / 3)
}
}
#[derive(Default)]
pub struct PlayMatchStateResult {
pub additional_time: u64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initialization() {
let match_time = MatchTime::new();
assert_eq!(match_time.time, 0);
}
#[test]
fn test_increment() {
let mut match_time = MatchTime::new();
let incremented_time = match_time.increment(10);
assert_eq!(match_time.time, 10);
assert_eq!(incremented_time, 10);
let incremented_time_again = match_time.increment(5);
assert_eq!(match_time.time, 15);
assert_eq!(incremented_time_again, 15);
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/result.rs | src/core/src/match/engine/result.rs | use crate::league::LeagueMatch;
use crate::r#match::player::statistics::MatchStatisticType;
use crate::r#match::{MatchSquad, ResultMatchPositionData};
use std::sync::atomic::{AtomicU8, Ordering};
#[derive(Debug)]
pub struct MatchResultRaw {
pub score: Option<Score>,
pub position_data: ResultMatchPositionData,
pub left_team_players: FieldSquad,
pub right_team_players: FieldSquad,
pub match_time_ms: u64,
pub additional_time_ms: u64,
}
impl Clone for MatchResultRaw {
fn clone(&self) -> Self {
MatchResultRaw {
score: self.score.clone(),
position_data: self.position_data.clone(),
left_team_players: self.left_team_players.clone(),
right_team_players: self.right_team_players.clone(),
match_time_ms: self.match_time_ms,
additional_time_ms: self.additional_time_ms,
}
}
}
impl MatchResultRaw {
pub fn with_match_time(match_time_ms: u64) -> Self {
MatchResultRaw {
score: None,
position_data: ResultMatchPositionData::new(),
left_team_players: FieldSquad::new(),
right_team_players: FieldSquad::new(),
match_time_ms,
additional_time_ms: 0,
}
}
pub fn copy_without_data_positions(&self) -> Self {
MatchResultRaw {
score: self.score.clone(),
position_data: ResultMatchPositionData::new(),
left_team_players: self.left_team_players.clone(),
right_team_players: self.right_team_players.clone(),
match_time_ms: self.match_time_ms,
additional_time_ms: self.additional_time_ms,
}
}
pub fn write_team_players(
&mut self,
home_team_players: &FieldSquad,
away_team_players: &FieldSquad,
) {
self.left_team_players = FieldSquad::from(home_team_players);
self.right_team_players = FieldSquad::from(away_team_players);
}
}
#[derive(Debug, Clone)]
pub struct FieldSquad {
pub team_id: u32,
pub main: Vec<u32>,
pub substitutes: Vec<u32>,
}
impl FieldSquad {
pub fn new() -> Self {
FieldSquad {
team_id: 0,
main: Vec::new(),
substitutes: Vec::new(),
}
}
pub fn from(field_squad: &FieldSquad) -> Self {
FieldSquad {
team_id: field_squad.team_id,
main: field_squad.main.to_vec(),
substitutes: field_squad.substitutes.to_vec(),
}
}
pub fn from_team(squad: &MatchSquad) -> Self {
FieldSquad {
team_id: squad.team_id,
main: squad.main_squad.iter().map(|p| p.id).collect(),
substitutes: squad.substitutes.iter().map(|p| p.id).collect(),
}
}
pub fn count(&self) -> usize {
self.main.len() + self.substitutes.len()
}
}
#[derive(Debug, Clone)]
pub struct Score {
pub home_team: TeamScore,
pub away_team: TeamScore,
pub details: Vec<GoalDetail>,
}
#[derive(Debug)]
pub struct TeamScore {
pub team_id: u32,
score: AtomicU8,
}
impl Clone for TeamScore {
fn clone(&self) -> Self {
TeamScore {
team_id: self.team_id,
score: AtomicU8::new(self.score.load(Ordering::Relaxed)),
}
}
}
impl TeamScore {
pub fn new(team_id: u32) -> Self {
TeamScore {
team_id,
score: AtomicU8::new(0),
}
}
pub fn new_with_score(team_id: u32, score: u8) -> Self {
TeamScore {
team_id,
score: AtomicU8::new(score),
}
}
pub fn get(&self) -> u8 {
self.score.load(Ordering::Relaxed)
}
}
impl From<&TeamScore> for TeamScore {
fn from(team_score: &TeamScore) -> Self {
TeamScore::new_with_score(team_score.team_id, team_score.score.load(Ordering::Relaxed))
}
}
impl PartialEq<Self> for TeamScore {
fn eq(&self, other: &Self) -> bool {
self.score.load(Ordering::Relaxed) == other.score.load(Ordering::Relaxed)
}
}
impl PartialOrd for TeamScore {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
let left_score = self.score.load(Ordering::Relaxed);
let other_score = other.score.load(Ordering::Relaxed);
Some(left_score.cmp(&other_score))
}
}
#[derive(Debug, Clone)]
pub struct GoalDetail {
pub player_id: u32,
pub stat_type: MatchStatisticType,
pub is_auto_goal: bool,
pub time: u64,
}
impl Score {
pub fn new(home_team_id: u32, away_team_id: u32) -> Self {
Score {
home_team: TeamScore::new(home_team_id),
away_team: TeamScore::new(away_team_id),
details: Vec::new(),
}
}
pub fn add_goal_detail(&mut self, goal_detail: GoalDetail) {
self.details.push(goal_detail)
}
pub fn detail(&self) -> &[GoalDetail] {
&self.details
}
pub fn increment_home_goals(&self) {
self.home_team.score.fetch_add(1, Ordering::Relaxed);
}
pub fn increment_away_goals(&self) {
self.away_team.score.fetch_add(1, Ordering::Relaxed);
}
}
#[derive(Debug, Clone)]
pub struct MatchResult {
pub id: String,
pub league_id: u32,
pub league_slug: String,
pub home_team_id: u32,
pub away_team_id: u32,
pub details: Option<MatchResultRaw>,
pub score: Score,
}
impl MatchResult {
pub fn copy_without_data_positions(&self) -> Self {
MatchResult {
id: String::from(&self.id),
league_id: self.league_id,
league_slug: String::from(&self.league_slug),
home_team_id: self.home_team_id,
away_team_id: self.away_team_id,
details: if self.details.is_some() {
Some(self.details.as_ref().unwrap().copy_without_data_positions())
} else {
None
},
score: self.score.clone(),
}
}
}
impl From<&LeagueMatch> for MatchResult {
fn from(m: &LeagueMatch) -> Self {
MatchResult {
id: m.id.clone(),
league_id: m.league_id,
league_slug: m.league_slug.clone(),
home_team_id: m.home_team_id,
away_team_id: m.away_team_id,
score: Score::new(m.home_team_id, m.away_team_id),
details: None,
}
}
}
impl PartialEq for MatchResult {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/mod.rs | src/core/src/match/engine/mod.rs | pub mod ball;
pub mod engine;
pub mod events;
pub mod field;
pub mod player;
pub mod raycast;
pub mod result;
pub mod state;
pub mod tactics;
pub mod context;
pub use ball::*;
pub use engine::*;
pub use field::*;
pub use raycast::*;
pub use result::*;
pub use state::*;
pub use context::*;
// Re-export player items except conflicting ones
pub use player::{
behaviours, closure, decision, objects, passing, team,
common_states, defender_states,
defenders, forwarders, goalkeepers, midfielders,
BallOperationsImpl,
MatchPlayer, PlayerSide, MatchPlayerLite,
};
// Re-export specific types from player submodules that code expects at this level
pub use player::context::GameTickContext;
pub use player::behaviours::SteeringBehavior;
pub use player::positions::{
MatchObjectsPositions, PlayerDistanceClosure, PlayerDistanceFromStartPosition,
closure as position_closure, objects as position_objects,
ball as position_ball, players as position_players,
};
pub use player::strategies::players::{
PlayerOpponentsOperationsImpl, PlayerTeammatesOperationsImpl,
};
pub use player::strategies::passing::PassEvaluator;
pub use player::strategies::processor::{
StateProcessingContext, StateProcessingResult, StateProcessor,
StateChangeResult, StateProcessingHandler, ConditionContext,
};
// Export modules for those who want to access them
pub use player::context as player_context;
pub use player::positions as player_positions;
pub use player::strategies::processor;
// Note: player::events conflicts with engine::events module, so we don't re-export it
// Re-export tactics items except conflicting ones
pub use tactics::field::{PositionType, POSITION_POSITIONING};
pub use tactics::field as tactics_field;
pub use tactics::positions as tactics_positions;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/context.rs | src/core/src/match/engine/context.rs | use nalgebra::Vector3;
use crate::r#match::{GameState, GoalDetail, GoalPosition, MatchField, MatchFieldSize, MatchPlayerCollection, MatchState, MatchTime, Score, TeamsTactics, MATCH_HALF_TIME_MS};
const MATCH_TIME_INCREMENT_MS: u64 = 10;
pub struct MatchContext {
pub state: GameState,
pub time: MatchTime,
pub score: Score,
pub field_size: MatchFieldSize,
pub players: MatchPlayerCollection,
pub goal_positions: GoalPosition,
pub tactics: TeamsTactics,
// Team IDs for determining which goal to shoot at
pub field_home_team_id: u32,
pub field_away_team_id: u32,
pub(crate) logging_enabled: bool,
// Track cumulative time across all match states
pub total_match_time: u64,
}
impl MatchContext {
pub fn new(field: &MatchField, players: MatchPlayerCollection, score: Score) -> Self {
MatchContext {
state: GameState::new(),
time: MatchTime::new(),
score,
field_size: MatchFieldSize::clone(&field.size),
players,
goal_positions: GoalPosition::from(&field.size),
tactics: TeamsTactics::from_field(field),
field_home_team_id: field.home_team_id,
field_away_team_id: field.away_team_id,
logging_enabled: false,
total_match_time: 0,
}
}
pub fn increment_time(&mut self) -> bool {
let new_time = self.time.increment(MATCH_TIME_INCREMENT_MS);
self.total_match_time += MATCH_TIME_INCREMENT_MS;
match self.state.match_state {
MatchState::FirstHalf | MatchState::SecondHalf => {
new_time < MATCH_HALF_TIME_MS
},
_ => false
}
}
pub fn reset_period_time(&mut self) {
self.time = MatchTime::new();
}
pub fn add_time(&mut self, time: u64) {
self.time.increment(time);
self.total_match_time += time;
}
pub fn fill_details(&mut self) {
for player in self
.players
.raw_players()
.iter()
.filter(|p| !p.statistics.is_empty())
{
for stat in &player.statistics.items {
let detail = GoalDetail {
player_id: player.id,
time: stat.match_second,
stat_type: stat.stat_type,
is_auto_goal: stat.is_auto_goal,
};
self.score.add_goal_detail(detail);
}
}
}
pub fn enable_logging(&mut self) {
self.logging_enabled = true;
}
pub fn penalty_area(&self, is_home_team: bool) -> PenaltyArea {
let field_width = self.field_size.width as f32;
let field_height = self.field_size.height as f32;
let penalty_area_width = 16.5; // Standard width of penalty area
let penalty_area_depth = 40.3; // Standard depth of penalty area
if is_home_team {
PenaltyArea::new(
Vector3::new(0.0, (field_height - penalty_area_width) / 2.0, 0.0),
Vector3::new(
penalty_area_depth,
(field_height + penalty_area_width) / 2.0,
0.0,
),
)
} else {
PenaltyArea::new(
Vector3::new(
field_width - penalty_area_depth,
(field_height - penalty_area_width) / 2.0,
0.0,
),
Vector3::new(field_width, (field_height + penalty_area_width) / 2.0, 0.0),
)
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct PenaltyArea {
pub min: Vector3<f32>,
pub max: Vector3<f32>,
}
impl PenaltyArea {
pub fn new(min: Vector3<f32>, max: Vector3<f32>) -> Self {
PenaltyArea { min, max }
}
pub fn contains(&self, point: &Vector3<f32>) -> bool {
point.x >= self.min.x
&& point.x <= self.max.x
&& point.y >= self.min.y
&& point.y <= self.max.y
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/raycast/mod.rs | src/core/src/match/engine/raycast/mod.rs | pub mod space;
pub use space::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/raycast/space.rs | src/core/src/match/engine/raycast/space.rs | use crate::r#match::{MatchField, MatchPlayer};
use nalgebra::Vector3;
pub struct Space {
colliders: Vec<SphereCollider>,
}
impl From<&MatchField> for Space {
fn from(field: &MatchField) -> Self {
let mut space = Space::new();
// Add ball collider
let ball_radius = 0.11; // Assuming the ball radius is 0.11 meters (size 5 football)
let ball_collider = SphereCollider {
center: field.ball.position,
radius: ball_radius,
player: None,
};
space.add_collider(ball_collider);
// Add player colliders
for player in &field.players {
let player_radius = 0.5; // Assuming the player radius is 0.5 meters
let player_collider = SphereCollider {
center: player.position,
radius: player_radius,
player: Some(player.clone()),
};
space.add_collider(player_collider);
}
space
}
}
impl Space {
pub fn new() -> Self {
Space {
colliders: Vec::with_capacity(30),
}
}
pub fn add_collider(&mut self, collider: SphereCollider) {
self.colliders.push(collider);
}
pub fn cast_ray(
&self,
origin: Vector3<f32>,
direction: Vector3<f32>,
max_distance: f32,
include_players: bool,
) -> Option<RaycastHit<SphereCollider>> {
let mut closest_hit: Option<RaycastHit<SphereCollider>> = None;
let mut closest_distance = max_distance;
// Iterate through all colliders in the space
for collider in &self.colliders {
// Check if the collider belongs to a player
if collider.match_player().is_some() && !include_players {
continue;
}
// Perform ray intersection test with the collider
if let Some(intersection) = collider.intersect_ray(origin, direction) {
let distance = (intersection - origin).magnitude();
if distance < closest_distance {
closest_distance = distance;
closest_hit = Some(RaycastHit {
collider: collider.clone(),
_point: intersection,
_normal: collider.normal(intersection),
_distance: distance,
});
}
}
}
closest_hit
}
}
pub struct RaycastHit<T: Collider> {
pub collider: T,
_point: Vector3<f32>,
_normal: Vector3<f32>,
_distance: f32,
}
pub trait Collider: Clone {
fn intersect_ray(&self, origin: Vector3<f32>, direction: Vector3<f32>) -> Option<Vector3<f32>>;
fn normal(&self, point: Vector3<f32>) -> Vector3<f32>;
fn match_player(&self) -> Option<&MatchPlayer>;
}
// Example collider implementations
#[derive(Clone)]
pub struct SphereCollider {
pub center: Vector3<f32>,
pub radius: f32,
pub player: Option<MatchPlayer>,
}
impl Collider for SphereCollider {
fn intersect_ray(&self, origin: Vector3<f32>, direction: Vector3<f32>) -> Option<Vector3<f32>> {
let oc = origin - self.center;
let a = direction.dot(&direction);
let b = 2.0 * oc.dot(&direction);
let c = oc.dot(&oc) - self.radius * self.radius;
let discriminant = b * b - 4.0 * a * c;
if discriminant < 0.0 {
// No intersection
None
} else {
let t1 = (-b - discriminant.sqrt()) / (2.0 * a);
let t2 = (-b + discriminant.sqrt()) / (2.0 * a);
if t1 >= 0.0 && t2 >= 0.0 {
// Two intersections, return the closer one
let t = t1.min(t2);
Some(origin + t * direction)
} else if t1 >= 0.0 {
// One intersection (t1)
Some(origin + t1 * direction)
} else if t2 >= 0.0 {
// One intersection (t2)
Some(origin + t2 * direction)
} else {
// No intersection (both t1 and t2 are negative)
None
}
}
}
fn normal(&self, point: Vector3<f32>) -> Vector3<f32> {
(point - self.center).normalize()
}
fn match_player(&self) -> Option<&MatchPlayer> {
self.player.as_ref()
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/state/manager.rs | src/core/src/match/engine/state/manager.rs | use crate::r#match::{MatchContext, MatchField, MatchState, PlayMatchStateResult};
pub struct StateManager {
current_state: MatchState,
}
impl Default for StateManager {
fn default() -> Self {
Self::new()
}
}
impl StateManager {
pub fn new() -> Self {
StateManager {
current_state: MatchState::Initial,
}
}
pub fn current(&self) -> MatchState {
self.current_state
}
pub fn next(&mut self) -> Option<MatchState> {
let next_state: MatchState = Self::get_next_state(self.current_state);
match next_state {
MatchState::End => None,
_ => {
self.current_state = next_state;
Some(self.current_state)
}
}
}
fn get_next_state(current_state: MatchState) -> MatchState {
match current_state {
MatchState::Initial => MatchState::FirstHalf,
MatchState::FirstHalf => MatchState::HalfTime,
MatchState::HalfTime => MatchState::SecondHalf,
MatchState::SecondHalf => MatchState::End, // Regular matches end after second half
MatchState::ExtraTime => MatchState::PenaltyShootout,
MatchState::PenaltyShootout => MatchState::End,
MatchState::End => MatchState::End,
}
}
pub fn handle_state_finish(
context: &mut MatchContext,
field: &mut MatchField,
play_result: PlayMatchStateResult,
) {
if context.state.match_state.need_swap_squads() {
field.swap_squads();
}
if play_result.additional_time > 0 {
context.add_time(play_result.additional_time);
}
match context.state.match_state {
MatchState::Initial => {}
MatchState::FirstHalf => {
Self::play_rest_time(field);
field.reset_players_positions();
field.ball.reset();
}
MatchState::HalfTime => {
// Half-time finished - reset time for second half
context.reset_period_time();
field.reset_players_positions();
field.ball.reset();
}
MatchState::SecondHalf => {
// Second half finished - ready for extra time if needed
}
MatchState::ExtraTime => {}
MatchState::PenaltyShootout => {}
_ => {}
}
}
fn play_rest_time(field: &mut MatchField) {
field.players.iter_mut().for_each(|p| {
p.player_attributes.rest(1000);
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::r#match::MatchState;
#[test]
fn test_state_manager_new() {
let state_manager = StateManager::new();
assert_eq!(state_manager.current(), MatchState::Initial);
}
#[test]
fn test_state_manager_next() {
let mut state_manager = StateManager::new();
assert_eq!(state_manager.next(), Some(MatchState::FirstHalf));
assert_eq!(state_manager.next(), Some(MatchState::HalfTime));
assert_eq!(state_manager.next(), Some(MatchState::SecondHalf));
assert_eq!(state_manager.next(), None); // Regular match ends after second half
assert_eq!(state_manager.next(), None); // No more states after match ends
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/state/state.rs | src/core/src/match/engine/state/state.rs | #[derive(Debug, Clone, Copy, PartialEq)]
pub enum MatchState {
Initial,
FirstHalf,
HalfTime,
SecondHalf,
ExtraTime,
PenaltyShootout,
End,
}
impl MatchState {
pub fn need_swap_squads(&self) -> bool {
match *self {
MatchState::SecondHalf | MatchState::ExtraTime => true,
_ => false,
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/state/mod.rs | src/core/src/match/engine/state/mod.rs | pub mod manager;
pub mod state;
pub use manager::*;
pub use state::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/tactics/field.rs | src/core/src/match/engine/tactics/field.rs | use crate::PlayerPositionType;
pub const POSITION_POSITIONING: &[(PlayerPositionType, PositionType, PositionType)] = &[
(
PlayerPositionType::Goalkeeper,
PositionType::Home(20, 275),
PositionType::Away(820, 275),
),
(
PlayerPositionType::Sweeper,
PositionType::Home(80, 275),
PositionType::Away(755, 275),
),
(
PlayerPositionType::DefenderLeft,
PositionType::Home(165, 85),
PositionType::Away(695, 450),
),
(
PlayerPositionType::DefenderCenterLeft,
PositionType::Home(165, 210),
PositionType::Away(695, 330),
),
(
PlayerPositionType::DefenderCenter,
PositionType::Home(165, 275),
PositionType::Away(695, 275),
),
(
PlayerPositionType::DefenderCenterRight,
PositionType::Home(165, 330),
PositionType::Away(695, 210),
),
(
PlayerPositionType::DefenderRight,
PositionType::Home(165, 450),
PositionType::Away(695, 85),
),
(
PlayerPositionType::DefensiveMidfielder,
PositionType::Home(230, 275),
PositionType::Away(630, 275),
),
(
PlayerPositionType::WingbackLeft,
PositionType::Home(235, 50),
PositionType::Away(625, 50),
),
(
PlayerPositionType::WingbackRight,
PositionType::Home(235, 480),
PositionType::Away(625, 480),
),
(
PlayerPositionType::MidfielderLeft,
PositionType::Home(297, 85),
PositionType::Away(560, 450),
),
(
PlayerPositionType::MidfielderCenterLeft,
PositionType::Home(297, 210),
PositionType::Away(560, 330),
),
(
PlayerPositionType::MidfielderCenter,
PositionType::Home(297, 275),
PositionType::Away(560, 275),
),
(
PlayerPositionType::MidfielderCenterRight,
PositionType::Home(297, 330),
PositionType::Away(560, 210),
),
(
PlayerPositionType::MidfielderRight,
PositionType::Home(297, 450),
PositionType::Away(560, 85),
),
(
PlayerPositionType::AttackingMidfielderLeft,
PositionType::Home(360, 150),
PositionType::Away(485, 385),
),
(
PlayerPositionType::AttackingMidfielderCenter,
PositionType::Home(360, 275),
PositionType::Away(485, 275),
),
(
PlayerPositionType::AttackingMidfielderRight,
PositionType::Home(360, 385),
PositionType::Away(485, 150),
),
(
PlayerPositionType::ForwardLeft,
PositionType::Home(395, 210),
PositionType::Away(480, 330),
),
(
PlayerPositionType::ForwardCenter,
PositionType::Home(395, 275),
PositionType::Away(480, 275),
),
(
PlayerPositionType::ForwardRight,
PositionType::Home(395, 330),
PositionType::Away(480, 210),
),
(
PlayerPositionType::Striker,
PositionType::Home(405, 275),
PositionType::Away(435, 275),
),
];
pub enum PositionType {
Home(i16, i16),
Away(i16, i16),
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/tactics/paths.rs | src/core/src/match/engine/tactics/paths.rs | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false | |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/tactics/mod.rs | src/core/src/match/engine/tactics/mod.rs | pub mod field;
pub mod positions;
pub mod paths;
pub use field::*;
pub use positions::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/tactics/positions.rs | src/core/src/match/engine/tactics/positions.rs | use crate::r#match::{PositionType, POSITION_POSITIONING};
use crate::r#match::player::PlayerSide;
use crate::PlayerPositionType;
#[derive(Debug, Clone)]
pub struct MatchTacticalPosition {
pub position: PlayerPositionType,
pub waypoints: Vec<(f32, f32)>,
}
#[derive(Debug, Clone)]
pub struct TacticalPositions {
pub current_position: PlayerPositionType,
pub tactical_positions: Vec<MatchTacticalPosition>,
}
impl TacticalPositions {
pub fn new(current_position: PlayerPositionType, side: Option<PlayerSide>) -> Self {
let tactical_positions = vec![
MatchTacticalPosition {
position: current_position,
waypoints: Self::generate_waypoints_for_position(current_position, side),
}
];
TacticalPositions {
current_position,
tactical_positions,
}
}
pub fn regenerate_waypoints(&mut self, side: Option<PlayerSide>) {
for tactical_position in &mut self.tactical_positions {
tactical_position.waypoints = Self::generate_waypoints_for_position(
tactical_position.position,
side,
);
}
}
fn generate_waypoints_for_position(position: PlayerPositionType, side: Option<PlayerSide>) -> Vec<(f32, f32)> {
// Get base position coordinates for this position and side
let (base_x, base_y) = Self::get_base_position_coordinates(position, side);
// Determine direction multiplier based on side
// Left side (Home): attacking right (positive x direction)
// Right side (Away): attacking left (negative x direction)
let direction = match side {
Some(PlayerSide::Left) => 1.0,
Some(PlayerSide::Right) => -1.0,
None => 1.0, // Default to left/home
};
// Goal positions
let (goal_x, goal_y) = match side {
Some(PlayerSide::Left) => (840.0, 275.0), // Attacking right goal
Some(PlayerSide::Right) => (0.0, 275.0), // Attacking left goal
None => (840.0, 275.0), // Default
};
match position {
// Goalkeeper - stay near own goal with minimal movement pattern
PlayerPositionType::Goalkeeper => {
vec![
(base_x + 20.0 * direction, base_y),
]
}
// Defenders - extended path from defensive position through midfield
PlayerPositionType::DefenderLeft => {
vec![
(base_x + 80.0 * direction, base_y), // First push
(base_x + 160.0 * direction, base_y), // Midfield approach
(base_x + 240.0 * direction, base_y), // Deep into midfield
(base_x + 320.0 * direction, base_y), // Attacking third
]
}
PlayerPositionType::DefenderCenterLeft |
PlayerPositionType::DefenderCenter |
PlayerPositionType::DefenderCenterRight => {
vec![
(base_x + 80.0 * direction, base_y),
(base_x + 160.0 * direction, base_y),
(base_x + 240.0 * direction, base_y),
(base_x + 320.0 * direction, base_y),
]
}
PlayerPositionType::DefenderRight => {
vec![
(base_x + 80.0 * direction, base_y),
(base_x + 160.0 * direction, base_y),
(base_x + 240.0 * direction, base_y),
(base_x + 320.0 * direction, base_y),
]
}
PlayerPositionType::Sweeper => {
vec![
(base_x + 60.0 * direction, base_y),
(base_x + 120.0 * direction, base_y),
(base_x + 180.0 * direction, base_y),
]
}
// Defensive midfielder - extended path through midfield to attack
PlayerPositionType::DefensiveMidfielder => {
vec![
(base_x + 100.0 * direction, base_y),
(base_x + 200.0 * direction, base_y),
(base_x + 300.0 * direction, base_y),
(base_x + 400.0 * direction, base_y),
]
}
// Wingbacks - diagonal path toward opponent's corner with more waypoints
PlayerPositionType::WingbackLeft => {
let target_y = if direction > 0.0 { 50.0 } else { 500.0 };
let mid_y = (base_y + target_y) / 2.0;
vec![
(base_x + 120.0 * direction, base_y),
(base_x + 240.0 * direction, mid_y),
(base_x + 360.0 * direction, target_y),
(base_x + 480.0 * direction, target_y),
]
}
PlayerPositionType::WingbackRight => {
let target_y = if direction > 0.0 { 500.0 } else { 50.0 };
let mid_y = (base_y + target_y) / 2.0;
vec![
(base_x + 120.0 * direction, base_y),
(base_x + 240.0 * direction, mid_y),
(base_x + 360.0 * direction, target_y),
(base_x + 480.0 * direction, target_y),
]
}
// Midfielders - extended path through attacking third
PlayerPositionType::MidfielderLeft => {
vec![
(base_x + 120.0 * direction, base_y),
(base_x + 240.0 * direction, base_y),
(base_x + 360.0 * direction, base_y),
(base_x + 480.0 * direction, base_y),
]
}
PlayerPositionType::MidfielderCenterLeft |
PlayerPositionType::MidfielderCenter |
PlayerPositionType::MidfielderCenterRight => {
vec![
(base_x + 120.0 * direction, base_y),
(base_x + 240.0 * direction, base_y),
(base_x + 360.0 * direction, base_y),
(base_x + 480.0 * direction, base_y),
]
}
PlayerPositionType::MidfielderRight => {
vec![
(base_x + 120.0 * direction, base_y),
(base_x + 240.0 * direction, base_y),
(base_x + 360.0 * direction, base_y),
(base_x + 480.0 * direction, base_y),
]
}
// Attacking midfielders - progressive path toward goal
PlayerPositionType::AttackingMidfielderLeft |
PlayerPositionType::AttackingMidfielderCenter |
PlayerPositionType::AttackingMidfielderRight => {
let distance_to_goal = (goal_x - base_x).abs();
let step = distance_to_goal / 4.0;
vec![
(base_x + step * direction, base_y),
(base_x + step * 2.0 * direction, base_y),
(base_x + step * 3.0 * direction, base_y),
(goal_x, goal_y),
]
}
// Forwards - extended path to opponent's goal with intermediate waypoints
PlayerPositionType::ForwardLeft |
PlayerPositionType::ForwardCenter |
PlayerPositionType::ForwardRight => {
let distance_to_goal = (goal_x - base_x).abs();
let step = distance_to_goal / 3.0;
vec![
(base_x + step * direction, base_y),
(base_x + step * 2.0 * direction, base_y),
(goal_x, goal_y),
]
}
// Striker - direct path to opponent's goal with intermediate waypoints
PlayerPositionType::Striker => {
let distance_to_goal = (goal_x - base_x).abs();
let step = distance_to_goal / 3.0;
vec![
(base_x + step * direction, base_y),
(base_x + step * 2.0 * direction, base_y),
(goal_x, goal_y),
]
}
}
}
fn get_base_position_coordinates(position: PlayerPositionType, side: Option<PlayerSide>) -> (f32, f32) {
// Find the base coordinates from POSITION_POSITIONING constant based on side
for (pos, home, away) in POSITION_POSITIONING {
if *pos == position {
match side {
Some(PlayerSide::Left) => {
if let PositionType::Home(x, y) = home {
return (*x as f32, *y as f32);
}
}
Some(PlayerSide::Right) => {
if let PositionType::Away(x, y) = away {
return (*x as f32, *y as f32);
}
}
None => {
// Default to home position if side is not specified
if let PositionType::Home(x, y) = home {
return (*x as f32, *y as f32);
}
}
}
}
}
// Default position if not found (center of the field)
(420.0, 272.5)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/ball/mod.rs | src/core/src/match/engine/ball/mod.rs | pub mod ball;
pub mod events;
pub use ball::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/ball/events.rs | src/core/src/match/engine/ball/events.rs | use crate::r#match::events::Event;
use crate::r#match::player::events::PlayerEvent;
use crate::r#match::{MatchContext, MatchField};
use log::debug;
#[derive(Copy, Clone, Debug)]
pub enum BallEvent {
Goal(BallGoalEventMetadata),
Claimed(u32),
Gained(u32),
TakeMe(u32),
}
#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
pub enum GoalSide {
Home,
Away,
}
#[derive(Copy, Clone, Debug)]
pub struct BallGoalEventMetadata {
pub side: GoalSide,
pub goalscorer_player_id: u32,
pub auto_goal: bool,
}
pub struct BallEventDispatcher;
impl BallEventDispatcher {
pub fn dispatch(
event: BallEvent,
field: &mut MatchField,
context: &MatchContext,
) -> Vec<Event> {
let mut remaining_events = Vec::new();
if context.logging_enabled {
match event {
BallEvent::TakeMe(_) => {},
_ => debug!("Ball event: {:?}", event)
}
}
match event {
BallEvent::Goal(metadata) => {
match metadata.side {
GoalSide::Home => context.score.increment_away_goals(),
GoalSide::Away => context.score.increment_home_goals(),
}
remaining_events.push(Event::PlayerEvent(PlayerEvent::Goal(
metadata.goalscorer_player_id,
metadata.auto_goal,
)));
field.reset_players_positions();
}
BallEvent::Claimed(player_id) => {
remaining_events.push(Event::PlayerEvent(PlayerEvent::ClaimBall(player_id)));
}
BallEvent::Gained(player_id) => {
remaining_events.push(Event::PlayerEvent(PlayerEvent::GainBall(player_id)));
}
BallEvent::TakeMe(player_id) => {
remaining_events.push(Event::PlayerEvent(PlayerEvent::TakeBall(player_id)));
}
}
remaining_events
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/ball/ball.rs | src/core/src/match/engine/ball/ball.rs | use std::collections::HashMap;
use crate::r#match::ball::events::{BallEvent, BallGoalEventMetadata, GoalSide};
use crate::r#match::events::EventCollection;
use crate::r#match::{GameTickContext, MatchContext, MatchPlayer, PlayerSide};
use nalgebra::Vector3;
pub struct Ball {
pub start_position: Vector3<f32>,
pub position: Vector3<f32>,
pub velocity: Vector3<f32>,
pub center_field_position: f32,
pub field_width: f32,
pub field_height: f32,
pub flags: BallFlags,
pub previous_owner: Option<u32>,
pub current_owner: Option<u32>,
pub take_ball_notified_players: Vec<u32>,
pub notification_cooldown: u32,
pub notification_timeout: u32, // Ticks since players were notified
pub last_boundary_position: Option<Vector3<f32>>,
pub unowned_stopped_ticks: u32, // How long ball has been stopped without owner
pub ownership_duration: u32, // How many ticks current owner has had the ball
}
#[derive(Default)]
pub struct BallFlags {
pub in_flight_state: usize,
pub running_for_ball: bool,
}
impl BallFlags {
pub fn reset(&mut self) {
self.in_flight_state = 0;
self.running_for_ball = false;
}
}
impl Ball {
pub fn with_coord(field_width: f32, field_height: f32) -> Self {
let x = field_width / 2.0;
let y = field_height / 2.0;
Ball {
position: Vector3::new(x, y, 0.0),
start_position: Vector3::new(x, y, 0.0),
field_width,
field_height,
velocity: Vector3::zeros(),
center_field_position: x, // initial ball position = center field
flags: BallFlags::default(),
previous_owner: None,
current_owner: None,
take_ball_notified_players: Vec::new(),
notification_cooldown: 0,
notification_timeout: 0,
last_boundary_position: None,
unowned_stopped_ticks: 0,
ownership_duration: 0,
}
}
pub fn update(
&mut self,
context: &MatchContext,
players: &[MatchPlayer],
tick_context: &GameTickContext,
events: &mut EventCollection,
) {
self.update_velocity();
self.check_goal(context, events);
self.check_boundary_collision(context);
self.try_intercept(players, events);
self.try_notify_standing_ball(players, events);
// NUCLEAR OPTION: Force claiming if ball unowned and stopped for too long
self.force_claim_if_deadlock(players, events);
self.process_ownership(context, players, events);
self.move_to(tick_context);
}
pub fn process_ownership(
&mut self,
context: &MatchContext,
players: &[MatchPlayer],
events: &mut EventCollection,
) {
// prevent pass tackling
if self.flags.in_flight_state > 0 {
self.flags.in_flight_state -= 1;
} else {
self.check_ball_ownership(context, players, events);
}
self.flags.running_for_ball = self.is_players_running_to_ball(players);
}
pub fn try_notify_standing_ball(
&mut self,
players: &[MatchPlayer],
events: &mut EventCollection,
) {
// Decrement cooldown timer
if self.notification_cooldown > 0 {
self.notification_cooldown -= 1;
}
// Check if ball is stopped (either outside or inside field) and no one owns it
let is_ball_stopped = self.is_stands_outside() || self.is_ball_stopped_on_field();
// Check if ball has moved significantly from last boundary position
let has_escaped_boundary = if let Some(last_pos) = self.last_boundary_position {
let distance_from_boundary = (self.position - last_pos).magnitude();
distance_from_boundary > 2.0 // Reduced from 5.0 to allow re-notification for slow rolling balls
} else {
true // No previous boundary position recorded
};
if (is_ball_stopped)
&& self.take_ball_notified_players.is_empty()
&& self.current_owner.is_none()
&& self.notification_cooldown == 0 // Only notify if cooldown expired
&& has_escaped_boundary // Only notify if ball escaped from previous boundary loop
{
let notified_players = self.notify_nearest_player(players, events);
if !notified_players.is_empty() {
self.take_ball_notified_players = notified_players;
self.notification_timeout = 0; // Reset timeout when new players are notified
// If ball is at boundary, set short cooldown and record position
if self.is_ball_outside() {
self.notification_cooldown = 5; // Short cooldown to prevent spam
self.last_boundary_position = Some(self.position);
}
}
} else if !self.take_ball_notified_players.is_empty() {
// Increment timeout counter
self.notification_timeout += 1;
// If players haven't claimed the ball within reasonable time, reset and try again
const MAX_NOTIFICATION_TIMEOUT: u32 = 60; // ~1 second - reduced from 200 for faster response
if self.notification_timeout > MAX_NOTIFICATION_TIMEOUT {
self.take_ball_notified_players.clear();
self.notification_timeout = 0;
self.notification_cooldown = 0; // Clear cooldown to allow immediate re-notification
// Clear boundary position to allow re-notification even if ball hasn't moved
self.last_boundary_position = None;
return; // Will re-notify on next tick
}
// Check if any notified player reached the ball - must be very close to claim
const CLAIM_DISTANCE: f32 = 1.8; // Increased from 1.5 for easier claiming
const MAX_CLAIM_VELOCITY: f32 = 6.0; // Increased from 5.0 - ball must be reasonably slow to claim
// For aerial balls, check distance to landing position
let target_position = if self.is_aerial() {
self.calculate_landing_position()
} else {
self.position
};
// Check ball velocity - allow claiming slower balls
let ball_speed = self.velocity.norm();
let can_claim_by_speed = ball_speed < MAX_CLAIM_VELOCITY;
// Find the first player who reached the ball
let mut claiming_player_id: Option<u32> = None;
let mut all_players_missing = true;
for notified_player_id in &self.take_ball_notified_players {
if let Some(player) = players.iter().find(|p| p.id == *notified_player_id) {
all_players_missing = false;
// Calculate proper 3D distance
let dx = player.position.x - target_position.x;
let dy = player.position.y - target_position.y;
let dz = target_position.z;
let distance_3d = (dx * dx + dy * dy + dz * dz).sqrt();
if distance_3d < CLAIM_DISTANCE && self.current_owner.is_none() && can_claim_by_speed {
// Check if ball is moving away from player
if ball_speed > 1.0 {
// Vector from ball to player (horizontal only for 2D check)
let to_player_x = dx;
let to_player_y = dy;
// Ball direction (normalized)
let ball_dir_x = self.velocity.x / ball_speed;
let ball_dir_y = self.velocity.y / ball_speed;
// Dot product: positive means ball moving towards player
let dot_product = ball_dir_x * to_player_x + ball_dir_y * to_player_y;
// If ball is moving away (negative dot), player can't claim it
if dot_product < 0.0 {
continue; // Skip this player
}
}
// Player reached the ball (or landing position), give them ownership when ball arrives
// For aerial balls, only claim when ball is low enough
if !self.is_aerial() || self.position.z < 2.5 {
claiming_player_id = Some(*notified_player_id);
break; // Ball claimed, no need to check other players
}
}
}
}
// If all notified players are missing from the players slice, clear the list
// This can happen if players were substituted or if there's a data inconsistency
if all_players_missing {
self.take_ball_notified_players.clear();
}
// Process the claim after iteration to avoid borrow checker issues
if let Some(player_id) = claiming_player_id {
self.current_owner = Some(player_id);
self.take_ball_notified_players.clear();
self.notification_timeout = 0;
events.add_ball_event(BallEvent::Claimed(player_id));
// Reset boundary tracking when ball is claimed
if has_escaped_boundary {
self.last_boundary_position = None;
}
}
}
}
pub fn try_intercept(&mut self, _players: &[MatchPlayer], _events: &mut EventCollection) {}
/// Calculate where an aerial ball will land (when z reaches 0)
/// Returns the predicted landing position using simple projection
pub fn calculate_landing_position(&self) -> Vector3<f32> {
// If ball is already on ground or owned, return current position
if self.position.z <= 0.1 || self.current_owner.is_some() {
return self.position;
}
// If ball is moving up or not moving vertically, estimate it will land near current position
if self.velocity.z >= 0.0 {
return Vector3::new(self.position.x, self.position.y, 0.0);
}
// Simple projection: calculate time until ball reaches ground (z = 0)
// time = current_height / vertical_speed
let time_to_ground = self.position.z / self.velocity.z.abs();
// Project horizontal position
let landing_x = self.position.x + self.velocity.x * time_to_ground;
let landing_y = self.position.y + self.velocity.y * time_to_ground;
// Clamp to field boundaries
let clamped_x = landing_x.clamp(0.0, self.field_width);
let clamped_y = landing_y.clamp(0.0, self.field_height);
Vector3::new(clamped_x, clamped_y, 0.0)
}
/// Check if the ball is aerial (in the air above player reach)
pub fn is_aerial(&self) -> bool {
const PLAYER_REACH_HEIGHT: f32 = 2.3;
self.position.z > PLAYER_REACH_HEIGHT && self.velocity.z.abs() > 0.1
}
pub fn is_stands_outside(&self) -> bool {
self.is_ball_outside()
&& self.velocity.norm() < 0.5 // Changed from exact 0.0 to allow tiny velocities from physics
&& self.current_owner.is_none()
}
pub fn is_ball_stopped_on_field(&self) -> bool {
!self.is_ball_outside()
&& self.velocity.norm() < 2.5 // Increased to catch slow rolling balls that need claiming
&& self.current_owner.is_none()
}
pub fn is_ball_outside(&self) -> bool {
self.position.x <= 0.0
|| self.position.x >= self.field_width
|| self.position.y <= 0.0
|| self.position.y >= self.field_height
}
/// NUCLEAR OPTION: Force the nearest player to claim the ball if it's been sitting unowned for too long
/// This is a last-resort failsafe to prevent deadlocks where no one claims the ball
fn force_claim_if_deadlock(
&mut self,
players: &[MatchPlayer],
events: &mut EventCollection,
) {
// Use hysteresis to avoid oscillation: stricter threshold to enter, looser to exit
const DEADLOCK_VELOCITY_ENTER: f32 = 4.0; // Enter deadlock detection when velocity drops below this (increased to catch more cases)
const DEADLOCK_VELOCITY_EXIT: f32 = 6.0; // Exit deadlock detection when velocity exceeds this
const DEADLOCK_HEIGHT_THRESHOLD: f32 = 1.5; // Catch low aerial balls too
const DEADLOCK_TICK_THRESHOLD: u32 = 25; // Force claim after 25 ticks (~0.4 seconds) - faster response
const DEADLOCK_SEARCH_RADIUS: f32 = 15.0; // Increased initial search radius
const DEADLOCK_EXTENDED_RADIUS: f32 = 30.0; // Extended radius if no one found nearby
const DEADLOCK_TICK_EXTENDED: u32 = 45; // Use extended radius after 45 ticks (~0.75 seconds)
// Check if ball is unowned
let is_unowned = self.current_owner.is_none();
if !is_unowned {
// Ball is owned - reset counter
self.unowned_stopped_ticks = 0;
return;
}
// CRITICAL: Don't interfere with passed/kicked balls
// If ball is in flight (pass protection), skip deadlock detection entirely
if self.flags.in_flight_state > 0 {
self.unowned_stopped_ticks = 0;
return;
}
// Determine velocity threshold based on current state (hysteresis)
let velocity_threshold = if self.unowned_stopped_ticks > 0 {
DEADLOCK_VELOCITY_EXIT // Already tracking - use looser threshold
} else {
DEADLOCK_VELOCITY_ENTER // Not tracking - use stricter threshold
};
let velocity_norm = self.velocity.norm();
let is_slow = velocity_norm < velocity_threshold;
let is_low = self.position.z < DEADLOCK_HEIGHT_THRESHOLD;
if is_slow && is_low {
self.unowned_stopped_ticks += 1;
// If ball has been slow and unowned for threshold ticks, FORCE claiming
if self.unowned_stopped_ticks >= DEADLOCK_TICK_THRESHOLD {
// Determine search radius based on how long we've been waiting
let search_radius = if self.unowned_stopped_ticks >= DEADLOCK_TICK_EXTENDED {
DEADLOCK_EXTENDED_RADIUS
} else {
DEADLOCK_SEARCH_RADIUS
};
// Find the nearest player within search radius
if let Some(nearest_player) = players.iter()
.filter(|p| {
let dx = p.position.x - self.position.x;
let dy = p.position.y - self.position.y;
let distance = (dx * dx + dy * dy).sqrt();
distance <= search_radius
})
.min_by(|a, b| {
let dist_a = (a.position - self.position).magnitude();
let dist_b = (b.position - self.position).magnitude();
dist_a.partial_cmp(&dist_b).unwrap()
}) {
// DIRECTLY CLAIM the ball - don't use TakeMe event which might fail
self.current_owner = Some(nearest_player.id);
self.previous_owner = None; // Clear previous owner to avoid conflicts
self.ownership_duration = 0;
// CRITICAL: Reset in_flight_state to prevent ownership blocking
self.flags.in_flight_state = 0;
// Clear any existing notifications to avoid conflicts
self.take_ball_notified_players.clear();
self.notification_timeout = 0;
// Force ball to ground if slightly aerial (but keep horizontal velocity)
if self.position.z > 0.1 && self.position.z < DEADLOCK_HEIGHT_THRESHOLD {
self.position.z = 0.0;
self.velocity.z = 0.0;
}
// Reset counter
self.unowned_stopped_ticks = 0;
// Emit claimed event for logging/tracking
events.add_ball_event(BallEvent::Claimed(nearest_player.id));
} else {
// No players found even with extended radius
// This shouldn't normally happen, but if it does, force ball to ground and stop it
if self.unowned_stopped_ticks > DEADLOCK_TICK_EXTENDED + 20 {
self.position.z = 0.0;
self.velocity = Vector3::zeros();
self.unowned_stopped_ticks = 0; // Reset to try again
// Clear notifications so system can restart fresh
self.take_ball_notified_players.clear();
self.notification_timeout = 0;
}
}
}
} else {
// Ball is moving fast or airborne - reset counter only if it's clearly moving
// Use hysteresis: only reset if velocity is above exit threshold
if velocity_norm >= velocity_threshold {
self.unowned_stopped_ticks = 0;
}
// Otherwise keep counting - this handles oscillating velocities
}
}
fn notify_nearest_player(
&self,
players: &[MatchPlayer],
events: &mut EventCollection,
) -> Vec<u32> {
let ball_position = self.position;
const NOTIFICATION_RADIUS: f32 = 500.0; // Cover entire field - all players can be notified
// Group players by team and find nearest from each team
let mut team_nearest: HashMap<u32, (&MatchPlayer, f32)> = HashMap::new();
for player in players {
let dx = player.position.x - ball_position.x;
let dy = player.position.y - ball_position.y;
let distance_squared = dx * dx + dy * dy;
// Only consider players within notification radius
if distance_squared < NOTIFICATION_RADIUS * NOTIFICATION_RADIUS {
// Check if this is the nearest player for their team
team_nearest
.entry(player.team_id)
.and_modify(|current| {
if distance_squared < current.1 {
*current = (player, distance_squared);
}
})
.or_insert((player, distance_squared));
}
}
// Notify one player from each team and collect their IDs
let mut notified_players = Vec::new();
for (player, _) in team_nearest.values() {
events.add_ball_event(BallEvent::TakeMe(player.id));
notified_players.push(player.id);
}
notified_players
}
fn check_boundary_collision(&mut self, context: &MatchContext) {
let field_width = context.field_size.width as f32;
let field_height = context.field_size.height as f32;
// Check if ball hits the boundary and reverse its velocity if it does
if self.position.x <= 0.0 {
self.position.x = 0.0;
self.velocity = Vector3::zeros();
}
if self.position.x >= field_width {
self.position.x = field_width;
self.velocity = Vector3::zeros();
}
if self.position.y <= 0.0 {
self.position.y = 0.0;
self.velocity = Vector3::zeros();
}
if self.position.y >= field_height {
self.position.y = field_height;
self.velocity = Vector3::zeros();
}
}
fn is_players_running_to_ball(&self, players: &[MatchPlayer]) -> bool {
let ball_position = self.position;
let player_positions: Vec<(Vector3<f32>, Vector3<f32>)> = players
.iter()
.map(|player| (player.position, player.velocity))
.collect();
for (player_position, player_velocity) in player_positions {
let direction_to_ball = (ball_position - player_position).normalize();
let player_direction = player_velocity.normalize();
let dot_product = direction_to_ball.dot(&player_direction);
if dot_product > 0.0 {
return true;
}
}
false
}
fn check_ball_ownership(
&mut self,
context: &MatchContext,
players: &[MatchPlayer],
events: &mut EventCollection,
) {
// Realistic distance threshold - players can only claim ball when it's very close to their feet
const BALL_DISTANCE_THRESHOLD: f32 = 1.2;
const BALL_DISTANCE_THRESHOLD_SQUARED: f32 = BALL_DISTANCE_THRESHOLD * BALL_DISTANCE_THRESHOLD;
const PLAYER_HEIGHT: f32 = 1.8; // Average player height in meters
const PLAYER_REACH_HEIGHT: f32 = PLAYER_HEIGHT + 0.5; // Player can reach ~2.3m when standing
const PLAYER_JUMP_REACH: f32 = PLAYER_HEIGHT + 1.0; // Player can reach ~2.8m when jumping
const MAX_BALL_HEIGHT: f32 = PLAYER_JUMP_REACH + 0.5; // Absolute max reachable height
// CRITICAL: Early validation - if current owner is too far AND ball is moving, clear ownership
// This catches cases where ball flies away from owner but ownership wasn't properly cleared
// Only applies when ball has velocity - if ball is stopped (e.g., at boundary), let normal mechanics handle it
const MAX_OWNERSHIP_DISTANCE: f32 = 3.0; // Maximum distance when ball is moving
const MAX_OWNERSHIP_DISTANCE_SQUARED: f32 = MAX_OWNERSHIP_DISTANCE * MAX_OWNERSHIP_DISTANCE;
const MIN_VELOCITY_FOR_DISTANCE_CHECK: f32 = 1.0; // Only check distance if ball is moving faster than this
if let Some(current_owner_id) = self.current_owner {
if let Some(owner) = context.players.by_id(current_owner_id) {
let dx = owner.position.x - self.position.x;
let dy = owner.position.y - self.position.y;
let distance_squared = dx * dx + dy * dy;
let ball_speed = self.velocity.norm();
// Only clear ownership if ball is moving AND far from owner
// This prevents interference with deadlock claiming and boundary situations
if distance_squared > MAX_OWNERSHIP_DISTANCE_SQUARED && ball_speed > MIN_VELOCITY_FOR_DISTANCE_CHECK {
// Check if ball is moving AWAY from owner (not towards them)
let ball_dir_x = self.velocity.x / ball_speed;
let ball_dir_y = self.velocity.y / ball_speed;
// Vector from ball to owner
let to_owner_x = dx;
let to_owner_y = dy;
let to_owner_dist = (dx * dx + dy * dy).sqrt();
if to_owner_dist > 0.1 {
let to_owner_norm_x = to_owner_x / to_owner_dist;
let to_owner_norm_y = to_owner_y / to_owner_dist;
// Dot product: negative means ball is moving away from owner
let dot = ball_dir_x * to_owner_norm_x + ball_dir_y * to_owner_norm_y;
if dot < -0.3 { // Ball is clearly moving away from owner
// Owner is too far and ball is flying away - clear ownership
self.previous_owner = self.current_owner;
self.current_owner = None;
self.ownership_duration = 0;
// Don't return - continue to allow new ownership claim
}
}
}
} else {
// Owner player not found - clear ownership
self.previous_owner = self.current_owner;
self.current_owner = None;
self.ownership_duration = 0;
}
}
// Ball is too high to be claimed by any player (flying over everyone's heads)
if self.position.z > MAX_BALL_HEIGHT {
return;
}
// Check if previous owner is still within range (use 3D distance)
// This prevents immediate ball reclaim after passing/shooting
// BUT: Allow opponents to contest the ball even if previous owner is still close
if let Some(previous_owner_id) = self.previous_owner {
if let Some(owner) = context.players.by_id(previous_owner_id) {
// Calculate proper 3D distance
let dx = owner.position.x - self.position.x;
let dy = owner.position.y - self.position.y;
let dz = self.position.z; // Ball height from ground (player is at z=0)
let distance_3d = (dx * dx + dy * dy + dz * dz).sqrt();
if distance_3d > BALL_DISTANCE_THRESHOLD {
self.previous_owner = None;
} else {
// Previous owner still in range
// Check if there are any opponents nearby who might contest the ball
let has_opponent_contesting = players
.iter()
.filter(|p| p.team_id != owner.team_id) // Opponents only
.any(|opponent| {
let dx = opponent.position.x - self.position.x;
let dy = opponent.position.y - self.position.y;
let horizontal_distance_squared = dx * dx + dy * dy;
// Check if opponent is close enough to contest
horizontal_distance_squared <= BALL_DISTANCE_THRESHOLD_SQUARED
});
// If no opponents are contesting, return early to prevent previous owner from reclaiming
// If opponents ARE contesting, continue to ownership check to allow fair challenge
if !has_opponent_contesting {
return;
}
// Otherwise, continue to normal ownership check below
}
} else {
// Previous owner not found - clear it
self.previous_owner = None;
}
}
// Velocity threshold - if ball is moving faster than this, players can't just "catch" it
const MAX_CLAIMABLE_VELOCITY: f32 = 8.0; // Ball moving faster than 8 m/s is hard to claim
const SLOW_BALL_VELOCITY: f32 = 3.0; // Ball moving slower than 3 m/s is easy to claim
let ball_speed = self.velocity.norm();
let is_ball_fast = ball_speed > MAX_CLAIMABLE_VELOCITY;
// Find all players within ball distance threshold with proper 3D collision detection
let nearby_players: Vec<&MatchPlayer> = players
.iter()
.filter(|player| {
let dx = player.position.x - self.position.x;
let dy = player.position.y - self.position.y;
let horizontal_distance_squared = dx * dx + dy * dy;
let horizontal_distance = horizontal_distance_squared.sqrt();
// Early exit if horizontally too far
if horizontal_distance_squared > BALL_DISTANCE_THRESHOLD_SQUARED {
return false;
}
// For slow balls (< 3 m/s), allow claiming regardless of direction
// This prevents balls from being unclaimed when rolling slowly
if ball_speed > SLOW_BALL_VELOCITY {
// Vector from ball to player
let to_player_x = dx;
let to_player_y = dy;
// Normalize ball velocity (direction ball is moving)
let ball_vel_norm = ball_speed;
if ball_vel_norm > 0.01 {
let ball_dir_x = self.velocity.x / ball_vel_norm;
let ball_dir_y = self.velocity.y / ball_vel_norm;
// Dot product: positive means ball is moving towards player, negative means away
let dot_product = ball_dir_x * to_player_x + ball_dir_y * to_player_y;
// If ball is moving away from player (negative dot product), they can't claim it
// unless they're close enough (within 0.8m) - relaxed from 0.5m
if dot_product < 0.0 && horizontal_distance > 0.8 {
return false;
}
// If ball is very fast and not moving directly at the player, make it harder to claim
if is_ball_fast {
// Require player to be close (0.8m) and ball to be moving towards them
if horizontal_distance > 0.8 || dot_product < 0.3 * ball_vel_norm * horizontal_distance {
return false;
}
}
}
}
// For slow balls, skip direction check entirely - always allow claiming if close enough
// Calculate reachable height based on horizontal distance
// Closer = easier to reach higher balls (can jump)
// Further = harder to reach higher balls
let effective_reach_height = if horizontal_distance < 0.8 {
// Very close - can jump and reach high
PLAYER_JUMP_REACH
} else if horizontal_distance < 1.2 {
// Medium distance - can reach with feet/body
PLAYER_REACH_HEIGHT
} else {
// Far distance - only low balls (sliding tackle range)
PLAYER_HEIGHT * 0.6
};
// Check if ball is at reachable height for this horizontal distance
self.position.z <= effective_reach_height
})
.collect();
// Early exit if no nearby players
if nearby_players.is_empty() {
return;
}
// Check if current owner is nearby
if let Some(current_owner_id) = self.current_owner {
// Check if current owner is still nearby
let current_owner_nearby = nearby_players
.iter()
.any(|player| player.id == current_owner_id);
if current_owner_nearby {
// Current owner is still close to the ball - maintain ownership
self.ownership_duration += 1;
return;
}
// Current owner is NOT nearby - clear ownership so ball can be claimed
// This prevents the ball from being "owned" by a player who is far away
self.previous_owner = self.current_owner;
self.current_owner = None;
// If only teammates are nearby, they can now claim the ball
// If opponents are nearby, they compete for it
// This prevents the rapid position changes caused by inconsistent ownership state
}
// Ownership stability constants
const MIN_OWNERSHIP_DURATION: u32 = 8; // Minimum ticks before ownership can change (reduced from 15 to prevent stuck duels)
const TAKEOVER_ADVANTAGE_THRESHOLD: f32 = 1.08; // Challenger must be 8% better (reduced from 1.15 to resolve duels faster)
// Determine the best tackler from nearby players
let best_tackler = if nearby_players.len() == 1 {
nearby_players.first().copied()
} else {
nearby_players
.iter()
.max_by(|player_a, player_b| {
let player_a_full = context.players.by_id(player_a.id).unwrap();
let player_b_full = context.players.by_id(player_b.id).unwrap();
let tackling_score_a = Self::calculate_tackling_score(player_a_full);
let tackling_score_b = Self::calculate_tackling_score(player_b_full);
tackling_score_a
.partial_cmp(&tackling_score_b)
.unwrap_or(std::cmp::Ordering::Equal)
})
.copied()
};
// Transfer ownership to the best tackler (with stability checks)
if let Some(player) = best_tackler {
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/events/dispatcher.rs | src/core/src/match/engine/events/dispatcher.rs | use crate::r#match::ball::events::{BallEvent, BallEventDispatcher};
use crate::r#match::player::events::{PlayerEvent, PlayerEventDispatcher};
use crate::r#match::{MatchContext, MatchField, ResultMatchPositionData};
pub enum Event {
BallEvent(BallEvent),
PlayerEvent(PlayerEvent),
}
pub struct EventCollection {
events: Vec<Event>,
}
impl EventCollection {
pub fn new() -> Self {
EventCollection {
events: Vec::with_capacity(10),
}
}
pub fn with_event(event: Event) -> Self {
EventCollection {
events: vec![event],
}
}
pub fn add(&mut self, event: Event) {
self.events.push(event)
}
pub fn add_ball_event(&mut self, event: BallEvent) {
self.events.push(Event::BallEvent(event))
}
pub fn add_player_event(&mut self, event: PlayerEvent) {
self.events.push(Event::PlayerEvent(event))
}
pub fn add_range(&mut self, events: Vec<Event>) {
for event in events {
self.events.push(event);
}
}
pub fn add_from_collection(&mut self, events: EventCollection) {
for event in events.events {
self.events.push(event);
}
}
pub fn to_vec(self) -> Vec<Event> {
self.events
}
}
pub struct EventDispatcher;
impl EventDispatcher {
pub fn dispatch(
events: Vec<Event>,
field: &mut MatchField,
context: &mut MatchContext,
match_data: &mut ResultMatchPositionData,
process_remaining_events: bool,
) {
let mut remaining_events = Vec::with_capacity(10);
for event in events {
match event {
Event::BallEvent(ball_event) => {
let mut ball_remaining_events =
BallEventDispatcher::dispatch(ball_event, field, context);
if process_remaining_events {
remaining_events.append(&mut ball_remaining_events);
}
}
Event::PlayerEvent(player_event) => {
let mut player_remaining_events =
PlayerEventDispatcher::dispatch(player_event, field, context, match_data);
if process_remaining_events {
remaining_events.append(&mut player_remaining_events);
}
}
}
}
if process_remaining_events {
Self::dispatch(remaining_events, field, context, match_data, false)
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/events/mod.rs | src/core/src/match/engine/events/mod.rs | pub mod dispatcher;
pub use dispatcher::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/player.rs | src/core/src/match/engine/player/player.rs | use crate::r#match::defenders::states::DefenderState;
use crate::r#match::engine::tactics::TacticalPositions;
use crate::r#match::events::EventCollection;
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::goalkeepers::states::state::GoalkeeperState;
use crate::r#match::midfielders::states::MidfielderState;
use crate::r#match::player::state::{PlayerMatchState, PlayerState};
use crate::r#match::player::statistics::MatchPlayerStatistics;
use crate::r#match::player::waypoints::WaypointManager;
use crate::r#match::{GameTickContext, MatchContext, StateProcessingContext};
use crate::{
PersonAttributes, Player, PlayerAttributes, PlayerFieldPositionGroup, PlayerPositionType,
PlayerSkills,
};
use nalgebra::Vector3;
use std::fmt::*;
#[cfg(debug_assertions)]
use log::warn;
#[derive(Debug, Clone)]
pub struct MatchPlayer {
pub id: u32,
pub position: Vector3<f32>,
pub start_position: Vector3<f32>,
pub attributes: PersonAttributes,
pub team_id: u32,
pub player_attributes: PlayerAttributes,
pub skills: PlayerSkills,
pub tactical_position: TacticalPositions,
pub velocity: Vector3<f32>,
pub side: Option<PlayerSide>,
pub state: PlayerState,
pub in_state_time: u64,
pub statistics: MatchPlayerStatistics,
pub use_extended_state_logging: bool,
pub waypoint_manager: WaypointManager,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PlayerSide {
Left,
Right,
}
impl MatchPlayer {
pub fn from_player(
team_id: u32,
player: &Player,
position: PlayerPositionType,
use_extended_state_logging: bool,
) -> Self {
MatchPlayer {
id: player.id,
position: Vector3::zeros(),
start_position: Vector3::zeros(),
attributes: player.attributes,
team_id,
player_attributes: player.player_attributes,
skills: player.skills,
velocity: Vector3::zeros(),
tactical_position: TacticalPositions::new(position, None),
side: None,
state: Self::default_state(position),
in_state_time: 0,
statistics: MatchPlayerStatistics::new(),
waypoint_manager: WaypointManager::new(),
use_extended_state_logging,
}
}
pub fn update(
&mut self,
context: &MatchContext,
tick_context: &GameTickContext,
events: &mut EventCollection,
) {
let player_events = PlayerMatchState::process(self, context, tick_context);
events.add_from_collection(player_events);
self.update_waypoint_index(tick_context);
self.check_boundary_collision(context);
self.move_to();
}
fn check_boundary_collision(&mut self, context: &MatchContext) {
let field_width = context.field_size.width as f32 + 1.0;
let field_height = context.field_size.height as f32 + 1.0;
// Clamp position to field boundaries
self.position.x = self.position.x.clamp(0.0, field_width);
self.position.y = self.position.y.clamp(0.0, field_height);
// Only stop velocity if player is trying to move OUT of bounds
// Allow velocity that moves them back into the field
if self.position.x <= 0.0 && self.velocity.x < 0.0 {
// At left boundary, trying to move further left
self.velocity.x = 0.0;
} else if self.position.x >= field_width && self.velocity.x > 0.0 {
// At right boundary, trying to move further right
self.velocity.x = 0.0;
}
if self.position.y <= 0.0 && self.velocity.y < 0.0 {
// At bottom boundary, trying to move further down
self.velocity.y = 0.0;
} else if self.position.y >= field_height && self.velocity.y > 0.0 {
// At top boundary, trying to move further up
self.velocity.y = 0.0;
}
}
pub fn set_default_state(&mut self) {
self.state = Self::default_state(self.tactical_position.current_position);
}
fn default_state(position: PlayerPositionType) -> PlayerState {
match position.position_group() {
PlayerFieldPositionGroup::Goalkeeper => {
PlayerState::Goalkeeper(GoalkeeperState::Standing)
}
PlayerFieldPositionGroup::Defender => PlayerState::Defender(DefenderState::Standing),
PlayerFieldPositionGroup::Midfielder => {
PlayerState::Midfielder(MidfielderState::Standing)
}
PlayerFieldPositionGroup::Forward => PlayerState::Forward(ForwardState::Standing),
}
}
pub fn run_for_ball(&mut self) {
self.state = match self.tactical_position.current_position.position_group() {
PlayerFieldPositionGroup::Goalkeeper => {
PlayerState::Goalkeeper(GoalkeeperState::TakeBall)
}
PlayerFieldPositionGroup::Defender => PlayerState::Defender(DefenderState::TakeBall),
PlayerFieldPositionGroup::Midfielder => {
PlayerState::Midfielder(MidfielderState::TakeBall)
}
PlayerFieldPositionGroup::Forward => PlayerState::Forward(ForwardState::TakeBall),
}
}
fn move_to(&mut self) {
#[cfg(debug_assertions)]
let old_position = self.position;
if !self.velocity.x.is_nan() {
self.position.x += self.velocity.x;
}
if !self.velocity.y.is_nan() {
self.position.y += self.velocity.y;
}
#[cfg(debug_assertions)]
{
// Check for abnormally large position changes
let position_delta = self.position - old_position;
let position_change = position_delta.norm();
// Thresholds for detecting issues
const MAX_REASONABLE_POSITION_CHANGE: f32 = 20.0; // Max reasonable position change per tick
if position_change > MAX_REASONABLE_POSITION_CHANGE {
warn!(
"Player {:?} position jumped abnormally! {} from: ({:.2}, {:.2}) to: ({:.2}, {:.2}), delta: ({:.2}, {:.2}), distance: {:.2}, velocity: ({:.2}, {:.2})",
self.state,
self.id,
old_position.x,
old_position.y,
self.position.x,
self.position.y,
position_delta.x,
position_delta.y,
position_change,
self.velocity.x,
self.velocity.y
);
}
}
}
pub fn heading(&self) -> f32 {
self.velocity.y.atan2(self.velocity.x)
}
pub fn has_ball(&self, ctx: &StateProcessingContext<'_>) -> bool {
ctx.ball().owner_id() == Some(self.id)
}
pub fn update_waypoint_index(&mut self, tick_context: &GameTickContext) {
self.waypoint_manager.update(
&tick_context.positions.players.position(self.id),
&self.get_waypoints_as_vectors(),
);
}
pub fn get_waypoints_as_vectors(&self) -> Vec<Vector3<f32>> {
self.tactical_position
.tactical_positions
.iter()
.filter(|tp| tp.position == self.tactical_position.current_position)
.flat_map(|tp| &tp.waypoints)
.map(|(x, y)| Vector3::new(*x, *y, 0.0))
.collect()
}
pub fn should_follow_waypoints(&self, ctx: &StateProcessingContext) -> bool {
let has_ball = self.has_ball(ctx);
let is_ball_close = ctx.ball().distance() < 100.0;
let team_in_control = ctx.team().is_control_ball();
!has_ball && !is_ball_close && team_in_control
}
}
#[derive(Copy, Clone)]
pub struct MatchPlayerLite {
pub id: u32,
pub position: Vector3<f32>,
pub tactical_positions: PlayerPositionType,
}
impl MatchPlayerLite {
pub fn has_ball(&self, ctx: &StateProcessingContext<'_>) -> bool {
ctx.ball().owner_id() == Some(self.id)
}
pub fn velocity(&self, ctx: &StateProcessingContext<'_>) -> Vector3<f32> {
ctx.tick_context.positions.players.velocity(ctx.player.id)
}
pub fn distance(&self, ctx: &StateProcessingContext<'_>) -> f32 {
ctx.tick_context.distances.get(self.id, ctx.player.id)
}
}
impl From<&MatchPlayer> for MatchPlayerLite {
fn from(player: &MatchPlayer) -> Self {
MatchPlayerLite {
id: player.id,
position: player.position,
tactical_positions: player.tactical_position.current_position,
}
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/state.rs | src/core/src/match/engine/player/state.rs | use crate::r#match::defenders::states::DefenderState;
use crate::r#match::events::EventCollection;
use crate::r#match::forwarders::states::ForwardState;
use crate::r#match::goalkeepers::states::state::GoalkeeperState;
use crate::r#match::midfielders::states::MidfielderState;
use crate::r#match::{GameTickContext, MatchContext, MatchPlayer};
use crate::PlayerFieldPositionGroup;
use log::error;
use std::fmt::Display;
use std::fmt::Formatter;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PlayerState {
Injured,
Goalkeeper(GoalkeeperState),
Defender(DefenderState),
Midfielder(MidfielderState),
Forward(ForwardState),
}
impl Display for PlayerState {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
PlayerState::Injured => write!(f, "Injured"),
PlayerState::Goalkeeper(state) => write!(f, "Goalkeeper: {}", state),
PlayerState::Defender(state) => write!(f, "Defender: {}", state),
PlayerState::Midfielder(state) => write!(f, "Midfielder: {}", state),
PlayerState::Forward(state) => write!(f, "Forward: {}", state),
}
}
}
pub struct PlayerMatchState;
impl PlayerMatchState {
pub fn process(
player: &mut MatchPlayer,
context: &MatchContext,
tick_context: &GameTickContext,
) -> EventCollection {
let player_position_group = player.tactical_position.current_position.position_group();
let state_change_result =
player_position_group.process(player.in_state_time, player, context, tick_context);
if let Some(state) = state_change_result.state {
#[cfg(debug_assertions)]
{
if !Self::validate_state(state, &player_position_group) {
error!(
"invalid state change {:?} -> {:?} for {:?}",
player.state, state, player_position_group
);
}
}
Self::change_state(player, state);
} else {
player.in_state_time += 1;
}
if let Some(velocity) = state_change_result.velocity {
// Safety clamp: ensure velocity never exceeds player's max speed (factoring in condition)
let max_speed = player.skills.max_speed_with_condition(
player.player_attributes.condition,
);
let velocity_magnitude = velocity.norm();
if velocity_magnitude > max_speed && velocity_magnitude > 0.0 {
// Velocity is too high, clamp it to max_speed
player.velocity = velocity * (max_speed / velocity_magnitude);
} else {
player.velocity = velocity;
}
}
state_change_result.events
}
fn change_state(player: &mut MatchPlayer, state: PlayerState) {
player.in_state_time = 0;
player.state = state;
}
fn validate_state(
player_state: PlayerState,
position_group: &PlayerFieldPositionGroup,
) -> bool {
match (player_state, position_group) {
(PlayerState::Injured, _) => true, // Injured state is valid for all position groups
(PlayerState::Goalkeeper(_), PlayerFieldPositionGroup::Goalkeeper) => true,
(PlayerState::Defender(_), PlayerFieldPositionGroup::Defender) => true,
(PlayerState::Midfielder(_), PlayerFieldPositionGroup::Midfielder) => true,
(PlayerState::Forward(_), PlayerFieldPositionGroup::Forward) => true,
_ => false, // Any other combination is invalid
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/mod.rs | src/core/src/match/engine/player/mod.rs | use crate::r#match::{MatchObjectsPositions, StateProcessingContext};
pub mod behaviours;
pub mod context;
pub mod player;
pub mod state;
pub mod statistics;
pub mod strategies;
pub mod positions;
pub mod events;
mod waypoints;
pub use behaviours::*;
pub use context::*;
use itertools::Itertools;
pub use player::*;
// Re-export positions items except conflicting ones
pub use positions::{closure, objects};
pub use positions::ball as position_ball;
pub use positions::players as position_players;
// Re-export strategies items except conflicting ones
pub use strategies::{
BallOperationsImpl, decision, passing, team,
common_states, defender_states, processor,
defenders, forwarders, goalkeepers, midfielders,
};
// Note: strategies re-exports players and ball from common, which conflicts with positions
// We'll use the position_ prefixed versions as the primary ones
pub struct GameFieldContextInput<'p> {
object_positions: &'p MatchObjectsPositions,
}
impl<'p> GameFieldContextInput<'p> {
pub fn from_contexts(ctx: &StateProcessingContext<'p>) -> Self {
GameFieldContextInput {
object_positions: &ctx.tick_context.positions,
}
}
pub fn to_input(&self) -> Vec<f64> {
let players_positions: Vec<f64> = self
.object_positions
.players
.items
.iter()
.sorted_by_key(|m| m.player_id)
.flat_map(|p| p.position.as_slice().to_vec())
.map(|m| m as f64)
.collect();
players_positions
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/context.rs | src/core/src/match/engine/player/context.rs | use crate::r#match::{
MatchField, MatchObjectsPositions, PlayerDistanceClosure, Space
};
pub struct GameTickContext {
pub positions: MatchObjectsPositions,
pub distances: PlayerDistanceClosure,
pub ball: BallMetadata,
pub space: Space,
}
impl GameTickContext {
pub fn new(field: &MatchField) -> Self {
GameTickContext {
ball: BallMetadata::from(field),
positions: MatchObjectsPositions::from(field),
distances: PlayerDistanceClosure::from(field),
space: Space::from(field),
}
}
}
pub struct BallMetadata {
pub is_owned: bool,
pub is_in_flight_state: usize,
pub current_owner: Option<u32>,
pub last_owner: Option<u32>,
pub notified_players: Vec<u32>,
pub ownership_duration: u32,
}
impl From<&MatchField> for BallMetadata {
fn from(field: &MatchField) -> Self {
BallMetadata {
is_owned: field.ball.current_owner.is_some(),
is_in_flight_state: field.ball.flags.in_flight_state,
current_owner: field.ball.current_owner,
last_owner: field.ball.previous_owner,
notified_players: field.ball.take_ball_notified_players.clone(),
ownership_duration: field.ball.ownership_duration,
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/statistics.rs | src/core/src/match/engine/player/statistics.rs | #[derive(Debug, Clone)]
pub struct MatchPlayerStatistics {
pub items: Vec<MatchPlayerStatisticsItem>,
}
impl MatchPlayerStatistics {
pub fn new() -> Self {
MatchPlayerStatistics {
items: Vec::with_capacity(5),
}
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn add_goal(&mut self, match_second: u64, is_auto_goal: bool) {
self.items.push(MatchPlayerStatisticsItem {
stat_type: MatchStatisticType::Goal,
match_second,
is_auto_goal,
})
}
pub fn add_assist(&mut self, match_second: u64) {
self.items.push(MatchPlayerStatisticsItem {
stat_type: MatchStatisticType::Assist,
match_second,
is_auto_goal: false,
})
}
}
impl Default for MatchPlayerStatistics {
fn default() -> Self {
MatchPlayerStatistics::new()
}
}
#[derive(Debug, Copy, Clone)]
pub struct MatchPlayerStatisticsItem {
pub stat_type: MatchStatisticType,
pub match_second: u64,
pub is_auto_goal: bool,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum MatchStatisticType {
Goal,
Assist,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_statistics_initialization() {
let stats = MatchPlayerStatistics::new();
assert!(stats.is_empty());
assert!(stats.items.is_empty());
}
#[test]
fn test_add_goal() {
let mut stats = MatchPlayerStatistics::new();
stats.add_goal(30, false);
assert_eq!(stats.items.len(), 1);
assert_eq!(stats.items[0].stat_type, MatchStatisticType::Goal);
assert_eq!(stats.items[0].match_second, 30);
assert!(!stats.is_empty());
}
#[test]
fn test_add_assist() {
let mut stats = MatchPlayerStatistics::new();
stats.add_assist(45);
assert_eq!(stats.items.len(), 1);
assert_eq!(stats.items[0].stat_type, MatchStatisticType::Assist);
assert_eq!(stats.items[0].match_second, 45);
assert!(!stats.is_empty());
}
#[test]
fn test_is_empty() {
let stats = MatchPlayerStatistics::new();
assert!(stats.is_empty());
let mut stats_with_goal = MatchPlayerStatistics::new();
stats_with_goal.add_goal(10, false);
assert!(!stats_with_goal.is_empty());
let mut stats_with_assist = MatchPlayerStatistics::new();
stats_with_assist.add_assist(20);
assert!(!stats_with_assist.is_empty());
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/positions/objects.rs | src/core/src/match/engine/player/positions/objects.rs | use crate::r#match::player_positions::{BallFieldData, PlayerFieldData};
use crate::r#match::{MatchField};
pub struct MatchObjectsPositions {
pub ball: BallFieldData,
pub players: PlayerFieldData,
}
impl MatchObjectsPositions {
pub fn from(field: &MatchField) -> Self {
MatchObjectsPositions {
ball: BallFieldData::from(&field.ball),
players: PlayerFieldData::from(field)
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/positions/closure.rs | src/core/src/match/engine/player/positions/closure.rs | use crate::r#match::{MatchField, VectorExtensions};
use log::debug;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
const MAX_DISTANCE: f32 = 999.0;
#[derive(Debug)]
pub struct PlayerDistanceClosure {
pub distances: BinaryHeap<PlayerDistanceItem>,
}
#[derive(Debug)]
pub struct PlayerDistanceItem {
pub player_from_id: u32,
pub player_from_team: u32,
pub player_to_id: u32,
pub player_to_team: u32,
pub distance: f32,
}
impl From<&MatchField> for PlayerDistanceClosure {
fn from(field: &MatchField) -> Self {
let n = field.players.len();
let capacity = (n * (n - 1)) / 2;
let mut distances = BinaryHeap::with_capacity(capacity);
for outer_player in &field.players {
for inner_player in &field.players {
if outer_player.id == inner_player.id {
continue;
}
let distance = outer_player.position.distance_to(&inner_player.position);
distances.push(PlayerDistanceItem {
player_from_id: outer_player.id,
player_from_team: outer_player.team_id,
player_to_id: inner_player.id,
player_to_team: inner_player.team_id,
distance,
});
}
}
PlayerDistanceClosure { distances }
}
}
impl PlayerDistanceClosure {
pub fn get(&self, player_from_id: u32, player_to_id: u32) -> f32 {
if player_from_id == player_to_id {
debug!(
"player {} and {} are the same",
player_from_id, player_to_id
);
return 0.0;
}
self.distances
.iter()
.find(|distance| {
(distance.player_from_id == player_from_id && distance.player_to_id == player_to_id)
|| (distance.player_from_id == player_to_id && distance.player_to_id == player_from_id)
})
.map(|dist| dist.distance)
.unwrap_or_else(|| {
MAX_DISTANCE // Required for subs
})
}
pub fn get_collisions(&self, max_distance: f32) -> Vec<&PlayerDistanceItem> {
self.distances
.iter()
.filter(|&p| p.distance < max_distance)
.collect()
}
pub fn teammates<'t>(
&'t self,
player_id: u32,
min_distance: f32,
max_distance: f32,
) -> impl Iterator<Item = (u32, f32)> + 't {
self.distances
.iter()
.filter(move |p| p.distance >= min_distance && p.distance <= max_distance)
.filter_map(move |item| {
if item.player_from_id == item.player_to_id
{
return None;
}
if item.player_from_id == player_id && item.player_from_team == item.player_to_team
{
return Some((item.player_to_id, item.distance));
}
if item.player_to_id == player_id && item.player_from_team == item.player_to_team {
return Some((item.player_from_id, item.distance));
}
None
})
}
pub fn opponents<'t>(
&'t self,
player_id: u32,
distance: f32,
) -> impl Iterator<Item = (u32, f32)> + 't {
self.distances
.iter()
.filter(move |p| p.distance <= distance)
.filter_map(move |item| {
if item.player_from_id == item.player_to_id
{
return None;
}
if item.player_from_id == player_id && item.player_from_team != item.player_to_team
{
return Some((item.player_to_id, item.distance));
}
if item.player_to_id == player_id && item.player_from_team != item.player_to_team {
return Some((item.player_from_id, item.distance));
}
None
})
}
}
impl Eq for PlayerDistanceItem {}
impl PartialEq<PlayerDistanceItem> for PlayerDistanceItem {
fn eq(&self, other: &Self) -> bool {
self.player_from_id == other.player_from_id
&& self.player_from_team == other.player_from_team
&& self.player_to_id == other.player_to_id
&& self.player_to_team == other.player_to_team
&& self.distance == other.distance
}
}
impl PartialOrd<Self> for PlayerDistanceItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PlayerDistanceItem {
fn cmp(&self, other: &Self) -> Ordering {
self.distance
.partial_cmp(&other.distance)
.unwrap_or(Ordering::Equal)
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/positions/mod.rs | src/core/src/match/engine/player/positions/mod.rs | pub mod closure;
pub mod players;
pub mod ball;
pub mod objects;
pub use ball::*;
pub use closure::*;
pub use objects::*;
pub use players::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/positions/players.rs | src/core/src/match/engine/player/positions/players.rs | use crate::r#match::{MatchField, PlayerSide};
use nalgebra::Vector3;
#[derive(Debug)]
pub struct PlayerFieldData {
pub items: Vec<PlayerFieldMetadata>,
}
#[derive(Debug)]
pub struct PlayerFieldMetadata {
pub player_id: u32,
pub side: PlayerSide,
pub position: Vector3<f32>,
pub velocity: Vector3<f32>,
}
impl PlayerFieldData {
pub fn position(&self, player_id: u32) -> Vector3<f32> {
self
.items
.iter()
.find(|p| p.player_id == player_id)
.map(|p| p.position)
.unwrap_or_else(|| panic!("no position for player = {}", player_id))
}
pub fn velocity(&self, player_id: u32) -> Vector3<f32> {
self.items
.iter()
.find(|p| p.player_id == player_id)
.map(|p| p.velocity)
.unwrap_or_else(|| panic!("no velocity for player = {}", player_id))
}
}
impl From<&MatchField> for PlayerFieldData {
#[inline]
fn from(field: &MatchField) -> Self {
PlayerFieldData {
items: field
.players
.iter()
.chain(field.substitutes.iter())
.map(|p| PlayerFieldMetadata {
player_id: p.id,
side: p
.side
.unwrap_or_else(|| panic!("unknown player side, player_id = {}", p.id)),
position: p.position,
velocity: p.velocity,
})
.collect(),
}
}
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum PlayerDistanceFromStartPosition {
Small,
Medium,
Big,
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/positions/ball.rs | src/core/src/match/engine/player/positions/ball.rs | use crate::r#match::Ball;
use nalgebra::Vector3;
pub struct BallFieldData {
pub position: Vector3<f32>,
pub velocity: Vector3<f32>,
pub landing_position: Vector3<f32>,
}
impl From<&Ball> for BallFieldData {
#[inline]
fn from(ball: &Ball) -> Self {
BallFieldData {
position: ball.position,
velocity: ball.velocity,
landing_position: ball.calculate_landing_position(),
}
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/waypoints/mod.rs | src/core/src/match/engine/player/waypoints/mod.rs | use nalgebra::Vector3;
const WAYPOINT_REACHED_THRESHOLD: f32 = 25.0; // Increased threshold for larger waypoint distances
#[derive(Debug, Clone)]
pub struct WaypointManager {
pub current_index: usize,
pub path_completed: bool,
pub loop_path: bool,
}
impl WaypointManager {
pub fn new() -> Self {
WaypointManager {
current_index: 0,
path_completed: false,
loop_path: false,
}
}
pub fn reset(&mut self) {
self.current_index = 0;
self.path_completed = false;
}
pub fn update(&mut self, player_position: &Vector3<f32>, waypoints: &[Vector3<f32>]) -> Option<Vector3<f32>> {
if waypoints.is_empty() || self.path_completed {
return None;
}
// Find the nearest waypoint ahead of or at the player's current position
let nearest_ahead = self.find_nearest_waypoint_ahead(player_position, waypoints);
// Update current index to the nearest waypoint ahead
if let Some(nearest_idx) = nearest_ahead {
self.current_index = nearest_idx;
}
let current_waypoint = waypoints[self.current_index];
let distance = (player_position - current_waypoint).magnitude();
// If close enough to current waypoint, advance to next
if distance < WAYPOINT_REACHED_THRESHOLD {
self.current_index += 1;
if self.current_index >= waypoints.len() {
if self.loop_path {
self.current_index = 0;
} else {
self.path_completed = true;
return None;
}
}
}
if self.current_index < waypoints.len() {
Some(waypoints[self.current_index])
} else {
None
}
}
fn find_nearest_waypoint_ahead(&self, player_position: &Vector3<f32>, waypoints: &[Vector3<f32>]) -> Option<usize> {
if waypoints.is_empty() {
return None;
}
// Start searching from current index (don't go backward unless necessary)
let mut nearest_index = self.current_index;
let mut nearest_distance = (player_position - waypoints[self.current_index]).magnitude();
// Check if any waypoint from current onwards is closer
for i in self.current_index..waypoints.len() {
let distance = (player_position - waypoints[i]).magnitude();
if distance < nearest_distance {
nearest_distance = distance;
nearest_index = i;
}
}
// If player moved backward significantly, find the absolute nearest waypoint
if nearest_distance > WAYPOINT_REACHED_THRESHOLD * 3.0 {
for i in 0..self.current_index {
let distance = (player_position - waypoints[i]).magnitude();
if distance < nearest_distance {
nearest_distance = distance;
nearest_index = i;
}
}
}
Some(nearest_index)
}
} | rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/events/mod.rs | src/core/src/match/engine/player/events/mod.rs | pub mod players;
pub mod models;
pub use models::*;
pub use players::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/events/players.rs | src/core/src/match/engine/player/events/players.rs | use crate::r#match::events::Event;
use crate::r#match::player::events::{PassingEventContext, ShootingEventContext};
use crate::r#match::player::statistics::MatchStatisticType;
use crate::r#match::{GoalDetail, MatchContext, MatchField, MatchPlayer};
use log::debug;
use nalgebra::Vector3;
use rand::Rng;
/// Helper struct to encapsulate player passing skills and condition
struct PassSkills {
passing: f32,
technique: f32,
vision: f32,
composure: f32,
decisions: f32,
concentration: f32,
flair: f32,
long_shots: f32,
crossing: f32,
stamina: f32,
match_readiness: f32,
condition_factor: f32,
}
impl PassSkills {
fn from_player(player: &MatchPlayer) -> Self {
// Normalize skills to 0.0-1.0 range
let passing = (player.skills.technical.passing / 20.0).clamp(0.4, 1.0);
let technique = (player.skills.technical.technique / 20.0).clamp(0.4, 1.0);
let vision = (player.skills.mental.vision / 20.0).clamp(0.3, 1.0);
let composure = (player.skills.mental.composure / 20.0).clamp(0.3, 1.0);
let decisions = (player.skills.mental.decisions / 20.0).clamp(0.3, 1.0);
let concentration = (player.skills.mental.concentration / 20.0).clamp(0.3, 1.0);
let flair = (player.skills.mental.flair / 20.0).clamp(0.0, 1.0);
let long_shots = (player.skills.technical.long_shots / 20.0).clamp(0.3, 1.0);
let crossing = (player.skills.technical.crossing / 20.0).clamp(0.3, 1.0);
let stamina = (player.skills.physical.stamina / 20.0).clamp(0.3, 1.0);
let match_readiness = (player.skills.physical.match_readiness / 20.0).clamp(0.3, 1.0);
// Calculate condition factor (0.5 to 1.0 based on player condition)
let condition_percentage = player.player_attributes.condition as f32 / 10000.0;
let fitness_factor = (player.player_attributes.fitness as f32 / 10000.0).clamp(0.5, 1.0);
let jadedness_penalty = (player.player_attributes.jadedness as f32 / 10000.0) * 0.3;
let condition_factor = (condition_percentage * fitness_factor - jadedness_penalty).clamp(0.5, 1.0);
Self {
passing,
technique,
vision,
composure,
decisions,
concentration,
flair,
long_shots,
crossing,
stamina,
match_readiness,
condition_factor,
}
}
/// Calculate overall passing quality (affected by condition)
fn overall_quality(&self) -> f32 {
let base_quality = self.passing * 0.5 + self.technique * 0.3 + self.vision * 0.2;
base_quality * self.condition_factor * self.match_readiness
}
/// Calculate decision-making quality for trajectory selection
fn decision_quality(&self) -> f32 {
(self.decisions * 0.4 + self.vision * 0.3 + self.concentration * 0.2 + self.composure * 0.1)
* self.condition_factor
}
}
/// Different trajectory styles for passes
/// Each type represents a different flight time and arc height to reach the same target
#[derive(Debug, Clone, Copy)]
enum TrajectoryType {
/// Ground pass - minimal flight time, almost zero arc (fastest)
Ground,
/// Low driven pass - short flight time, low arc (fast and direct)
LowDriven,
/// Medium arc - moderate flight time, balanced trajectory
MediumArc,
/// High arc - longer flight time, high parabolic arc (for distance/obstacles)
HighArc,
/// Chip - very high arc over short distance (for beating defenders)
Chip,
}
#[derive(Debug)]
pub enum PlayerEvent {
Goal(u32, bool),
Assist(u32),
BallCollision(u32),
TacklingBall(u32),
BallOwnerChange(u32),
PassTo(PassingEventContext),
ClearBall(Vector3<f32>),
RushOut(u32),
Shoot(ShootingEventContext),
MovePlayer(u32, Vector3<f32>),
StayInGoal(u32),
MoveBall(u32, Vector3<f32>),
CommunicateMessage(u32, &'static str),
OfferSupport(u32),
ClaimBall(u32),
GainBall(u32),
CaughtBall(u32),
CommitFoul,
RequestHeading(u32, Vector3<f32>),
RequestShot(u32, Vector3<f32>),
RequestBallReceive(u32),
TakeBall(u32),
}
pub struct PlayerEventDispatcher;
impl PlayerEventDispatcher {
pub fn dispatch(
event: PlayerEvent,
field: &mut MatchField,
context: &mut MatchContext,
match_data: &mut crate::r#match::ResultMatchPositionData,
) -> Vec<Event> {
let remaining_events = Vec::new();
if context.logging_enabled {
match event {
PlayerEvent::TakeBall(_) => {},
_ => debug!("Player event: {:?}", event)
}
}
match event {
PlayerEvent::Goal(player_id, is_auto_goal) => {
Self::handle_goal_event(player_id, is_auto_goal, field, context);
}
PlayerEvent::Assist(player_id) => {
Self::handle_assist_event(player_id, field, context);
}
PlayerEvent::BallCollision(player_id) => {
Self::handle_ball_collision_event(player_id, field);
}
PlayerEvent::TacklingBall(player_id) => {
Self::handle_tackling_ball_event(player_id, field);
}
PlayerEvent::BallOwnerChange(player_id) => {
Self::handle_ball_owner_change_event(player_id, field);
}
PlayerEvent::PassTo(pass_event_model) => {
// Record the pass event (only if tracking is enabled)
if match_data.is_tracking_events() {
match_data.add_pass_event(
context.total_match_time,
pass_event_model.from_player_id,
pass_event_model.to_player_id,
);
}
Self::handle_pass_to_event(pass_event_model, field);
}
PlayerEvent::ClaimBall(player_id) => {
Self::handle_claim_ball_event(player_id, field);
}
PlayerEvent::MoveBall(player_id, ball_velocity) => {
Self::handle_move_ball_event(player_id, ball_velocity, field);
}
PlayerEvent::GainBall(player_id) => {
Self::handle_gain_ball_event(player_id, field);
}
PlayerEvent::Shoot(shoot_event_model) => {
Self::handle_shoot_event(shoot_event_model, field);
}
PlayerEvent::CaughtBall(player_id) => {
Self::handle_caught_ball_event(player_id, field);
}
PlayerEvent::MovePlayer(player_id, position) => {
Self::handle_move_player_event(player_id, position, field);
}
PlayerEvent::TakeBall(player_id) => {
Self::handle_take_ball_event(player_id, field);
}
PlayerEvent::ClearBall(velocity) => {
Self::handle_clear_ball_event(velocity, field);
}
_ => {} // Ignore unsupported events
}
remaining_events
}
fn handle_goal_event(player_id: u32, is_auto_goal: bool, field: &mut MatchField, context: &mut MatchContext) {
let player = field.get_player_mut(player_id).unwrap();
player.statistics.add_goal(context.total_match_time, is_auto_goal);
context.score.add_goal_detail(GoalDetail {
player_id,
stat_type: MatchStatisticType::Goal,
is_auto_goal,
time: context.total_match_time,
});
field.ball.previous_owner = None;
field.ball.current_owner = None;
field.reset_players_positions();
field.ball.reset();
}
fn handle_assist_event(player_id: u32, field: &mut MatchField, context: &mut MatchContext) {
let player = field.get_player_mut(player_id).unwrap();
context.score.add_goal_detail(GoalDetail {
player_id,
stat_type: MatchStatisticType::Assist,
time: context.total_match_time,
is_auto_goal: false
});
player.statistics.add_assist(context.total_match_time);
}
fn handle_ball_collision_event(player_id: u32, field: &mut MatchField) {
let player = field.get_player_mut(player_id).unwrap();
if player.skills.technical.first_touch > 10.0 {
// Handle player gaining control of the ball after collision
}
}
fn handle_tackling_ball_event(player_id: u32, field: &mut MatchField) {
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = Some(player_id);
}
fn handle_ball_owner_change_event(player_id: u32, field: &mut MatchField) {
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = Some(player_id);
}
fn handle_pass_to_event(event_model: PassingEventContext, field: &mut MatchField) {
let mut rng = rand::rng();
// Extract player skills and condition
let player = field.get_player(event_model.from_player_id).unwrap();
let passer_position = player.position;
let skills = PassSkills::from_player(player);
// Calculate overall quality for accuracy - affected by condition
let overall_quality = skills.overall_quality();
// Calculate ideal target position
let ideal_target = event_model.pass_target;
// Use passer's position as starting point if ball is very close (within 5m)
// This handles cases where ball ownership just changed
let ball_position = field.ball.position;
let ideal_pass_vector = ideal_target - ball_position;
let horizontal_distance = Self::calculate_horizontal_distance(&ideal_pass_vector);
// Apply skill-based targeting error
// Better players are more accurate with their intended target
let accuracy_factor = overall_quality * skills.concentration;
// Distance-based error: longer passes have more positional error
// Realistic values: professional players accurate to ~0.5-2m depending on distance
let distance_error_factor = (horizontal_distance / 200.0).min(1.5);
let max_position_error = 1.2 * (1.0 - accuracy_factor) * distance_error_factor;
// Add random targeting error
let target_error_x = rng.random_range(-max_position_error..max_position_error);
let target_error_y = rng.random_range(-max_position_error..max_position_error);
// Calculate actual target with error
let actual_target = Vector3::new(
ideal_target.x + target_error_x,
ideal_target.y + target_error_y,
0.0,
);
let actual_pass_vector = actual_target - ball_position;
let actual_horizontal_distance = Self::calculate_horizontal_distance(&actual_pass_vector);
// Calculate pass force with power variation
// Reduced variation to make passes more consistent
let power_consistency = 0.9 + (skills.technique * skills.stamina * 0.1);
let power_variation_range = (1.0 - overall_quality) * 0.11;
let power_variation = rng.random_range(
power_consistency - power_variation_range..power_consistency + power_variation_range
);
let adjusted_force = event_model.pass_force * power_variation;
// Calculate horizontal velocity to reach target
let horizontal_velocity = Self::calculate_horizontal_velocity(
&actual_pass_vector,
adjusted_force,
);
// Determine trajectory type based on context, not just distance
let passer = field.get_player_mut(event_model.from_player_id).unwrap();
let passer_team_id = passer.team_id;
let trajectory_type = Self::select_trajectory_type_contextual(
actual_horizontal_distance,
&skills,
&mut rng,
&passer_position,
&actual_target,
passer_team_id,
&field.players,
);
// Calculate z-velocity to reach target with chosen trajectory type
let z_velocity = Self::calculate_trajectory_to_target(
actual_horizontal_distance,
&horizontal_velocity,
trajectory_type,
&skills,
&mut rng,
);
let max_z_velocity = Self::calculate_max_z_velocity(actual_horizontal_distance, &skills);
let final_z_velocity = z_velocity.min(max_z_velocity);
// Calculate final velocity
let mut final_velocity = Vector3::new(
horizontal_velocity.x,
horizontal_velocity.y,
final_z_velocity,
);
// CRITICAL: Validate velocity to prevent cosmic-speed passes
const MAX_PASS_VELOCITY: f32 = 10.0; // Maximum realistic pass velocity per tick
// Check for NaN or infinity
if final_velocity.x.is_nan() || final_velocity.y.is_nan() || final_velocity.z.is_nan()
|| final_velocity.x.is_infinite() || final_velocity.y.is_infinite() || final_velocity.z.is_infinite()
{
// Fallback to a safe default velocity
let safe_direction = actual_pass_vector.normalize();
final_velocity = Vector3::new(
safe_direction.x * 3.0,
safe_direction.y * 3.0,
0.5
);
}
// Clamp velocity magnitude to maximum
let velocity_magnitude = final_velocity.norm();
if velocity_magnitude > MAX_PASS_VELOCITY {
final_velocity = final_velocity * (MAX_PASS_VELOCITY / velocity_magnitude);
}
// Apply ball physics
field.ball.velocity = final_velocity;
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = None;
// Increase in_flight_state based on pass distance to prevent immediate reclaim
// Short passes (< 30m): 20 ticks (~0.33s)
// Medium passes (30-60m): 30 ticks (~0.5s)
// Long passes (> 60m): 40 ticks (~0.67s)
let flight_protection = if actual_horizontal_distance < 30.0 {
20
} else if actual_horizontal_distance < 60.0 {
30
} else {
40
};
field.ball.flags.in_flight_state = flight_protection;
}
fn calculate_horizontal_distance(ball_pass_vector: &Vector3<f32>) -> f32 {
(ball_pass_vector.x * ball_pass_vector.x + ball_pass_vector.y * ball_pass_vector.y).sqrt()
}
fn calculate_horizontal_velocity(
ball_pass_vector: &Vector3<f32>,
pass_force: f32,
) -> Vector3<f32> {
const PASS_FORCE_MULTIPLIER: f32 = 5.0;
let horizontal_direction = Vector3::new(ball_pass_vector.x, ball_pass_vector.y, 0.0).normalize();
horizontal_direction * (pass_force * PASS_FORCE_MULTIPLIER)
}
/// Select trajectory type based on obstacles in the passing lane
/// Simple rule: obstacles present → cross (lofted), no obstacles → ground pass
fn select_trajectory_type_contextual(
horizontal_distance: f32,
skills: &PassSkills,
rng: &mut impl Rng,
from_position: &Vector3<f32>,
to_position: &Vector3<f32>,
passer_team_id: u32,
players: &[MatchPlayer],
) -> TrajectoryType {
// Check for obstacles in the passing lane
let obstacles_in_lane = Self::count_obstacles_in_passing_lane(
from_position,
to_position,
passer_team_id,
players,
);
// Calculate decision quality - determines how well player chooses trajectory
let decision_quality = skills.decision_quality();
let vision_quality = skills.vision;
// Better decision makers make more appropriate choices
let skill_influenced_random = {
let pure_random = rng.random_range(0.0..1.0);
let randomness_factor = 1.0 - (decision_quality * 0.6);
let skill_bias = decision_quality * 0.3;
(pure_random * randomness_factor + skill_bias).clamp(0.0, 1.0)
};
// Distance categories
let is_short = horizontal_distance <= 100.0;
let is_medium = horizontal_distance > 100.0 && horizontal_distance <= 200.0;
let is_long = horizontal_distance > 200.0 && horizontal_distance <= 300.0;
// Note: distances > 300.0 (very long) are handled in the else branches
// MAIN LOGIC: If obstacles present, use lofted passes (crosses)
// If no obstacles, use ground passes
if obstacles_in_lane == 0 {
// CLEAR LANE - Ground passes or low-driven passes
if is_short {
// Short passes - almost always ground
if skill_influenced_random < 0.95 {
TrajectoryType::Ground
} else if skills.flair * skills.technique > 0.75 {
TrajectoryType::Chip // Rare skillful chip
} else {
TrajectoryType::Ground
}
} else if is_medium {
// Medium passes - mostly ground, some driven
if skill_influenced_random < 0.75 {
TrajectoryType::Ground // 75% ground
} else {
TrajectoryType::LowDriven // 25% driven
}
} else if is_long {
// Long passes - prefer driven for speed
if skills.technique > 0.7 {
// Good technique - mostly driven
if skill_influenced_random < 0.85 {
TrajectoryType::LowDriven // 85% driven
} else {
TrajectoryType::Ground // 15% ground (safe option)
}
} else {
// Average technique - mix of ground and driven
if skill_influenced_random < 0.55 {
TrajectoryType::LowDriven // 55% driven
} else {
TrajectoryType::Ground // 45% ground
}
}
} else {
// Very long passes - mostly driven
let long_pass_ability = skills.long_shots * skills.vision * skills.crossing;
if long_pass_ability > 0.7 {
TrajectoryType::LowDriven // Elite long passer - driven
} else if skill_influenced_random < 0.6 {
TrajectoryType::LowDriven // 60% driven
} else {
TrajectoryType::MediumArc // 40% medium arc for safety
}
}
} else {
// OBSTACLES PRESENT - Use lofted passes (crosses)
let many_obstacles = obstacles_in_lane >= 2;
let has_good_crossing = skills.crossing > 0.7;
if is_short {
// Short pass with obstacles - chip or lift (NEVER low)
if vision_quality > 0.7 && skill_influenced_random < 0.65 {
TrajectoryType::Chip // Smart chip over defender (65%)
} else {
TrajectoryType::MediumArc // Medium loft (35%)
}
} else if is_medium {
// Medium pass with obstacles - cross with arc (NEVER low)
if many_obstacles {
// Multiple obstacles - higher arc needed
if skill_influenced_random < 0.70 {
TrajectoryType::HighArc // 70% high cross
} else {
TrajectoryType::MediumArc // 30% medium cross
}
} else {
// One obstacle - medium/high arc to clear it
if skill_influenced_random < 0.70 {
TrajectoryType::MediumArc // 70% medium cross
} else {
TrajectoryType::HighArc // 30% high cross
}
}
} else if is_long {
// Long pass with obstacles - definitely need arc
if many_obstacles || has_good_crossing {
// Multiple obstacles or good crosser - high arc
if skill_influenced_random < 0.75 {
TrajectoryType::HighArc // 75% high cross
} else {
TrajectoryType::MediumArc // 25% medium cross
}
} else {
// One obstacle - medium/high arc mix
if skill_influenced_random < 0.60 {
TrajectoryType::MediumArc // 60% medium cross
} else {
TrajectoryType::HighArc // 40% high cross
}
}
} else {
// Very long pass with obstacles - high cross
let long_pass_ability = skills.long_shots * skills.vision * skills.crossing;
if long_pass_ability > 0.7 {
// Elite crosser - controlled high arc
if skill_influenced_random < 0.80 {
TrajectoryType::HighArc // 80% high cross
} else {
TrajectoryType::MediumArc // 20% medium cross
}
} else {
// Average crosser - mostly high arc
if skill_influenced_random < 0.70 {
TrajectoryType::HighArc // 70% high cross
} else {
TrajectoryType::MediumArc // 30% medium cross
}
}
}
}
}
/// Count how many opponent players are in the passing lane (obstacles)
fn count_obstacles_in_passing_lane(
from_position: &Vector3<f32>,
to_position: &Vector3<f32>,
passer_team_id: u32,
players: &[MatchPlayer],
) -> usize {
const LANE_WIDTH: f32 = 12.0; // Width of the passing lane corridor (accounts for player reach and movement)
let pass_direction = (*to_position - *from_position).normalize();
let pass_distance = (*to_position - *from_position).magnitude();
players
.iter()
.filter(|player| {
// Only count opponents
if player.team_id == passer_team_id {
return false;
}
// Vector from passer to player
let to_player = player.position - *from_position;
// Project player onto pass line to find closest point
let projection_length = to_player.dot(&pass_direction);
// Player must be between passer and target
if projection_length < 0.0 || projection_length > pass_distance {
return false;
}
// Calculate perpendicular distance to pass line
let projection_point = *from_position + pass_direction * projection_length;
let perpendicular_distance = (player.position - projection_point).magnitude();
// Player is an obstacle if within lane width
perpendicular_distance < LANE_WIDTH
})
.count()
}
/// Calculate z-velocity to reach target with chosen trajectory type
/// Ground passes stay on the ground, aerial passes use physics
fn calculate_trajectory_to_target(
horizontal_distance: f32,
horizontal_velocity: &Vector3<f32>,
trajectory_type: TrajectoryType,
skills: &PassSkills,
rng: &mut impl Rng,
) -> f32 {
const GRAVITY: f32 = 9.81;
let horizontal_speed = horizontal_velocity.norm();
if horizontal_speed < 0.1 {
return 0.0; // Avoid division by zero
}
// Add very small random variation to all trajectories for realism
let tiny_random = rng.random_range(0.98..1.02);
match trajectory_type {
// Ground pass - truly on the ground (rolling)
TrajectoryType::Ground => {
// Almost no lift - just enough to handle slight bumps
// This keeps the ball rolling along the ground
let base_lift = 0.02 * skills.technique;
let random_variation = rng.random_range(0.0..0.1);
base_lift * random_variation * tiny_random // 0.0 to ~0.002 m/s (truly ground)
}
// Low driven - stays very close to ground, minimal arc (like real driven passes)
TrajectoryType::LowDriven => {
// Very slight lift - driven passes should barely leave the ground
// Maximum height should be ~0.3-0.8m for realistic driven passes
let distance_factor = (horizontal_distance / 150.0).clamp(0.2, 0.8);
let skill_factor = skills.technique * skills.condition_factor;
let base_z = 0.2 + (distance_factor * 0.5); // 0.2 to 0.7 m/s (much lower)
let variation = rng.random_range(0.9..1.1);
base_z * skill_factor * variation * tiny_random
}
// Medium arc - moderate parabolic trajectory (height ~1.5-3m, reduced)
TrajectoryType::MediumArc => {
let base_flight_time = horizontal_distance / horizontal_speed;
let flight_time = base_flight_time * 0.5; // Reduced from 0.7 - lower arc
let ideal_z = 0.65 * GRAVITY * flight_time; // Reduced from 0.8
// Skill affects consistency
let execution_quality = skills.overall_quality();
let error_range = (1.0 - execution_quality) * 0.12;
let error = rng.random_range(1.0 - error_range..1.0 + error_range);
ideal_z * error * tiny_random
}
// High arc - high parabolic trajectory (height ~4-8m)
TrajectoryType::HighArc => {
let base_flight_time = horizontal_distance / horizontal_speed;
let flight_time = base_flight_time * 1.5; // High arc
let ideal_z = 0.8 * GRAVITY * flight_time;
// Requires good long passing ability
let execution_quality = (skills.overall_quality() + skills.long_shots + skills.crossing) / 3.0;
let error_range = (1.0 - execution_quality) * 0.18;
let error = rng.random_range(1.0 - error_range..1.0 + error_range);
ideal_z * error * tiny_random
}
// Chip - very high arc over short distance (height ~3-6m)
TrajectoryType::Chip => {
// Chips are based on technique, not distance
let chip_ability = (skills.technique * 0.5 + skills.flair * 0.3 + skills.passing * 0.2)
* skills.condition_factor;
// Base height for chip regardless of distance
let base_chip_height = 2.5 + (chip_ability * 2.0); // 2.5 to 4.5 m/s
// Execution error for this difficult skill
let error_range = (1.0 - chip_ability) * 0.25;
let error = rng.random_range(1.0 - error_range..1.0 + error_range);
base_chip_height * error * tiny_random
}
}
}
fn calculate_max_z_velocity(horizontal_distance: f32, skills: &PassSkills) -> f32 {
// Combine vision and long_shots for long pass capability
let long_pass_ability = (skills.vision * 0.6 + skills.long_shots * 0.4) * skills.condition_factor;
// Very strict limits - driven passes should dominate, not high arcs
if horizontal_distance <= 20.0 {
// Short passes - almost no lift allowed (ground passes)
0.25 // Maximum 0.25 m/s vertical
} else if horizontal_distance <= 45.0 {
// Medium passes - keep very low (mostly ground/driven)
0.6 + (long_pass_ability * 0.2) // 0.6 to 0.8 m/s
} else if horizontal_distance <= 80.0 {
// Long passes - still prefer low arcs
1.2 + (long_pass_ability * 0.8) // 1.2 to 2.0 m/s (much lower)
} else if horizontal_distance <= 150.0 {
// Very long passes - moderate lift (reduced significantly)
2.5 + (long_pass_ability * 1.5) // 2.5 to 4.0 m/s (was 4.5-7.0)
} else if horizontal_distance <= 250.0 {
// Ultra-long diagonal switches - still prefer lower when possible
4.5 + (long_pass_ability * 2.5) // 4.5 to 7.0 m/s (was 7.0-10.0)
} else {
// Extreme distance - goalkeeper goal kicks, clearances
7.0 + (long_pass_ability * 3.5) // 7.0 to 10.5 m/s (was 10.0-14.0)
}
}
fn handle_claim_ball_event(player_id: u32, field: &mut MatchField) {
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = Some(player_id);
field.ball.flags.in_flight_state = 30;
}
fn handle_move_ball_event(player_id: u32, ball_velocity: Vector3<f32>, field: &mut MatchField) {
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = Some(player_id);
field.ball.velocity = ball_velocity;
}
fn handle_gain_ball_event(player_id: u32, field: &mut MatchField) {
field.ball.previous_owner = field.ball.current_owner;
field.ball.current_owner = Some(player_id);
field.ball.flags.in_flight_state = 100;
}
fn handle_shoot_event(shoot_event_model: ShootingEventContext, field: &mut MatchField) {
const GOAL_WIDTH: f32 = 60.0; // Half-width of goal (full width is 120.0)
const GOAL_HEIGHT: f32 = 8.0; // Height of crossbar
const MAX_SHOT_VELOCITY: f32 = 12.0; // Maximum realistic shot velocity per tick (~40 m/s at 60fps)
const MIN_SHOT_DISTANCE: f32 = 1.0; // Minimum distance to prevent NaN from normalization
let mut rng = rand::rng();
// Get player skills for power and accuracy calculations
let player = field.get_player(shoot_event_model.from_player_id).unwrap();
let finishing_skill = (player.skills.technical.finishing / 20.0).clamp(0.5, 1.0);
let technique_skill = (player.skills.technical.technique / 20.0).clamp(0.5, 1.0);
let long_shot_skill = (player.skills.technical.long_shots / 20.0).clamp(0.5, 1.0);
let composure_skill = (player.skills.mental.composure / 20.0).clamp(0.4, 1.0);
let decisions_skill = (player.skills.mental.decisions / 20.0).clamp(0.4, 1.0);
// Determine which goal we're shooting at
let goal_center = shoot_event_model.target;
// Calculate goal bounds
let goal_left_post = goal_center.y - GOAL_WIDTH;
let goal_right_post = goal_center.y + GOAL_WIDTH;
// Calculate distance to goal
let ball_to_goal_vector = goal_center - field.ball.position;
let horizontal_distance = (ball_to_goal_vector.x * ball_to_goal_vector.x +
ball_to_goal_vector.y * ball_to_goal_vector.y).sqrt();
// Safety check: if ball is already at/very near the goal, just give it a gentle push
if horizontal_distance < MIN_SHOT_DISTANCE {
let direction = if ball_to_goal_vector.x.abs() > 0.01 {
Vector3::new(ball_to_goal_vector.x.signum(), 0.0, 0.0)
} else {
Vector3::new(1.0, 0.0, 0.0) // Default direction
};
field.ball.previous_owner = Some(shoot_event_model.from_player_id);
field.ball.current_owner = None;
field.ball.velocity = direction * 2.0; // Gentle push
field.ball.flags.in_flight_state = 20;
return;
}
// Calculate overall shooting accuracy (0.0 to 1.0)
let base_accuracy = if horizontal_distance > 100.0 {
// Long shots depend more on long_shot skill and technique
(long_shot_skill * 0.5 + technique_skill * 0.3 + finishing_skill * 0.2) * composure_skill
} else if horizontal_distance > 50.0 {
// Medium range - balanced
(finishing_skill * 0.4 + technique_skill * 0.3 + long_shot_skill * 0.3) * composure_skill
} else {
// Close range - finishing is key
finishing_skill * 0.6 + technique_skill * 0.2 + composure_skill * 0.2
};
// Calculate target point within goal (aim for corners/areas based on skill)
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | true |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/events/models/shooting.rs | src/core/src/match/engine/player/events/models/shooting.rs | use crate::r#match::StateProcessingContext;
use nalgebra::Vector3;
#[derive(Debug)]
pub struct ShootingEventContext {
pub from_player_id: u32,
pub target: Vector3<f32>,
pub force: f64,
pub reason: &'static str,
}
impl ShootingEventContext {
pub fn new() -> ShootingEventBuilder{
ShootingEventBuilder::new()
}
}
pub struct ShootingEventBuilder {
from_player_id: Option<u32>,
target: Option<Vector3<f32>>,
reason: Option<&'static str>,
}
impl Default for ShootingEventBuilder {
fn default() -> Self {
ShootingEventBuilder::new()
}
}
impl ShootingEventBuilder {
pub fn new() -> Self {
ShootingEventBuilder {
from_player_id: None,
target: None,
reason: None,
}
}
pub fn with_player_id(mut self, from_player_id: u32) -> Self {
self.from_player_id = Some(from_player_id);
self
}
pub fn with_target(mut self, target: Vector3<f32>) -> Self {
self.target = Some(target);
self
}
pub fn with_reason(mut self, reason: &'static str) -> Self {
self.reason = Some(reason);
self
}
pub fn build(self, ctx: &StateProcessingContext) -> ShootingEventContext {
ShootingEventContext {
from_player_id: self.from_player_id.unwrap(),
target: self.target.unwrap(),
force: ctx.player().shoot_goal_power(),
reason: self.reason.unwrap_or("No reason specified"),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/events/models/mod.rs | src/core/src/match/engine/player/events/models/mod.rs | pub mod passing;
pub mod shooting;
pub use passing::*;
pub use shooting::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/events/models/passing.rs | src/core/src/match/engine/player/events/models/passing.rs | use crate::r#match::StateProcessingContext;
use nalgebra::Vector3;
#[derive(Debug)]
pub struct PassingEventContext {
pub from_player_id: u32,
pub to_player_id: u32,
pub pass_target: Vector3<f32>,
pub pass_force: f32,
pub reason: &'static str,
}
impl PassingEventContext {
pub fn new() -> PassingEventBuilder{
PassingEventBuilder::new()
}
}
pub struct PassingEventBuilder {
from_player_id: Option<u32>,
to_player_id: Option<u32>,
pass_force: Option<f32>,
reason: Option<&'static str>,
}
impl Default for PassingEventBuilder {
fn default() -> Self {
PassingEventBuilder::new()
}
}
impl PassingEventBuilder {
pub fn new() -> Self {
PassingEventBuilder {
from_player_id: None,
to_player_id: None,
pass_force: None,
reason: None,
}
}
pub fn with_from_player_id(mut self, from_player_id: u32) -> Self {
self.from_player_id = Some(from_player_id);
self
}
pub fn with_to_player_id(mut self, to_player_id: u32) -> Self {
self.to_player_id = Some(to_player_id);
self
}
pub fn with_pass_force(mut self, pass_force: f32) -> Self {
self.pass_force = Some(pass_force);
self
}
pub fn with_reason(mut self, reason: &'static str) -> Self {
self.reason = Some(reason);
self
}
pub fn build(self, ctx: &StateProcessingContext) -> PassingEventContext {
let to_player_id = self.to_player_id.unwrap();
PassingEventContext {
from_player_id: self.from_player_id.unwrap(),
to_player_id,
pass_target: ctx.tick_context.positions.players.position(to_player_id),
pass_force: self.pass_force.unwrap_or_else(|| ctx.player().pass_teammate_power(to_player_id)),
reason: self.reason.unwrap_or("No reason specified"),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/behaviours/steering.rs | src/core/src/match/engine/player/behaviours/steering.rs | use crate::r#match::MatchPlayer;
use nalgebra::Vector3;
pub enum SteeringBehavior {
Seek {
target: Vector3<f32>,
},
Arrive {
target: Vector3<f32>,
slowing_distance: f32,
},
Pursuit {
target: Vector3<f32>,
target_velocity: Vector3<f32>,
},
Evade {
target: Vector3<f32>
},
Wander {
target: Vector3<f32>,
radius: f32,
jitter: f32,
distance: f32,
angle: f32,
},
Flee {
target: Vector3<f32>,
},
FollowPath {
waypoints: Vec<Vector3<f32>>,
current_waypoint: usize,
path_offset: f32,
},
}
impl SteeringBehavior {
pub fn calculate(&self, player: &MatchPlayer) -> SteeringOutput {
match self {
SteeringBehavior::Seek { target } => {
let to_target = *target - player.position;
let max_speed = player.skills.max_speed_with_condition(
player.player_attributes.condition,
);
let desired_velocity = if to_target.norm() > 0.0 {
to_target.normalize() * max_speed
} else {
Vector3::zeros()
};
let steering = desired_velocity - player.velocity;
let max_force = player.skills.physical.acceleration / 20.0;
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to get new absolute velocity
let new_velocity = player.velocity + steering;
let final_velocity = Self::limit_magnitude(new_velocity, max_speed);
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
SteeringBehavior::Arrive {
target,
slowing_distance,
} => {
let to_target = *target - player.position;
let distance = to_target.norm();
// Stop if very close to target
const ARRIVAL_DEADZONE: f32 = 1.0; // Increased from 0.5 for better stability
if distance < ARRIVAL_DEADZONE {
// Apply strong braking to prevent oscillation
let braking_force = -player.velocity * 0.6; // Increased from 0.3 for better stopping
let new_velocity = player.velocity + braking_force;
return SteeringOutput {
velocity: new_velocity,
rotation: 0.0,
};
}
// Normalize skill values
let pace_normalized = 0.8 + (player.skills.physical.pace - 1.0) / 19.0;
let agility_normalized = 0.8 + (player.skills.physical.agility - 1.0) / 19.0;
// Ensure slowing_distance is never zero (increased for smoother deceleration)
let safe_slowing_distance = slowing_distance.max(8.0); // Increased from 5.0
// Calculate desired speed based on distance (with condition factor)
let max_speed = player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * pace_normalized;
let desired_speed = if distance < safe_slowing_distance {
// Smooth cubic deceleration for better control (changed from quadratic)
let ratio = (distance / safe_slowing_distance).clamp(0.0, 1.0);
max_speed * ratio * ratio * ratio
} else {
max_speed
};
// Calculate desired velocity direction
let desired_velocity = if distance > 0.0 {
to_target.normalize() * desired_speed
} else {
Vector3::zeros()
};
// Calculate steering force (the change in velocity needed)
let steering = desired_velocity - player.velocity;
// Limit steering force based on agility (with condition)
let max_force = player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * agility_normalized * 0.7;
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to current velocity to get new absolute velocity
let new_velocity = player.velocity + steering;
// Clamp to max speed
let final_velocity = Self::limit_magnitude(new_velocity, max_speed);
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
SteeringBehavior::Pursuit { target, target_velocity } => {
// Calculate interception point by predicting where the target will be
let to_target = *target - player.position;
let distance = to_target.norm();
// Deadzone to prevent oscillation when very close
const PURSUIT_DEADZONE: f32 = 1.5;
const SLOWING_DISTANCE: f32 = 10.0;
if distance < PURSUIT_DEADZONE {
// Very close to target - apply strong braking
let braking_force = -player.velocity * 0.9;
let new_velocity = player.velocity + braking_force;
return SteeringOutput {
velocity: new_velocity,
rotation: 0.0,
};
}
// Normalize skill values
let acceleration_normalized = 1.2 + (player.skills.physical.acceleration - 1.0) / 19.0;
let pace_normalized = 1.1 + (player.skills.physical.pace - 1.0) / 19.0;
let agility_normalized = 1.1 + (player.skills.physical.agility - 1.0) / 19.0;
let max_speed = player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * pace_normalized * acceleration_normalized;
// Calculate interception point
let interception_point = Self::calculate_interception_point(
player.position,
*target,
*target_velocity,
max_speed,
);
// Calculate direction to interception point
let to_interception = interception_point - player.position;
let interception_distance = to_interception.norm();
// Calculate desired speed based on distance - slow down when approaching
let desired_speed = if interception_distance < SLOWING_DISTANCE {
// Within slowing distance - reduce speed proportionally
let speed_ratio = (interception_distance / SLOWING_DISTANCE).clamp(0.2, 1.0);
max_speed * speed_ratio
} else {
// Full speed when far away
max_speed
};
let desired_velocity = if interception_distance > 0.0 {
to_interception.normalize() * desired_speed
} else {
Vector3::zeros()
};
// Use direct velocity blending when close to prevent oscillation
let final_velocity = if interception_distance < SLOWING_DISTANCE {
// Close to target - blend toward desired velocity to prevent overshoot
let blend_factor = (interception_distance / SLOWING_DISTANCE).clamp(0.0, 1.0);
let damping = 0.7 - (blend_factor * 0.3); // More damping when closer
desired_velocity * (1.0 - damping) + player.velocity * damping
} else {
// Far from target - use normal steering accumulation
let steering = desired_velocity - player.velocity;
let max_acceleration = player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * agility_normalized * acceleration_normalized;
let limited_steering = Self::limit_magnitude(steering, max_acceleration);
let move_velocity = player.velocity + limited_steering;
Self::limit_magnitude(move_velocity, max_speed)
};
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
SteeringBehavior::Evade { target } => {
let to_player = player.position - *target;
let desired_velocity = if to_player.norm() > 0.0 {
to_player.normalize() * player.skills.max_speed_with_condition(
player.player_attributes.condition,
)
} else {
Vector3::zeros()
};
let steering = desired_velocity - player.velocity;
// Limit the steering force like other behaviors
let max_force = player.skills.physical.acceleration / 20.0;
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to get new absolute velocity
let new_velocity = player.velocity + steering;
let final_velocity = Self::limit_magnitude(new_velocity, player.skills.max_speed_with_condition(
player.player_attributes.condition,
));
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
SteeringBehavior::Wander {
target: _,
radius,
jitter: _,
distance,
angle
} => {
// The wander circle is projected in front of the player
let circle_center = player.position + player.velocity.normalize() * *distance;
// Calculate the displacement around the circle using the stored angle
let displacement = Vector3::new(
angle.cos() * *radius,
angle.sin() * *radius,
0.0,
);
// The wander target is on the circle's edge
let wander_target = circle_center + displacement;
// Calculate desired velocity toward the wander target
let to_target = wander_target - player.position;
let desired_velocity = if to_target.norm() > 0.0 {
to_target.normalize() * player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * 0.3 // Reduced speed for wandering
} else {
Vector3::zeros()
};
let steering = desired_velocity - player.velocity;
// Limit steering force
let max_force = player.skills.physical.acceleration / 30.0; // Gentler force
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to get new absolute velocity
let new_velocity = player.velocity + steering;
let wander_max_speed = player.skills.max_speed_with_condition(
player.player_attributes.condition,
) * 0.3; // Wandering is slower
let final_velocity = Self::limit_magnitude(new_velocity, wander_max_speed);
let rotation = if final_velocity.x != 0.0 || final_velocity.y != 0.0 {
final_velocity.y.atan2(final_velocity.x)
} else {
0.0
};
SteeringOutput {
velocity: final_velocity,
rotation,
}
}
SteeringBehavior::Flee { target } => {
let to_player = player.position - *target;
let desired_velocity = if to_player.norm() > 0.0 {
to_player.normalize() * player.skills.max_speed_with_condition(
player.player_attributes.condition,
)
} else {
Vector3::zeros()
};
let steering = desired_velocity - player.velocity;
let max_force = player.skills.physical.acceleration / 20.0;
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to get new absolute velocity
let new_velocity = player.velocity + steering;
let final_velocity = Self::limit_magnitude(new_velocity, player.skills.max_speed_with_condition(
player.player_attributes.condition,
));
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
SteeringBehavior::FollowPath { waypoints, current_waypoint, path_offset } => {
if waypoints.is_empty() {
return SteeringOutput {
velocity: Vector3::zeros(),
rotation: 0.0,
};
}
// Get the current target waypoint
if *current_waypoint >= waypoints.len() {
return SteeringOutput {
velocity: Vector3::zeros(),
rotation: 0.0,
};
}
let target = waypoints[*current_waypoint];
// Calculate distance to current waypoint
let to_waypoint = target - player.position;
let distance = to_waypoint.norm();
// Calculate desired velocity toward waypoint with slight offset for natural movement
let direction = if distance > 0.0 {
to_waypoint.normalize()
} else {
Vector3::zeros()
};
// Apply slight offset if specified (makes movement more natural)
let offset_direction = if *path_offset > 0.0 {
// Create a perpendicular vector for offset
Vector3::new(-direction.y, direction.x, 0.0) * *path_offset
} else {
Vector3::zeros()
};
let desired_velocity = (direction + offset_direction.normalize() * 0.1) * player.skills.max_speed_with_condition(
player.player_attributes.condition,
);
let steering = desired_velocity - player.velocity;
// Limit steering force
let max_force = player.skills.physical.acceleration / 20.0;
let steering = Self::limit_magnitude(steering, max_force);
// Apply steering force to get new absolute velocity
let new_velocity = player.velocity + steering;
let final_velocity = Self::limit_magnitude(new_velocity, player.skills.max_speed_with_condition(
player.player_attributes.condition,
));
SteeringOutput {
velocity: final_velocity,
rotation: 0.0,
}
}
}
}
fn limit_magnitude(v: Vector3<f32>, max_magnitude: f32) -> Vector3<f32> {
let current_magnitude = v.norm();
if current_magnitude > max_magnitude && current_magnitude > 0.0 {
v * (max_magnitude / current_magnitude)
} else {
v
}
}
fn calculate_interception_point(
pursuer_pos: Vector3<f32>,
target_pos: Vector3<f32>,
target_vel: Vector3<f32>,
pursuer_speed: f32,
) -> Vector3<f32> {
// If target is not moving, just return its current position
let target_speed = target_vel.norm();
if target_speed < 0.01 {
return target_pos;
}
// Calculate relative position
let relative_pos = target_pos - pursuer_pos;
let distance_sq = relative_pos.norm_squared();
// If target is very close, just return its current position
if distance_sq < 1.0 {
return target_pos;
}
// Calculate time to intercept using quadratic formula
// We're solving: |relative_pos + target_vel * t| = pursuer_speed * t
// Which expands to: a*t^2 + b*t + c = 0
let target_speed_sq = target_vel.norm_squared();
let pursuer_speed_sq = pursuer_speed * pursuer_speed;
let a = target_speed_sq - pursuer_speed_sq;
let b = 2.0 * relative_pos.dot(&target_vel);
let c = distance_sq;
// Solve quadratic equation
let discriminant = b * b - 4.0 * a * c;
let intercept_time = if discriminant < 0.0 {
// No real solution - target is too fast to catch
// Aim for where target will be in 1 second
1.0
} else if a.abs() < 0.001 {
// Linear case (pursuer and target have same speed)
if b.abs() < 0.001 {
0.0
} else {
-c / b
}
} else {
// Quadratic case - take the smaller positive root
let sqrt_discriminant = discriminant.sqrt();
let t1 = (-b - sqrt_discriminant) / (2.0 * a);
let t2 = (-b + sqrt_discriminant) / (2.0 * a);
// Choose the smallest positive time
if t1 > 0.0 && t2 > 0.0 {
t1.min(t2)
} else if t1 > 0.0 {
t1
} else if t2 > 0.0 {
t2
} else {
// Both negative, can't intercept - aim ahead by 1 second
1.0
}
};
// Clamp intercept time to reasonable range (0.1 to 5 seconds)
let clamped_time = intercept_time.clamp(0.1, 5.0);
// Calculate predicted position
target_pos + target_vel * clamped_time
}
}
#[derive(Debug, Clone, Copy)]
pub struct SteeringOutput {
pub velocity: Vector3<f32>,
pub rotation: f32,
}
impl SteeringOutput {
pub fn new(velocity: Vector3<f32>, rotation: f32) -> Self {
SteeringOutput { velocity, rotation }
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/behaviours/mod.rs | src/core/src/match/engine/player/behaviours/mod.rs | pub mod steering;
pub use steering::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/behaviours/events/dispatcher.rs | src/core/src/match/engine/player/behaviours/events/dispatcher.rs | use crate::r#match::ball::events::{BallEvent, BallEventDispatcher};
use crate::r#match::player::events::{PlayerEvent, PlayerEventDispatcher};
use crate::r#match::{MatchContext, MatchField};
pub enum Event {
BallEvent(BallEvent),
PlayerEvent(PlayerEvent),
}
pub struct EventCollection {
events: Vec<Event>,
}
impl EventCollection {
pub fn new() -> Self {
EventCollection {
events: Vec::with_capacity(10),
}
}
pub fn with_event(event: Event) -> Self {
EventCollection {
events: vec![event],
}
}
pub fn add(&mut self, event: Event) {
self.events.push(event)
}
pub fn add_ball_event(&mut self, event: BallEvent) {
self.events.push(Event::BallEvent(event))
}
pub fn add_player_event(&mut self, event: PlayerEvent) {
self.events.push(Event::PlayerEvent(event))
}
pub fn add_range(&mut self, events: Vec<Event>) {
for event in events {
self.events.push(event);
}
}
pub fn add_from_collection(&mut self, events: EventCollection) {
for event in events.events {
self.events.push(event);
}
}
pub fn to_vec(self) -> Vec<Event> {
self.events
}
}
pub struct EventDispatcher;
impl EventDispatcher {
pub fn dispatch(
events: Vec<Event>,
field: &mut MatchField,
context: &mut MatchContext,
process_remaining_events: bool,
) {
let mut remaining_events = Vec::with_capacity(10);
for event in events {
match event {
Event::BallEvent(ball_event) => {
let mut ball_remaining_events =
BallEventDispatcher::dispatch(ball_event, field, context);
if process_remaining_events {
remaining_events.append(&mut ball_remaining_events);
}
}
Event::PlayerEvent(player_event) => {
let mut player_remaining_events =
PlayerEventDispatcher::dispatch(player_event, field, context);
if process_remaining_events {
remaining_events.append(&mut player_remaining_events);
}
}
}
}
if process_remaining_events {
Self::dispatch(remaining_events, field, context, false)
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/behaviours/events/mod.rs | src/core/src/match/engine/player/behaviours/events/mod.rs | pub mod dispatcher;
pub use dispatcher::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/processor.rs | src/core/src/match/engine/player/strategies/processor.rs | use crate::r#match::defenders::states::{DefenderState, DefenderStrategies};
use crate::r#match::events::{Event, EventCollection};
use crate::r#match::forwarders::states::{ForwardState, ForwardStrategies};
use crate::r#match::goalkeepers::states::state::{GoalkeeperState, GoalkeeperStrategies};
use crate::r#match::midfielders::states::{MidfielderState, MidfielderStrategies};
use crate::r#match::player::state::PlayerState;
use crate::r#match::player::state::PlayerState::{Defender, Forward, Goalkeeper, Midfielder};
use crate::r#match::{
BallOperationsImpl, GameTickContext, MatchContext, MatchPlayer,
};
use crate::r#match::common_states::CommonInjuredState;
use crate::r#match::player::strategies::common::PlayerOperationsImpl;
use crate::r#match::player::strategies::common::PlayersOperationsImpl;
use crate::r#match::team::TeamOperationsImpl;
use crate::PlayerFieldPositionGroup;
use log::debug;
use nalgebra::Vector3;
pub trait StateProcessingHandler {
// Try fast processing
fn try_fast(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult>;
// Try slow processing with neural network
fn process_slow(&self, ctx: &StateProcessingContext) -> Option<StateChangeResult>;
// Calculate velocity
fn velocity(&self, ctx: &StateProcessingContext) -> Option<Vector3<f32>>;
// Calculate changind conditions
fn process_conditions(&self, ctx: ConditionContext);
}
impl PlayerFieldPositionGroup {
pub fn process(
&self,
in_state_time: u64,
player: &mut MatchPlayer,
context: &MatchContext,
tick_context: &GameTickContext,
) -> StateProcessingResult {
let player_state = player.state;
let state_processor = StateProcessor::new(in_state_time, player, context, tick_context);
match player_state {
// Common states
PlayerState::Injured => state_processor.process(CommonInjuredState::default()),
// // Specific states
Goalkeeper(state) => GoalkeeperStrategies::process(state, state_processor),
Defender(state) => DefenderStrategies::process(state, state_processor),
Midfielder(state) => MidfielderStrategies::process(state, state_processor),
Forward(state) => ForwardStrategies::process(state, state_processor),
}
}
}
pub struct StateProcessor<'p> {
in_state_time: u64,
player: &'p mut MatchPlayer,
context: &'p MatchContext,
tick_context: &'p GameTickContext,
}
impl<'p> StateProcessor<'p> {
pub fn new(
in_state_time: u64,
player: &'p mut MatchPlayer,
context: &'p MatchContext,
tick_context: &'p GameTickContext,
) -> Self {
StateProcessor {
in_state_time,
player,
context,
tick_context,
}
}
pub fn process<H: StateProcessingHandler>(self, handler: H) -> StateProcessingResult {
let condition_ctx = ConditionContext {
in_state_time: self.in_state_time,
player: self.player,
};
// Process player conditions
handler.process_conditions(condition_ctx);
self.process_inner(handler)
}
pub fn process_inner<H: StateProcessingHandler>(self, handler: H) -> StateProcessingResult {
let player_id = self.player.id;
let need_extended_state_logging = self.player.use_extended_state_logging;
let processing_ctx = self.into_ctx();
let mut result = StateProcessingResult::new();
if let Some(velocity) = handler.velocity(&processing_ctx) {
result.velocity = Some(velocity);
}
// common logic
let complete_result = |state_results: StateChangeResult,
mut result: StateProcessingResult| {
if let Some(state) = state_results.state {
if need_extended_state_logging {
debug!("Player, Id={}, State {:?}", player_id, state);
}
result.state = Some(state);
result.events = state_results.events;
}
result
};
if let Some(fast_result) = handler.try_fast(&processing_ctx) {
return complete_result(fast_result, result);
}
if let Some(slow_result) = handler.process_slow(&processing_ctx) {
return complete_result(slow_result, result);
}
result
}
pub fn into_ctx(self) -> StateProcessingContext<'p> {
StateProcessingContext::from(self)
}
}
pub struct ConditionContext<'sp> {
pub in_state_time: u64,
pub player: &'sp mut MatchPlayer,
}
pub struct StateProcessingContext<'sp> {
pub in_state_time: u64,
pub player: &'sp MatchPlayer,
pub context: &'sp MatchContext,
pub tick_context: &'sp GameTickContext,
}
impl<'sp> StateProcessingContext<'sp> {
#[inline]
pub fn ball(&'sp self) -> BallOperationsImpl<'sp> {
BallOperationsImpl::new(self)
}
#[inline]
pub fn player(&'sp self) -> PlayerOperationsImpl<'sp> {
PlayerOperationsImpl::new(self)
}
#[inline]
pub fn players(&'sp self) -> PlayersOperationsImpl<'sp> {
PlayersOperationsImpl::new(self)
}
#[inline]
pub fn team(&'sp self) -> TeamOperationsImpl<'sp> {
TeamOperationsImpl::new(self)
}
}
impl<'sp> From<StateProcessor<'sp>> for StateProcessingContext<'sp> {
fn from(value: StateProcessor<'sp>) -> Self {
StateProcessingContext {
in_state_time: value.in_state_time,
player: value.player,
context: value.context,
tick_context: value.tick_context,
}
}
}
pub struct StateProcessingResult {
pub state: Option<PlayerState>,
pub velocity: Option<Vector3<f32>>,
pub events: EventCollection,
}
impl Default for StateProcessingResult {
fn default() -> Self {
Self::new()
}
}
impl StateProcessingResult {
pub fn new() -> Self {
StateProcessingResult {
state: None,
velocity: None,
events: EventCollection::new(),
}
}
}
pub struct StateChangeResult {
pub state: Option<PlayerState>,
pub velocity: Option<Vector3<f32>>,
pub events: EventCollection,
}
impl Default for StateChangeResult {
fn default() -> Self {
Self::new()
}
}
impl StateChangeResult {
pub fn new() -> Self {
StateChangeResult {
state: None,
velocity: None,
events: EventCollection::new(),
}
}
pub fn with(state: PlayerState) -> Self {
StateChangeResult {
state: Some(state),
velocity: None,
events: EventCollection::new(),
}
}
pub fn with_goalkeeper_state(state: GoalkeeperState) -> Self {
StateChangeResult {
state: Some(Goalkeeper(state)),
velocity: None,
events: EventCollection::new(),
}
}
pub fn with_goalkeeper_state_and_event(state: GoalkeeperState, event: Event) -> Self {
StateChangeResult {
state: Some(Goalkeeper(state)),
velocity: None,
events: EventCollection::with_event(event),
}
}
pub fn with_defender_state(state: DefenderState) -> Self {
StateChangeResult {
state: Some(Defender(state)),
velocity: None,
events: EventCollection::new(),
}
}
pub fn with_defender_state_and_event(state: DefenderState, event: Event) -> Self {
StateChangeResult {
state: Some(Defender(state)),
velocity: None,
events: EventCollection::with_event(event),
}
}
pub fn with_midfielder_state(state: MidfielderState) -> Self {
StateChangeResult {
state: Some(Midfielder(state)),
velocity: None,
events: EventCollection::new(),
}
}
pub fn with_midfielder_state_and_event(state: MidfielderState, event: Event) -> Self {
StateChangeResult {
state: Some(Midfielder(state)),
velocity: None,
events: EventCollection::with_event(event),
}
}
pub fn with_forward_state(state: ForwardState) -> Self {
StateChangeResult {
state: Some(Forward(state)),
velocity: None,
events: EventCollection::new(),
}
}
pub fn with_forward_state_and_event(state: ForwardState, event: Event) -> Self {
StateChangeResult {
state: Some(Forward(state)),
velocity: None,
events: EventCollection::with_event(event),
}
}
pub fn with_event(event: Event) -> Self {
StateChangeResult {
state: None,
velocity: None,
events: EventCollection::with_event(event),
}
}
pub fn with_events(events: EventCollection) -> Self {
StateChangeResult {
state: None,
velocity: None,
events,
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/mod.rs | src/core/src/match/engine/player/strategies/mod.rs | mod common;
pub mod defenders;
pub mod forwarders;
pub mod goalkeepers;
pub mod midfielders;
pub mod processor;
// Re-export common items
pub use common::{
ball::{BallOperationsImpl, MatchBallLogic},
passing, players, team,
};
pub use common::states as common_states;
// Re-export defenders items
pub use defenders::decision;
pub use defenders::states as defender_states;
pub use processor::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/midfielders/mod.rs | src/core/src/match/engine/player/strategies/midfielders/mod.rs | pub mod states;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/midfielders/states/state.rs | src/core/src/match/engine/player/strategies/midfielders/states/state.rs | use crate::r#match::midfielders::states::{MidfielderAttackSupportingState, MidfielderCreatingSpaceState, MidfielderCrossingState, MidfielderDistanceShootingState, MidfielderDistributingState, MidfielderDribblingState, MidfielderHoldingPossessionState, MidfielderInterceptingState, MidfielderPassingState, MidfielderPressingState, MidfielderRestingState, MidfielderReturningState, MidfielderRunningState, MidfielderShootingState, MidfielderStandingState, MidfielderSwitchingPlayState, MidfielderTacklingState, MidfielderTakeBallState, MidfielderTrackingRunnerState, MidfielderWalkingState};
use crate::r#match::{StateProcessingResult, StateProcessor};
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MidfielderState {
Standing, // Standing still
Distributing, // Distributing the ball to teammates
Dribbling, // Dribbling the ball
AttackSupporting, // Supporting the attack, moving forward
HoldingPossession, // Holding possession of the ball, maintaining control
SwitchingPlay, // Switching the play to the other side of the field
Crossing, // Delivering a cross into the box
Passing, // Executing a pass
Running, // Running in the direction of the ball
DistanceShooting, // Taking a shot from a long distance
Pressing, // Pressing the opponent to regain possession
TrackingRunner, // Tracking a runner to prevent a break
Tackling, // Tackling to win the ball
Returning, // Returning the ball,
Resting, // Resting
Walking, // Walking
TakeBall, // Take the ball,
Shooting, // Shooting,
Intercepting, // Intercepting the ball,
CreatingSpace, // Creating space for teammates
}
pub struct MidfielderStrategies {}
impl MidfielderStrategies {
pub fn process(
state: MidfielderState,
state_processor: StateProcessor,
) -> StateProcessingResult {
match state {
MidfielderState::Standing => {
state_processor.process(MidfielderStandingState::default())
}
MidfielderState::Distributing => {
state_processor.process(MidfielderDistributingState::default())
}
MidfielderState::AttackSupporting => {
state_processor.process(MidfielderAttackSupportingState::default())
}
MidfielderState::HoldingPossession => {
state_processor.process(MidfielderHoldingPossessionState::default())
}
MidfielderState::SwitchingPlay => {
state_processor.process(MidfielderSwitchingPlayState::default())
}
MidfielderState::Crossing => {
state_processor.process(MidfielderCrossingState::default())
}
MidfielderState::Passing => state_processor.process(MidfielderPassingState::default()),
MidfielderState::DistanceShooting => {
state_processor.process(MidfielderDistanceShootingState::default())
}
MidfielderState::Pressing => {
state_processor.process(MidfielderPressingState::default())
}
MidfielderState::TrackingRunner => {
state_processor.process(MidfielderTrackingRunnerState::default())
}
MidfielderState::Tackling => {
state_processor.process(MidfielderTacklingState::default())
}
MidfielderState::Returning => {
state_processor.process(MidfielderReturningState::default())
}
MidfielderState::Resting => {
state_processor.process(MidfielderRestingState::default())
}
MidfielderState::Walking => state_processor.process(MidfielderWalkingState::default()),
MidfielderState::Running => state_processor.process(MidfielderRunningState::default()),
MidfielderState::TakeBall => {
state_processor.process(MidfielderTakeBallState::default())
}
MidfielderState::Dribbling => {
state_processor.process(MidfielderDribblingState::default())
}
MidfielderState::Shooting => {
state_processor.process(MidfielderShootingState::default())
}
MidfielderState::Intercepting => {
state_processor.process(MidfielderInterceptingState::default())
},
MidfielderState::CreatingSpace => {
state_processor.process(MidfielderCreatingSpaceState::default())
},
}
}
}
impl Display for MidfielderState {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
MidfielderState::Standing => write!(f, "Standing"),
MidfielderState::Distributing => write!(f, "Distributing"),
MidfielderState::AttackSupporting => write!(f, "Supporting Attack"),
MidfielderState::HoldingPossession => write!(f, "Holding Possession"),
MidfielderState::SwitchingPlay => write!(f, "Switching Play"),
MidfielderState::Crossing => write!(f, "Crossing"),
MidfielderState::Passing => write!(f, "Passing"),
MidfielderState::Pressing => write!(f, "Pressing"),
MidfielderState::TrackingRunner => write!(f, "Tracking Runner"),
MidfielderState::Tackling => write!(f, "Tackling"),
MidfielderState::DistanceShooting => write!(f, "DistanceShooting"),
MidfielderState::Returning => write!(f, "Returning"),
MidfielderState::Resting => write!(f, "Resting"),
MidfielderState::Walking => write!(f, "Walking"),
MidfielderState::Running => write!(f, "Running"),
MidfielderState::TakeBall => write!(f, "Take Ball"),
MidfielderState::Dribbling => write!(f, "Dribbling"),
MidfielderState::Shooting => write!(f, "Shooting"),
MidfielderState::Intercepting => write!(f, "Intercepting"),
MidfielderState::CreatingSpace => write!(f, "Creating Space"),
}
}
}
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
ZOXEXIVO/open-football | https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/match/engine/player/strategies/midfielders/states/mod.rs | src/core/src/match/engine/player/strategies/midfielders/states/mod.rs | pub mod attack_supporting;
pub mod common;
pub mod crossing;
pub mod distance_shooting;
pub mod distributing;
pub mod dribbling;
pub mod holding_posession;
pub mod passing;
pub mod pressing;
pub mod resting;
pub mod returning;
pub mod running;
pub mod shooting;
pub mod standing;
pub mod state;
pub mod switching_play;
pub mod tackling;
pub mod takeball;
pub mod tracking_runner;
pub mod walking;
pub mod intercepting;
pub mod creating_space;
pub use attack_supporting::*;
pub use creating_space::*;
pub use crossing::*;
pub use distance_shooting::*;
pub use distributing::*;
pub use dribbling::*;
pub use holding_posession::*;
pub use intercepting::*;
pub use passing::*;
pub use pressing::*;
pub use resting::*;
pub use returning::*;
pub use running::*;
pub use shooting::*;
pub use standing::*;
pub use state::*;
pub use switching_play::*;
pub use tackling::*;
pub use takeball::*;
pub use tracking_runner::*;
pub use walking::*;
| rust | Apache-2.0 | 7b55c8c095942c1df498d7aa02b524af6e3a896c | 2026-01-04T20:24:06.162327Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.