repo_id stringlengths 4 98 | size int64 611 5.02M | file_path stringlengths 1 276 | content stringlengths 611 5.02M | shard_id int64 0 109 | quality_score float32 0.5 1 | quality_prediction int8 1 1 | quality_confidence float32 0.5 1 | topic_primary stringclasses 1 value | topic_group stringclasses 1 value | topic_score float32 0.05 1 | topic_all stringclasses 96 values | quality2_score float32 0.5 1 | quality2_prediction int8 1 1 | quality2_confidence float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lua9520/source-engine-2018-hl2_src | 4,499 | game/server/portal/portal_client.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
/*
===== portal_client.cpp ========================================================
Portal client/server game specific stuff
*/
#include "cbase.h"
#include "portal_player.h"
#include "portal_gamerules.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
#include "entitylist.h"
#include "physics.h"
#include "game.h"
#include "player_resource.h"
#include "engine/IEngineSound.h"
#include "tier0/vprof.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
void Host_Say( edict_t *pEdict, bool teamonly );
extern CBaseEntity* FindPickerEntityClass( CBasePlayer *pPlayer, char *classname );
extern bool g_fGameOver;
/*
===========
ClientPutInServer
called each time a player is spawned into the game
============
*/
void ClientPutInServer( edict_t *pEdict, const char *playername )
{
// Allocate a CBasePlayer for pev, and call spawn
CPortal_Player *pPlayer = CPortal_Player::CreatePlayer( "player", pEdict );
pPlayer->PlayerData()->netname = AllocPooledString( playername );
}
void ClientActive( edict_t *pEdict, bool bLoadGame )
{
CPortal_Player *pPlayer = dynamic_cast< CPortal_Player* >( CBaseEntity::Instance( pEdict ) );
Assert( pPlayer );
pPlayer->InitialSpawn();
if ( !bLoadGame )
{
pPlayer->Spawn();
}
}
/*
===============
const char *GetGameDescription()
Returns the descriptive name of this .dll. E.g., Half-Life, or Team Fortress 2
===============
*/
const char *GetGameDescription()
{
if ( g_pGameRules ) // this function may be called before the world has spawned, and the game rules initialized
return g_pGameRules->GetGameDescription();
else
return "Half-Life 2";
}
//-----------------------------------------------------------------------------
// Purpose: Given a player and optional name returns the entity of that
// classname that the player is nearest facing
//
// Input :
// Output :
//-----------------------------------------------------------------------------
CBaseEntity* FindEntity( edict_t *pEdict, char *classname)
{
// If no name was given set bits based on the picked
if (FStrEq(classname,""))
{
return (FindPickerEntityClass( static_cast<CBasePlayer*>(GetContainingEntity(pEdict)), classname ));
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Precache game-specific models & sounds
//-----------------------------------------------------------------------------
void ClientGamePrecache( void )
{
CBaseEntity::PrecacheModel("models/player.mdl");
CBaseEntity::PrecacheModel( "models/gibs/agibs.mdl" );
CBaseEntity::PrecacheModel("models/weapons/v_hands.mdl");
CBaseEntity::PrecacheScriptSound( "HUDQuickInfo.LowAmmo" );
CBaseEntity::PrecacheScriptSound( "HUDQuickInfo.LowHealth" );
CBaseEntity::PrecacheScriptSound( "Missile.ShotDown" );
CBaseEntity::PrecacheScriptSound( "Bullets.DefaultNearmiss" );
CBaseEntity::PrecacheScriptSound( "Bullets.GunshipNearmiss" );
CBaseEntity::PrecacheScriptSound( "Bullets.StriderNearmiss" );
CBaseEntity::PrecacheScriptSound( "Geiger.BeepHigh" );
CBaseEntity::PrecacheScriptSound( "Geiger.BeepLow" );
CBaseEntity::PrecacheModel( "models/portals/portal1.mdl" );
CBaseEntity::PrecacheModel( "models/portals/portal2.mdl" );
}
// called by ClientKill and DeadThink
void respawn( CBaseEntity *pEdict, bool fCopyCorpse )
{
if (gpGlobals->coop || gpGlobals->deathmatch)
{
if ( fCopyCorpse )
{
// make a copy of the dead body for appearances sake
((CPortal_Player *)pEdict)->CreateCorpse();
}
// respawn player
pEdict->Spawn();
}
else
{ // restart the entire server
engine->ServerCommand("reload\n");
}
}
void GameStartFrame( void )
{
VPROF("GameStartFrame()");
if ( g_fGameOver )
return;
gpGlobals->teamplay = (teamplay.GetInt() != 0);
}
//=========================================================
// instantiate the proper game rules object
//=========================================================
void InstallGameRules()
{
if ( !gpGlobals->deathmatch )
{
CreateGameRulesObject( "CPortalGameRules" );
return;
}
else
{
if ( teamplay.GetInt() > 0 )
{
// teamplay
CreateGameRulesObject( "CTeamplayRules" );
}
else
{
// vanilla deathmatch
CreateGameRulesObject( "CMultiplayRules" );
}
}
}
| 0 | 0.913875 | 1 | 0.913875 | game-dev | MEDIA | 0.925592 | game-dev | 0.782967 | 1 | 0.782967 |
Secrets-of-Sosaria/World | 5,105 | Data/Scripts/Magic/Research/Spells/Conjuration/ResearchConjure.cs | using System;
using Server.Targeting;
using Server.Network;
using Server;
using Server.Items;
namespace Server.Spells.Research
{
public class ResearchConjure : ResearchSpell
{
public override int spellIndex { get { return 1; } }
public override bool alwaysConsume { get{ return bool.Parse( Server.Misc.Research.SpellInformation( spellIndex, 14 )); } }
public int CirclePower = 1;
public static int spellID = 1;
public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 2.0 ); } }
public override double RequiredSkill{ get{ return (double)(Int32.Parse( Server.Misc.Research.SpellInformation( spellIndex, 8 ))); } }
public override int RequiredMana{ get{ return Int32.Parse( Server.Misc.Research.SpellInformation( spellIndex, 7 )); } }
private static SpellInfo m_Info = new SpellInfo(
Server.Misc.Research.SpellInformation( spellID, 2 ),
Server.Misc.Research.CapsCast( Server.Misc.Research.SpellInformation( spellID, 4 ) ),
203,
9041,
Reagent.MoonCrystal,Reagent.FairyEgg
);
public ResearchConjure( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnCast()
{
if ( CheckSequence() )
{
Item item = new Dagger();
string msg = "You conjure a dagger.";
switch( Utility.RandomMinMax( 1, 27 ) )
{
case 1: item = new Apple(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure some apples.";
if ( Server.Items.BaseRace.BloodDrinker( Caster.RaceID ) ){ item = new BloodyDrink(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh blood."; }
else if ( Server.Items.BaseRace.BrainEater( Caster.RaceID ) ){ item = new FreshBrain(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh brains."; }
break;
case 2: item = new Arrow(); item.Amount = Utility.RandomMinMax( 1, 10 ); msg = "You conjure some arrows."; break;
case 3: item = new Backpack(); msg = "You conjure a backpack."; break;
case 4: item = new Bag(); msg = "You conjure a bag."; break;
case 5: item = new Bandage(); item.Amount = Utility.RandomMinMax( 1, 10 ); msg = "You conjure some bandages."; break;
case 6: item = new Bedroll(); msg = "You conjure a bedroll."; break;
case 7: item = new Beeswax(); msg = "You conjure some beeswax."; break;
case 8: item = new WritingBook(); msg = "You conjure a book."; break;
case 9: item = new Bolt(); item.Amount = Utility.RandomMinMax( 1, 10 ); msg = "You conjure some crossbow bolts."; break;
case 10: item = new Bottle(); msg = "You conjure a bottle."; break;
case 11: item = new BreadLoaf(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure some bread.";
if ( Server.Items.BaseRace.BloodDrinker( Caster.RaceID ) ){ item = new BloodyDrink(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh blood."; }
else if ( Server.Items.BaseRace.BrainEater( Caster.RaceID ) ){ item = new FreshBrain(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh brains."; }
break;
case 12: item = new Candle(); msg = "You conjure a candle."; break;
case 13: item = new Club(); msg = "You conjure a club."; break;
case 14: item = new Dagger(); msg = "You conjure a dagger."; break;
case 15: item = new FloppyHat(); msg = "You conjure a hat."; break;
case 16: item = new Jar(); msg = "You conjure a jar."; break;
case 17: item = new Kindling(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure some kindling."; break;
case 18: item = new Lantern(); msg = "You conjure a lantern."; break;
case 19: item = new Lockpick(); msg = "You conjure a lockpick."; break;
case 20: item = new OilCloth(); msg = "You conjure an oil cloth."; break;
case 21: item = new Pouch(); msg = "You conjure a pouch."; break;
case 22: item = new Robe(); msg = "You conjure a robe."; break;
case 23: item = new Shoes(); msg = "You conjure some shoes."; break;
case 24: item = new SpoolOfThread(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure some string."; break;
case 25: item = new TenFootPole(); msg = "You conjure a ten foot pole."; break;
case 26: item = new Torch(); msg = "You conjure a torch."; break;
case 27: item = new Pitcher( BeverageType.Water ); msg = "You conjure a decanter of water.";
if ( Server.Items.BaseRace.BloodDrinker( Caster.RaceID ) ){ item = new BloodyDrink(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh blood."; }
else if ( Server.Items.BaseRace.BrainEater( Caster.RaceID ) ){ item = new FreshBrain(); item.Amount = Utility.RandomMinMax( 1, 5 ); msg = "You conjure fresh brains."; }
break;
}
Caster.SendMessage( msg );
Caster.AddToBackpack( item );
Caster.FixedParticles( 0, 10, 5, 2003, Server.Misc.PlayerSettings.GetMySpellHue( true, Caster, 0 ), 0, EffectLayer.RightHand );
Caster.PlaySound( 0x1E2 );
Server.Misc.Research.ConsumeScroll( Caster, true, spellIndex, alwaysConsume, Scroll );
}
FinishSequence();
}
}
}
| 0 | 0.711602 | 1 | 0.711602 | game-dev | MEDIA | 0.870595 | game-dev | 0.762406 | 1 | 0.762406 |
klebs6/aloe-rs | 6,918 | aloe-box2d/src/common_b2blockallocator.rs | crate::ix!();
//-------------------------------------------[.cpp/Aloe/modules/aloe_box2d/box2d/Common/b2BlockAllocator.h]
pub const b2_chunkSize: usize = 16 * 1024;
pub const b2_maxBlockSize: usize = 640;
pub const b2_blockSizes: usize = 14;
pub const b2_chunkArrayIncrement: usize = 128;
pub struct b2Chunk
{
block_size: i32,
blocks: *mut b2Block,
}
pub struct b2Block
{
next: *mut b2Block,
}
/**
| This is a small object allocator used for
| allocating small objects that persist for more
| than one time step. See:
| http://www.codeproject.com/useritems/Small_Block_Allocator.asp
*/
pub struct b2BlockAllocator {
chunks: *mut b2Chunk,
chunk_count: i32,
chunk_space: i32,
free_lists: *mut [b2Block; b2_blockSizes],
}
impl Drop for b2BlockAllocator {
fn drop(&mut self) {
todo!();
/*
for (int32 i = 0; i < m_chunkCount; ++i)
{
b2Free(m_chunks[i].blocks);
}
b2Free(m_chunks);
*/
}
}
pub mod b2_block_allocator {
use super::*;
lazy_static!{
/*
static int32 s_blockSizes[b2_blockSizes];
static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
static bool s_blockSizeLookupInitialized;
int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] =
{
16, // 0
32, // 1
64, // 2
96, // 3
128, // 4
160, // 5
192, // 6
224, // 7
256, // 8
320, // 9
384, // 10
448, // 11
512, // 12
640, // 13
};
uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1];
bool b2BlockAllocator::s_blockSizeLookupInitialized;
*/
}
}
//-------------------------------------------[.cpp/Aloe/modules/aloe_box2d/box2d/Common/b2BlockAllocator.cpp]
impl Default for b2BlockAllocator {
fn default() -> Self {
todo!();
/*
b2Assert(b2_blockSizes < UCHAR_MAX);
m_chunkSpace = b2_chunkArrayIncrement;
m_chunkCount = 0;
m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
memset(m_freeLists, 0, sizeof(m_freeLists));
if (s_blockSizeLookupInitialized == false)
{
int32 j = 0;
for (int32 i = 1; i <= b2_maxBlockSize; ++i)
{
b2Assert(j < b2_blockSizes);
if (i <= s_blockSizes[j])
{
s_blockSizeLookup[i] = (uint8)j;
}
else
{
++j;
s_blockSizeLookup[i] = (uint8)j;
}
}
s_blockSizeLookupInitialized = true;
}
*/
}
}
impl b2BlockAllocator {
/**
| Allocate memory. This will use b2Alloc
| if the size is larger than b2_maxBlockSize.
|
*/
pub fn allocate(&mut self, size: i32) {
todo!();
/*
if (size == 0)
return NULL;
b2Assert(0 < size);
if (size > b2_maxBlockSize)
{
return b2Alloc(size);
}
int32 index = s_blockSizeLookup[size];
b2Assert(0 <= index && index < b2_blockSizes);
if (m_freeLists[index])
{
b2Block* block = m_freeLists[index];
m_freeLists[index] = block->next;
return block;
}
else
{
if (m_chunkCount == m_chunkSpace)
{
b2Chunk* oldChunks = m_chunks;
m_chunkSpace += b2_chunkArrayIncrement;
m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk));
memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk));
b2Free(oldChunks);
}
b2Chunk* chunk = m_chunks + m_chunkCount;
chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize);
#if defined(_DEBUG)
memset(chunk->blocks, 0xcd, b2_chunkSize);
#endif
int32 blockSize = s_blockSizes[index];
chunk->blockSize = blockSize;
int32 blockCount = b2_chunkSize / blockSize;
b2Assert(blockCount * blockSize <= b2_chunkSize);
for (int32 i = 0; i < blockCount - 1; ++i)
{
b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i);
b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1));
block->next = next;
}
b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1));
last->next = NULL;
m_freeLists[index] = chunk->blocks->next;
++m_chunkCount;
return chunk->blocks;
}
*/
}
/**
| Free memory. This will use b2Free if
| the size is larger than b2_maxBlockSize.
|
*/
pub fn free(
&mut self,
p: *mut c_void,
size: i32
) {
todo!();
/*
if (size == 0)
{
return;
}
b2Assert(0 < size);
if (size > b2_maxBlockSize)
{
b2Free(p);
return;
}
int32 index = s_blockSizeLookup[size];
b2Assert(0 <= index && index < b2_blockSizes);
#ifdef _DEBUG
// Verify the memory address and size is valid.
int32 blockSize = s_blockSizes[index];
bool found = false;
for (int32 i = 0; i < m_chunkCount; ++i)
{
b2Chunk* chunk = m_chunks + i;
if (chunk->blockSize != blockSize)
{
b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks ||
(int8*)chunk->blocks + b2_chunkSize <= (int8*)p);
}
else
{
if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize)
{
found = true;
}
}
}
b2Assert(found);
memset(p, 0xfd, blockSize);
#endif
b2Block* block = (b2Block*)p;
block->next = m_freeLists[index];
m_freeLists[index] = block;
*/
}
pub fn clear(&mut self) {
todo!();
/*
for (int32 i = 0; i < m_chunkCount; ++i)
{
b2Free(m_chunks[i].blocks);
}
m_chunkCount = 0;
memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
memset(m_freeLists, 0, sizeof(m_freeLists));
*/
}
}
| 0 | 0.786357 | 1 | 0.786357 | game-dev | MEDIA | 0.583593 | game-dev | 0.759315 | 1 | 0.759315 |
utilForever/2023-UNIST-Rust-Minecraft | 10,478 | 2 - Example/240321 - Rust Basic + Make Minecraft, Week X/src/chunk_manager.rs | use crate::block_texture_sides::{get_uv_every_side, BlockFaces};
use crate::chunk::{BlockID, Chunk};
use crate::shader::ShaderProgram;
use crate::shapes::write_unit_cube_to_ptr;
use crate::UVCoords;
use nalgebra::Matrix4;
use nalgebra_glm::vec3;
use noise::{NoiseFn, SuperSimplex};
use rand::random;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
pub const CHUNK_SIZE: u32 = 16;
pub const CHUNK_VOLUME: u32 = CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE;
pub type Sides = [bool; 6];
#[derive(Default)]
pub struct ChunkManager {
pub loaded_chunks: HashMap<(i32, i32, i32), Chunk>,
}
impl ChunkManager {
pub fn preload_some_chunks(&mut self) {
for y in 0..2 {
for z in 0..2 {
for x in 0..2 {
self.loaded_chunks.insert((x, y, z), Chunk::random());
}
}
}
}
pub fn simplex(&mut self) {
let ss = SuperSimplex::new(1296);
let n = 5;
for y in 0..16 {
for z in -n..=n {
for x in -n..=n {
self.loaded_chunks.insert((x, y, z), Chunk::empty());
}
}
}
for x in -16 * n..16 * n {
for z in -16 * n..16 * n {
let (xf, zf) = (x as f64 / 64.0, z as f64 / 64.0);
let y = ss.get([xf, zf]);
let y = (16.0 * (y + 1.0)) as i32;
self.set_block(x, y, z, BlockID::GrassBlock);
self.set_block(x, y - 1, z, BlockID::Dirt);
self.set_block(x, y - 2, z, BlockID::Dirt);
self.set_block(x, y - 3, z, BlockID::Cobblestone);
if random::<u32>() % 100 == 0 {
let h = 5;
for i in y + 1..y + 1 + h {
self.set_block(x, i, z, BlockID::OakLog);
}
for yy in y + h - 2..=y + h - 1 {
for xx in x - 2..=x + 2 {
for zz in z - 2..=z + 2 {
if xx != x || zz != z {
self.set_block(xx, yy, zz, BlockID::OakLeaves);
}
}
}
}
for xx in x - 1..=x + 1 {
for zz in z - 1..=z + 1 {
if xx != x || zz != z {
self.set_block(xx, y + h, zz, BlockID::OakLeaves);
}
}
}
self.set_block(x, y + h + 1, z, BlockID::OakLeaves);
self.set_block(x + 1, y + h + 1, z, BlockID::OakLeaves);
self.set_block(x - 1, y + h + 1, z, BlockID::OakLeaves);
self.set_block(x, y + h + 1, z + 1, BlockID::OakLeaves);
self.set_block(x, y + h + 1, z - 1, BlockID::OakLeaves);
}
}
}
}
fn get_chunk_and_block_coords(x: i32, y: i32, z: i32) -> (i32, i32, i32, u32, u32, u32) {
let chunk_x = if x < 0 { (x + 1) / 16 - 1 } else { x / 16 };
let chunk_y = if y < 0 { (y + 1) / 16 - 1 } else { y / 16 };
let chunk_z = if z < 0 { (z + 1) / 16 - 1 } else { z / 16 };
let block_x = x.rem_euclid(16) as u32;
let block_y = y.rem_euclid(16) as u32;
let block_z = z.rem_euclid(16) as u32;
(chunk_x, chunk_y, chunk_z, block_x, block_y, block_z)
}
fn get_global_coords(
(chunk_x, chunk_y, chunk_z, block_x, block_y, block_z): (i32, i32, i32, u32, u32, u32),
) -> (i32, i32, i32) {
let x = 16 * chunk_x + block_x as i32;
let y = 16 * chunk_y + block_y as i32;
let z = 16 * chunk_z + block_z as i32;
(x, y, z)
}
pub fn get_block(&self, x: i32, y: i32, z: i32) -> Option<BlockID> {
let (chunk_x, chunk_y, chunk_z, block_x, block_y, block_z) =
ChunkManager::get_chunk_and_block_coords(x, y, z);
self.loaded_chunks
.get((chunk_x, chunk_y, chunk_z).borrow())
.map(|chunk| chunk.get_block(block_x, block_y, block_z))
}
pub fn set_block(&mut self, x: i32, y: i32, z: i32, block: BlockID) {
let (chunk_x, chunk_y, chunk_z, block_x, block_y, block_z) =
ChunkManager::get_chunk_and_block_coords(x, y, z);
if let Some(chunk) = self
.loaded_chunks
.get_mut((chunk_x, chunk_y, chunk_z).borrow())
{
chunk.set_block(block_x, block_y, block_z, block);
}
}
pub fn rebuild_dirty_chunks(&mut self, uv_map: &HashMap<BlockID, BlockFaces<UVCoords>>) {
let mut dirty_chunks = HashSet::new();
// Nearby chunks can be also dirty if the change happens at the edge
for (&(x, y, z), chunk) in self.loaded_chunks.iter() {
if chunk.dirty {
dirty_chunks.insert((x, y, z));
}
for &(dx, dy, dz) in chunk.dirty_neighbours.iter() {
dirty_chunks.insert((x + dx, y + dy, z + dz));
}
}
let mut active_sides: HashMap<(i32, i32, i32), Vec<Sides>> = HashMap::new();
for &coords in dirty_chunks.iter() {
let (cx, cy, cz) = coords;
let chunk = self.loaded_chunks.get(&coords);
if let Some(chunk) = chunk {
let sides_vec = active_sides.entry(coords).or_default();
for by in 0..CHUNK_SIZE {
for bz in 0..CHUNK_SIZE {
for bx in 0..CHUNK_SIZE {
if !chunk.get_block(bx, by, bz).is_air() {
let (gx, gy, gz) =
ChunkManager::get_global_coords((cx, cy, cz, bx, by, bz));
sides_vec.push(self.get_active_sides_of_block(gx, gy, gz));
}
}
}
}
}
}
for coords in dirty_chunks.iter() {
let chunk = self.loaded_chunks.get_mut(coords);
if let Some(chunk) = chunk {
chunk.dirty = false;
chunk.dirty_neighbours.clear();
chunk.vertices_drawn = 0;
let sides = active_sides.get(coords).unwrap();
let n_visible_faces = sides
.iter()
.map(|faces| faces.iter().fold(0, |acc, &x| acc + x as u32))
.fold(0, |acc, n| acc + n);
if n_visible_faces == 0 {
continue;
}
// Initialize the VBO
gl_call!(gl::NamedBufferData(
chunk.vbo,
(180 * std::mem::size_of::<f32>() * n_visible_faces as usize) as isize,
std::ptr::null(),
gl::DYNAMIC_DRAW
));
let vbo_ptr = gl_call!(gl::MapNamedBuffer(chunk.vbo, gl::WRITE_ONLY)) as *mut f32;
let mut idx = 0;
let sides_vec = active_sides.get(coords).unwrap();
let mut cnt = 0;
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
for x in 0..CHUNK_SIZE {
let block = chunk.get_block(x, y, z);
if block != BlockID::Air {
let active_sides = sides_vec[cnt];
let uvs = uv_map.get(&block).unwrap().clone();
let uvs = get_uv_every_side(uvs);
let copied_vertices = unsafe {
write_unit_cube_to_ptr(
vbo_ptr.offset(idx),
(x as f32, y as f32, z as f32),
uvs,
active_sides,
)
};
chunk.vertices_drawn += copied_vertices;
idx += copied_vertices as isize * 5;
cnt += 1;
}
}
}
}
gl_call!(gl::UnmapNamedBuffer(chunk.vbo));
}
}
}
pub fn get_active_sides_of_block(&self, x: i32, y: i32, z: i32) -> Sides {
let right = self
.get_block(x + 1, y, z)
.filter(|&b| !b.is_transparent())
.is_none();
let left = self
.get_block(x - 1, y, z)
.filter(|&b| !b.is_transparent())
.is_none();
let top = self
.get_block(x, y + 1, z)
.filter(|&b| !b.is_transparent())
.is_none();
let bottom = self
.get_block(x, y - 1, z)
.filter(|&b| !b.is_transparent())
.is_none();
let front = self
.get_block(x, y, z + 1)
.filter(|&b| !b.is_transparent())
.is_none();
let back = self
.get_block(x, y, z - 1)
.filter(|&b| !b.is_transparent())
.is_none();
[right, left, top, bottom, front, back]
}
pub fn render_loaded_chunks(&mut self, program: &mut ShaderProgram) {
for ((x, y, z), chunk) in &self.loaded_chunks {
// Skip rendering the chunk if there is nothing to draw
if chunk.vertices_drawn == 0 {
continue;
}
let model_matrix = {
let translate_matrix =
Matrix4::new_translation(&vec3(*x as f32, *y as f32, *z as f32).scale(16.0));
let rotate_matrix = Matrix4::from_euler_angles(0.0f32, 0.0, 0.0);
let scale_matrix = Matrix4::new_nonuniform_scaling(&vec3(1.0f32, 1.0f32, 1.0f32));
translate_matrix * rotate_matrix * scale_matrix
};
gl_call!(gl::BindVertexArray(chunk.vao));
unsafe {
program.set_uniform_matrix4fv("model", model_matrix.as_ptr());
}
gl_call!(gl::DrawArrays(
gl::TRIANGLES,
0,
chunk.vertices_drawn as i32
));
}
}
}
| 0 | 0.96543 | 1 | 0.96543 | game-dev | MEDIA | 0.293882 | game-dev | 0.969437 | 1 | 0.969437 |
ReactiveDrop/reactivedrop_public_src | 13,554 | src/game/server/hl2/script_intro.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#include "cbase.h"
#include "eventqueue.h"
#include "script_intro.h"
#include "point_camera.h"
#include "ai_utils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// Used by server and client to calculate our FOV blend at any given frame
extern float ScriptInfo_CalculateFOV( float flFOVBlendStartTime, float flNextFOVBlendTime, int nFOV, int nNextFOV, bool bSplineRamp );
// Global point to the active intro script
CHandle<CScriptIntro> g_hIntroScript;
LINK_ENTITY_TO_CLASS(script_intro, CScriptIntro);
BEGIN_DATADESC(CScriptIntro)
// Keys
DEFINE_FIELD( m_vecCameraView, FIELD_VECTOR ),
DEFINE_FIELD( m_vecCameraViewAngles, FIELD_VECTOR ),
DEFINE_FIELD( m_vecPlayerView, FIELD_VECTOR ),
DEFINE_FIELD( m_vecPlayerViewAngles, FIELD_VECTOR ),
DEFINE_FIELD( m_iBlendMode, FIELD_INTEGER ),
DEFINE_FIELD( m_iQueuedBlendMode, FIELD_INTEGER ),
DEFINE_FIELD( m_iQueuedNextBlendMode, FIELD_INTEGER ),
DEFINE_FIELD( m_iNextBlendMode, FIELD_INTEGER ),
DEFINE_FIELD( m_flNextBlendTime, FIELD_TIME ),
DEFINE_FIELD( m_flBlendStartTime, FIELD_TIME ),
DEFINE_FIELD( m_bActive, FIELD_BOOLEAN ),
DEFINE_FIELD( m_iNextFOV, FIELD_INTEGER ),
DEFINE_FIELD( m_flNextFOVBlendTime, FIELD_TIME ),
DEFINE_FIELD( m_flFOVBlendStartTime, FIELD_TIME ),
DEFINE_FIELD( m_iFOV, FIELD_INTEGER ),
DEFINE_ARRAY( m_flFadeColor, FIELD_FLOAT, 3 ),
DEFINE_FIELD( m_flFadeAlpha, FIELD_FLOAT ),
DEFINE_FIELD( m_flFadeDuration, FIELD_FLOAT ),
DEFINE_FIELD( m_hCameraEntity, FIELD_EHANDLE ),
DEFINE_FIELD( m_iStartFOV, FIELD_INTEGER ),
DEFINE_KEYFIELD( m_bAlternateFOV, FIELD_BOOLEAN, "alternatefovchange" ),
// Inputs
DEFINE_INPUTFUNC(FIELD_STRING, "SetCameraViewEntity", InputSetCameraViewEntity ),
DEFINE_INPUTFUNC(FIELD_INTEGER, "SetBlendMode", InputSetBlendMode ),
DEFINE_INPUTFUNC(FIELD_INTEGER, "SetNextFOV", InputSetNextFOV ),
DEFINE_INPUTFUNC(FIELD_FLOAT, "SetFOVBlendTime", InputSetFOVBlendTime ),
DEFINE_INPUTFUNC(FIELD_INTEGER, "SetFOV", InputSetFOV ),
DEFINE_INPUTFUNC(FIELD_INTEGER, "SetNextBlendMode", InputSetNextBlendMode ),
DEFINE_INPUTFUNC(FIELD_FLOAT, "SetNextBlendTime", InputSetNextBlendTime ),
DEFINE_INPUTFUNC(FIELD_VOID, "Activate", InputActivate ),
DEFINE_INPUTFUNC(FIELD_VOID, "Deactivate", InputDeactivate ),
DEFINE_INPUTFUNC(FIELD_STRING, "FadeTo", InputFadeTo ),
DEFINE_INPUTFUNC(FIELD_STRING, "SetFadeColor", InputSetFadeColor ),
DEFINE_THINKFUNC( BlendComplete ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CScriptIntro, DT_ScriptIntro )
SendPropVector(SENDINFO(m_vecCameraView), -1, SPROP_COORD),
SendPropVector(SENDINFO(m_vecCameraViewAngles), -1, SPROP_COORD),
SendPropInt( SENDINFO( m_iBlendMode ), 5 ),
SendPropInt( SENDINFO( m_iNextBlendMode ), 5 ),
SendPropFloat( SENDINFO( m_flNextBlendTime ), 10 ),
SendPropFloat( SENDINFO( m_flBlendStartTime ), 10 ),
SendPropBool( SENDINFO( m_bActive ) ),
// Fov & fov blends
SendPropInt( SENDINFO( m_iFOV ), 9 ),
SendPropInt( SENDINFO( m_iNextFOV ), 9 ),
SendPropInt( SENDINFO( m_iStartFOV ), 9 ),
SendPropFloat( SENDINFO( m_flNextFOVBlendTime ), 10 ),
SendPropFloat( SENDINFO( m_flFOVBlendStartTime ), 10 ),
SendPropBool( SENDINFO( m_bAlternateFOV ) ),
// Fades
SendPropFloat( SENDINFO( m_flFadeAlpha ), 10 ),
SendPropArray(
SendPropFloat( SENDINFO_ARRAY(m_flFadeColor), 32, SPROP_NOSCALE),
m_flFadeColor),
SendPropFloat( SENDINFO( m_flFadeDuration ), 10, SPROP_ROUNDDOWN, 0.0f, 255.0 ),
SendPropEHandle(SENDINFO( m_hCameraEntity ) ),
END_SEND_TABLE()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::Spawn( void )
{
m_iNextBlendMode = -1;
m_iQueuedBlendMode = -1;
m_iQueuedNextBlendMode = -1;
AddSolidFlags( FSOLID_NOT_SOLID );
SetSize( -Vector(5,5,5), Vector(5,5,5) );
m_bActive = false;
m_iNextFOV = 0;
m_iFOV = 0;
m_iStartFOV = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::Activate( void )
{
// Restore our script pointer, this is necessary to trigger other internal logic to due with PVS checks
if ( m_bActive )
{
g_hIntroScript = this;
}
BaseClass::Activate();
}
void CScriptIntro::Precache()
{
PrecacheMaterial( "scripted/intro_screenspaceeffect" );
BaseClass::Precache();
}
//------------------------------------------------------------------------------
// Purpose : Send even though we don't have a model.
//------------------------------------------------------------------------------
int CScriptIntro::UpdateTransmitState()
{
return SetTransmitState( FL_EDICT_ALWAYS );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetCameraViewEntity( inputdata_t &inputdata )
{
// Find the specified entity
string_t iszEntityName = inputdata.value.StringID();
if ( iszEntityName == NULL_STRING )
return;
CBaseEntity *pEntity = gEntList.FindEntityByName( NULL, iszEntityName, NULL, inputdata.pActivator, inputdata.pCaller );
if ( !pEntity )
{
Warning("script_intro %s couldn't find SetCameraViewEntity named %s\n", STRING(GetEntityName()), STRING(iszEntityName) );
return;
}
m_hCameraEntity = pEntity;
m_vecCameraView = pEntity->GetAbsOrigin();
m_vecCameraViewAngles = pEntity->GetAbsAngles();
}
//-----------------------------------------------------------------------------
// Purpose: Fill out the origin that should be included in the player's PVS
//-----------------------------------------------------------------------------
bool CScriptIntro::GetIncludedPVSOrigin( Vector *pOrigin, CBaseEntity **ppCamera )
{
if ( m_bActive && m_hCameraEntity.Get() )
{
*ppCamera = m_hCameraEntity.Get();
*pOrigin = m_hCameraEntity.Get()->GetAbsOrigin();
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Used for debugging
//-----------------------------------------------------------------------------
static ConVar cl_spewscriptintro( "cl_spewscriptintro", "0" );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetBlendMode( inputdata_t &inputdata )
{
m_iBlendMode = m_iNextBlendMode = inputdata.value.Int();
m_flBlendStartTime = m_flNextBlendTime = gpGlobals->curtime;
m_iQueuedBlendMode = -1;
SetContextThink( NULL, gpGlobals->curtime, "BlendComplete" );
if ( cl_spewscriptintro.GetInt() )
{
DevMsg( 1, "%.2f INPUT: Blend mode set to %d\n", gpGlobals->curtime, m_iBlendMode.Get() );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetNextBlendMode( inputdata_t &inputdata )
{
m_iQueuedNextBlendMode = inputdata.value.Int();
if ( cl_spewscriptintro.GetInt() )
{
DevMsg( 1, "%.2f INPUT: Next Blend mode set to %d\n", gpGlobals->curtime, m_iQueuedNextBlendMode );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetNextFOV( inputdata_t &inputdata )
{
m_iNextFOV = inputdata.value.Int();
}
//------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetFOVBlendTime( inputdata_t &inputdata )
{
// Cache our FOV starting point before we update our data here
if ( m_flNextFOVBlendTime >= gpGlobals->curtime )
{
// We're already in a blend, so capture where we are at this point in time
m_iStartFOV = ScriptInfo_CalculateFOV( m_flFOVBlendStartTime, m_flNextFOVBlendTime, m_iStartFOV, m_iNextFOV, m_bAlternateFOV );
}
else
{
// If we weren't blending, then we need to construct a proper starting point from scratch
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if ( pPlayer )
{
m_iStartFOV = ( m_iFOV ) ? m_iFOV : pPlayer->GetFOV();
}
else
{
m_iStartFOV = m_iFOV;
}
}
m_flNextFOVBlendTime = gpGlobals->curtime + inputdata.value.Float();
m_flFOVBlendStartTime = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetFOV( inputdata_t &inputdata )
{
m_iFOV = inputdata.value.Int();
m_iStartFOV = m_iFOV;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetNextBlendTime( inputdata_t &inputdata )
{
m_flNextBlendTime = gpGlobals->curtime + inputdata.value.Float();
m_flBlendStartTime = gpGlobals->curtime;
// This logic is used to support continued calls to SetNextBlendMode
// without intervening calls to SetBlendMode
if ( m_iQueuedBlendMode >= 0 )
{
m_iBlendMode = m_iQueuedBlendMode;
}
if ( m_iQueuedNextBlendMode < 0 )
{
Warning( "script_intro: Warning!! Set blend time without setting next blend mode!\n" );
m_iQueuedNextBlendMode = m_iBlendMode;
}
m_iNextBlendMode = m_iQueuedNextBlendMode;
m_iQueuedNextBlendMode = -1;
m_iQueuedBlendMode = m_iNextBlendMode;
if ( cl_spewscriptintro.GetInt() )
{
DevMsg( 1, "%.2f BLEND STARTED: %d to %d, end at %.2f\n", gpGlobals->curtime, m_iBlendMode.Get(), m_iNextBlendMode.Get(), m_flNextBlendTime.Get() );
}
SetContextThink( &CScriptIntro::BlendComplete, m_flNextBlendTime, "BlendComplete" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CScriptIntro::BlendComplete( )
{
m_iBlendMode = m_iNextBlendMode;
m_flBlendStartTime = m_flNextBlendTime = gpGlobals->curtime;
m_iQueuedBlendMode = -1;
SetContextThink( NULL, gpGlobals->curtime, "BlendComplete" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputActivate( inputdata_t &inputdata )
{
m_bActive = true;
g_hIntroScript = this;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputDeactivate( inputdata_t &inputdata )
{
m_bActive = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputFadeTo( inputdata_t &inputdata )
{
char parseString[255];
Q_strncpy(parseString, inputdata.value.String(), sizeof(parseString));
// Get the fade alpha
char *pszParam = strtok(parseString," ");
if ( !pszParam || !pszParam[0] )
{
Warning("%s (%s) received FadeTo input without an alpha. Syntax: <fade alpha> <fade duration>\n", GetClassname(), GetDebugName() );
return;
}
float flAlpha = atof( pszParam );
// Get the fade duration
pszParam = strtok(NULL," ");
if ( !pszParam || !pszParam[0] )
{
Warning("%s (%s) received FadeTo input without a duration. Syntax: <fade alpha> <fade duration>\n", GetClassname(), GetDebugName() );
return;
}
// Set the two variables
m_flFadeAlpha = flAlpha;
m_flFadeDuration = atof( pszParam );
//Msg("%.2f INPUT FADE: Fade to %.2f. End at %.2f\n", gpGlobals->curtime, m_flFadeAlpha.Get(), gpGlobals->curtime + m_flFadeDuration.Get() );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CScriptIntro::InputSetFadeColor( inputdata_t &inputdata )
{
char parseString[255];
Q_strncpy(parseString, inputdata.value.String(), sizeof(parseString));
// Get the fade colors
char *pszParam = strtok(parseString," ");
if ( !pszParam || !pszParam[0] )
{
Warning("%s (%s) received SetFadeColor input without correct parameters. Syntax: <Red> <Green> <Blue>>\n", GetClassname(), GetDebugName() );
return;
}
float flR = atof( pszParam );
pszParam = strtok(NULL," ");
if ( !pszParam || !pszParam[0] )
{
Warning("%s (%s) received SetFadeColor input without correct parameters. Syntax: <Red> <Green> <Blue>>\n", GetClassname(), GetDebugName() );
return;
}
float flG = atof( pszParam );
pszParam = strtok(NULL," ");
if ( !pszParam || !pszParam[0] )
{
Warning("%s (%s) received SetFadeColor input without correct parameters. Syntax: <Red> <Green> <Blue>>\n", GetClassname(), GetDebugName() );
return;
}
float flB = atof( pszParam );
// Use the colors
m_flFadeColor.Set( 0, flR );
m_flFadeColor.Set( 1, flG );
m_flFadeColor.Set( 2, flB );
}
| 0 | 0.955918 | 1 | 0.955918 | game-dev | MEDIA | 0.791607 | game-dev | 0.953485 | 1 | 0.953485 |
SpectrumIM/spectrum2 | 4,065 | backends/frotz/dfrotz/common/main.c | /* main.c - Frotz V2.40 main function
* Copyright (c) 1995-1997 Stefan Jokisch
*
* This file is part of Frotz.
*
* Frotz is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Frotz is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/*
* This is an interpreter for Infocom V1 to V6 games. It also supports
* the recently defined V7 and V8 games. Please report bugs to
*
* s.jokisch@avu.de
*
*/
#include "frotz.h"
#ifndef MSDOS_16BIT
#define cdecl
#endif
extern void init_memory (void);
extern void init_undo (void);
extern void init_sound (void);
extern void init_buffer (void);
extern void init_process (void);
extern void interpret (void);
extern void reset_memory (void);
/* Story file name, id number and size */
char *story_name = 0;
enum story story_id = UNKNOWN;
long story_size = 0;
/* Story file header data */
zbyte h_version = 0;
zbyte h_config = 0;
zword h_release = 0;
zword h_resident_size = 0;
zword h_start_pc = 0;
zword h_dictionary = 0;
zword h_objects = 0;
zword h_globals = 0;
zword h_dynamic_size = 0;
zword h_flags = 0;
zbyte h_serial[6] = { 0, 0, 0, 0, 0, 0 };
zword h_abbreviations = 0;
zword h_file_size = 0;
zword h_checksum = 0;
zbyte h_interpreter_number = 0;
zbyte h_interpreter_version = 0;
zbyte h_screen_rows = 0;
zbyte h_screen_cols = 0;
zword h_screen_width = 0;
zword h_screen_height = 0;
zbyte h_font_height = 1;
zbyte h_font_width = 1;
zword h_functions_offset = 0;
zword h_strings_offset = 0;
zbyte h_default_background = 0;
zbyte h_default_foreground = 0;
zword h_terminating_keys = 0;
zword h_line_width = 0;
zbyte h_standard_high = 1;
zbyte h_standard_low = 0;
zword h_alphabet = 0;
zword h_extension_table = 0;
zbyte h_user_name[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
zword hx_table_size = 0;
zword hx_mouse_x = 0;
zword hx_mouse_y = 0;
zword hx_unicode_table = 0;
/* Stack data */
zword stack[STACK_SIZE];
zword *sp = 0;
zword *fp = 0;
zword frame_count = 0;
/* IO streams */
bool ostream_screen = TRUE;
bool ostream_script = FALSE;
bool ostream_memory = FALSE;
bool ostream_record = FALSE;
bool istream_replay = FALSE;
bool message = FALSE;
/* Current window and mouse data */
int cwin = 0;
int mwin = 0;
int mouse_y = 0;
int mouse_x = 0;
/* Window attributes */
bool enable_wrapping = FALSE;
bool enable_scripting = FALSE;
bool enable_scrolling = FALSE;
bool enable_buffering = FALSE;
/* User options */
/*
int option_attribute_assignment = 0;
int option_attribute_testing = 0;
int option_context_lines = 0;
int option_object_locating = 0;
int option_object_movement = 0;
int option_left_margin = 0;
int option_right_margin = 0;
int option_ignore_errors = 0;
int option_piracy = 0;
int option_undo_slots = MAX_UNDO_SLOTS;
int option_expand_abbreviations = 0;
int option_script_cols = 80;
int option_save_quetzal = 1;
*/
int option_sound = 1;
char *option_zcode_path;
/* Size of memory to reserve (in bytes) */
long reserve_mem = 0;
/*
* z_piracy, branch if the story file is a legal copy.
*
* no zargs used
*
*/
void z_piracy (void)
{
branch (!f_setup.piracy);
}/* z_piracy */
/*
* main
*
* Prepare and run the game.
*
*/
int cdecl main (int argc, char *argv[])
{
os_init_setup ();
os_process_arguments (argc, argv);
init_buffer ();
init_err ();
init_memory ();
init_process ();
init_sound ();
os_init_screen ();
init_undo ();
z_restart ();
interpret ();
reset_memory ();
os_reset_screen ();
return 0;
}/* main */
| 0 | 0.748662 | 1 | 0.748662 | game-dev | MEDIA | 0.307088 | game-dev | 0.881322 | 1 | 0.881322 |
xfl03/MCCustomSkinLoader | 5,212 | Fabric/src/main/java/customskinloader/fabric/DevEnvRemapper.java | package customskinloader.fabric;
import java.lang.reflect.Field;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.common.collect.Lists;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.impl.FabricLoaderImpl;
import net.fabricmc.loader.impl.game.patch.GameTransformer;
import org.apache.commons.io.IOUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.SimpleRemapper;
import org.objectweb.asm.tree.ClassNode;
public class DevEnvRemapper extends SimpleRemapper {
// key: correct method owner names,
// value:
// left: fake method owner names,
// right: other classes which contain fake methods.
private static Map<String, Map.Entry<List<String>, List<String>>> remappedClasses = new HashMap<>();
static {
remappedClasses.put(
"net.minecraft.class_310",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeMinecraft"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_1011",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeNativeImage"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_3298",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeIResource$V1", "customskinloader.fake.itf.IFakeIResource$V2"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_3300",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeIResourceManager"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
}
@SuppressWarnings("unchecked")
public static void initRemapper() {
try {
if (FabricLoader.getInstance().isDevelopmentEnvironment()) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Field patchedClassesField = GameTransformer.class.getDeclaredField("patchedClasses");
patchedClassesField.setAccessible(true);
Map<String, byte[]> patchedClasses = (Map<String, byte[]>) patchedClassesField.get(FabricLoaderImpl.INSTANCE.getGameProvider().getEntrypointTransformer());
for (Map.Entry<String, Map.Entry<List<String>, List<String>>> entry : remappedClasses.entrySet()) {
List<String> targetClasses = new ArrayList<>(entry.getValue().getKey());
targetClasses.addAll(entry.getValue().getValue());
for (String clazz : targetClasses) {
byte[] classBytes = patchedClasses.get(clazz);
if (classBytes == null) {
classBytes = IOUtils.toByteArray(Objects.requireNonNull(cl.getResourceAsStream(clazz.replace(".", "/") + ".class")));
}
patchedClasses.put(clazz, remapClass(entry.getKey(), classBytes));
}
}
}
} catch (Throwable t) {
MixinConfigPlugin.logger.warning(t);
}
}
// Remap all method names with specific method owner name.
public static byte[] remapClass(String owner, byte[] bytes) {
ClassNode cn = new ClassNode();
new ClassReader(bytes).accept(new ClassRemapper(cn, new DevEnvRemapper(owner)), ClassReader.EXPAND_FRAMES);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cn.accept(cw);
return cw.toByteArray();
}
private final String owner;
private final SimpleRemapper remapper = new SimpleRemapper(new HashMap<>()) {
@Override
public String map(String key) {
return FabricLoader.getInstance().getMappingResolver().unmapClassName("intermediary", Type.getType("L" + key + ";").getClassName()).replace(".", "/");
}
};
public DevEnvRemapper(String owner) {
super(new HashMap<>());
this.owner = owner;
}
@Override
public String mapMethodName(String owner, String name, String desc) {
// Method desc should be unmapped in the development environment.
desc = this.remapper.mapDesc(desc);
String s = this.isFakeOwner(owner) ? FabricLoader.getInstance().getMappingResolver().mapMethodName("intermediary", this.owner, name, desc) : name;
return s == null ? name : s;
}
private boolean isFakeOwner(String owner) {
return remappedClasses.get(this.owner).getKey().contains(owner.replace("/", "."));
}
}
| 0 | 0.917031 | 1 | 0.917031 | game-dev | MEDIA | 0.920624 | game-dev | 0.968184 | 1 | 0.968184 |
ProjectEQ/projecteqquests | 4,151 | freporte/Miocaei_Herlsas.lua | function event_say(e)
local level = e.other:GetLevel();
local qglobals = eq.get_qglobals(e.other);
if(level >= 15) then
if(e.message:findi("hail")) then
e.self:Say("Come to find out about the Wayfarers Brotherhood, hm? I think I saw you around here long ago. Because you are familiar to me, I will trust you with some [".. eq.say_link("information",false,"information") .. "].");
elseif(e.message:findi("information")) then
e.self:Say("The Wayfarers Brotherhood is pretty particular about who they do business with. You will need to prove yourself to them. You can start gaining their gratitude by helping them. The Wayfarers Brotherhood will ask you to answer some questions when you first meet with them. They tend to call all of their assignments 'adventures.' You'd do well to keep that in mind as they'll be more likely to give you some tasks. There is other information that makes them easier to [" .. eq.say_link("deal with",false,"deal with") .. "] too.");
elseif(e.message:findi("deal with")) then
e.self:Say("There are several camps of Wayfarers Brotherhood explorers around the world. In each camp you'll find a trusted Wayfarers Brotherhood member that has the task of recruiting adventurers that will take on interesting, and potentially lethal, [" .. eq.say_link("work",false,"work") .. "]. Some members will tell you stories, if they think you are worthy of learning such prized information. Others will share their treasures with you, but only if you do work for them.");
elseif(e.message:findi("work")) then
e.self:Say("The Wayfarers Brotherhood believes in giving something for something. For each adventure you take from them, they will add you to their Favor Journal. With the points of Favor that their record keepers have counted for you, you can trade your good Favor for wonderful treasures and goods. Also, the more adventures you do for the Wayfarers Brotherhood, the more your Favor increases. The harder jobs get you more Favor, by the way. As you gain more Favor, the Wayfarers Brotherhood treasure keepers will let you peek at some of their more unique and sought after items. So, it pays to get in good with them, you see! And there's [" .. eq.say_link("more",false,"more") .. "]!");
elseif(e.message:findi("more")) then
e.self:Say("You should also know that there are five magi in the Wayfarers Brotherhood that have found very unique magic stones in the world that they are able to use to transport adventurers to one another. They have placed a magus with one of these stones at each large camp. They call it Farstone Magic. And that's not the only [" .. eq.say_link("interesting ore",false,"interesting ore") .. "] we've seen lately.");
elseif(e.message:findi("interesting ore")) then
e.self:Say("We've found some strange items off the dead in the dungeons. At first we just thought they were simple things -- rocks, pebbles, gems, and the like -- and then we noticed they had very unusual auras about them. Well, one day, Morden Rasp was toying with one -- a shiny green shard -- and he went to scrape it with his dagger. Suddenly, the shard began to reform and fused with his dagger. While the dagger remained as fine as ever, Morden himself felt a surge of strength! So, you will want to watch out for these strange magic pieces in the world. Now, I suggest you go talk to Selephra Giztral, Barstre Songweaver, Vual Stoutest, Teria Grinntli, or Ruanya Windleaf. They handle all of those who are interested in working for the Wayfarers Brotherhood and getting rewards. Remember well what I've told you!");
if(qglobals.Wayfarer == nil) then
e.other:Message(MT.Yellow,"You have completed a step toward becoming a great adventurer. Well done!");
eq.set_global("Wayfarer","1",5,"F");
end
end
else
e.self:Say("You show a great deal of courage in coming here to speak with me at such a young age. I'm afraid you are not yet ready to pursue work with the Wayfarers Brotherhood.Come back when you have more experience and we will talk again.");
end
end
function event_trade(e)
local item_lib = require("items");
item_lib.return_items(e.self, e.other, e.trade)
end
| 0 | 0.679733 | 1 | 0.679733 | game-dev | MEDIA | 0.916284 | game-dev | 0.608139 | 1 | 0.608139 |
magefree/mage | 1,188 | Mage.Sets/src/mage/cards/e/EngineRat.java | package mage.cards.e;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.LoseLifeOpponentsEffect;
import mage.abilities.keyword.DeathtouchAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class EngineRat extends CardImpl {
public EngineRat(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}");
this.subtype.add(SubType.ZOMBIE);
this.subtype.add(SubType.RAT);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// Deathtouch
this.addAbility(DeathtouchAbility.getInstance());
// {5}{B}: Each opponent loses 2 life.
this.addAbility(new SimpleActivatedAbility(new LoseLifeOpponentsEffect(2), new ManaCostsImpl<>("{5}{B}")));
}
private EngineRat(final EngineRat card) {
super(card);
}
@Override
public EngineRat copy() {
return new EngineRat(this);
}
}
| 0 | 0.960122 | 1 | 0.960122 | game-dev | MEDIA | 0.980163 | game-dev | 0.983929 | 1 | 0.983929 |
ms-iot/ros_msft_mrtk | 8,495 | SampleProject/Assets/MixedRealityToolkit/Providers/UnityInput/UnityTouchController.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input.UnityInput
{
[MixedRealityController(
SupportedControllerType.TouchScreen,
new[] { Handedness.Any })]
public class UnityTouchController : BaseController
{
public UnityTouchController(TrackingState trackingState, Handedness controllerHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null)
: base(trackingState, controllerHandedness, inputSource, interactions)
{
}
/// <summary>
/// Time in seconds to determine if the contact registers as a tap or a hold
/// </summary>
public float MaxTapContactTime { get; set; } = 0.5f;
/// <summary>
/// The threshold a finger must move before starting a manipulation gesture.
/// </summary>
public float ManipulationThreshold { get; set; } = 5f;
/// <summary>
/// Current Touch Data for the Controller.
/// </summary>
public Touch TouchData { get; internal set; }
/// <summary>
/// Current Screen point ray for the Touch.
/// </summary>
public Ray ScreenPointRay { get; internal set; }
/// <summary>
/// The current lifetime of the Touch.
/// </summary>
public float Lifetime { get; private set; } = 0.0f;
/// <inheritdoc />
public override MixedRealityInteractionMapping[] DefaultInteractions { get; } =
{
new MixedRealityInteractionMapping(0, "Touch Pointer Delta", AxisType.DualAxis, DeviceInputType.PointerPosition),
new MixedRealityInteractionMapping(1, "Touch Pointer Position", AxisType.SixDof, DeviceInputType.SpatialPointer),
new MixedRealityInteractionMapping(2, "Touch Press", AxisType.Digital, DeviceInputType.PointerClick),
};
private bool isTouched;
private MixedRealityInputAction holdingAction;
private bool isHolding;
private MixedRealityInputAction manipulationAction;
private bool isManipulating;
private MixedRealityPose lastPose = MixedRealityPose.ZeroIdentity;
/// <inheritdoc />
public override void SetupDefaultInteractions(Handedness controllerHandedness)
{
AssignControllerMappings(DefaultInteractions);
if (CoreServices.InputSystem?.InputSystemProfile.GesturesProfile != null)
{
var gestures = CoreServices.InputSystem.InputSystemProfile.GesturesProfile.Gestures;
for (int i = 0; i < gestures.Length; i++)
{
var gesture = gestures[i];
switch (gesture.GestureType)
{
case GestureInputType.Hold:
holdingAction = gesture.Action;
break;
case GestureInputType.Manipulation:
manipulationAction = gesture.Action;
break;
}
}
}
}
private bool isNewController = false;
/// <summary>
/// Start the touch.
/// </summary>
public void StartTouch()
{
// Indicate that this is a new controller.
isNewController = true;
}
/// <summary>
/// Update the touch data.
/// </summary>
public void Update()
{
var inputSystem = CoreServices.InputSystem;
if (inputSystem == null)
{
return;
}
if (isNewController)
{
isNewController = false;
inputSystem.RaiseOnInputDown(InputSource, Handedness.None, Interactions[2].MixedRealityInputAction);
inputSystem.RaisePointerDown(InputSource.Pointers[0], Interactions[2].MixedRealityInputAction);
isTouched = true;
inputSystem.RaiseGestureStarted(this, holdingAction);
isHolding = true;
}
if (!isTouched) { return; }
Lifetime += Time.deltaTime;
if (TouchData.phase == TouchPhase.Moved)
{
Interactions[0].Vector2Data = TouchData.deltaPosition;
if (Interactions[0].Changed)
{
inputSystem.RaisePositionInputChanged(InputSource, ControllerHandedness, Interactions[0].MixedRealityInputAction, TouchData.deltaPosition);
}
lastPose.Position = InputSource.Pointers[0].Position;
lastPose.Rotation = InputSource.Pointers[0].Rotation;
inputSystem.RaiseSourcePoseChanged(InputSource, this, lastPose);
Interactions[1].PoseData = lastPose;
if (Interactions[1].Changed)
{
inputSystem.RaisePoseInputChanged(InputSource, ControllerHandedness, Interactions[1].MixedRealityInputAction, lastPose);
}
if (!isManipulating)
{
if (Mathf.Abs(TouchData.deltaPosition.x) > ManipulationThreshold ||
Mathf.Abs(TouchData.deltaPosition.y) > ManipulationThreshold)
{
inputSystem?.RaiseGestureCanceled(this, holdingAction);
isHolding = false;
inputSystem?.RaiseGestureStarted(this, manipulationAction);
isManipulating = true;
}
}
else
{
inputSystem.RaiseGestureUpdated(this, manipulationAction, TouchData.deltaPosition);
}
// Send dragged event, to inform manipulation handlers.
inputSystem.RaisePointerDragged(InputSource.Pointers[0], Interactions[1].MixedRealityInputAction);
}
}
/// <summary>
/// End the touch.
/// </summary>
public void EndTouch()
{
var inputSystem = CoreServices.InputSystem;
if (inputSystem == null)
{
return;
}
if (TouchData.phase == TouchPhase.Ended)
{
if (Lifetime < MaxTapContactTime)
{
if (isHolding)
{
inputSystem.RaiseGestureCanceled(this, holdingAction);
isHolding = false;
}
if (isManipulating)
{
inputSystem.RaiseGestureCanceled(this, manipulationAction);
isManipulating = false;
}
inputSystem.RaisePointerClicked(InputSource.Pointers[0], Interactions[2].MixedRealityInputAction, TouchData.tapCount);
}
if (isHolding)
{
inputSystem.RaiseGestureCompleted(this, holdingAction);
isHolding = false;
}
if (isManipulating)
{
inputSystem.RaiseGestureCompleted(this, manipulationAction, TouchData.deltaPosition);
isManipulating = false;
}
}
if (isHolding)
{
inputSystem.RaiseGestureCompleted(this, holdingAction);
isHolding = false;
}
Debug.Assert(!isHolding);
if (isManipulating)
{
inputSystem.RaiseGestureCompleted(this, manipulationAction, TouchData.deltaPosition);
isManipulating = false;
}
Debug.Assert(!isManipulating);
inputSystem.RaiseOnInputUp(InputSource, Handedness.None, Interactions[2].MixedRealityInputAction);
inputSystem.RaisePointerUp(InputSource.Pointers[0], Interactions[2].MixedRealityInputAction);
Lifetime = 0.0f;
isTouched = false;
Interactions[1].PoseData = MixedRealityPose.ZeroIdentity;
Interactions[0].Vector2Data = Vector2.zero;
}
}
} | 0 | 0.945139 | 1 | 0.945139 | game-dev | MEDIA | 0.546263 | game-dev | 0.954527 | 1 | 0.954527 |
RyleiC/MagickaForgeV2 | 21,256 | Source/MagickaForge/Components/Animations/AnimationAction.cs | using MagickaForge.Components.Common;
using MagickaForge.Utils.Data;
using MagickaForge.Utils.Data.Abilities;
using MagickaForge.Utils.Data.Animations;
using System.Text.Json.Serialization;
namespace MagickaForge.Components.Animations
{
[JsonPolymorphic(TypeDiscriminatorPropertyName = "_ActionType")]
[JsonDerivedType(typeof(Block), typeDiscriminator: "Block")]
[JsonDerivedType(typeof(BreakFree), typeDiscriminator: "BreakFree")]
[JsonDerivedType(typeof(CameraShake), typeDiscriminator: "CameraShake")]
[JsonDerivedType(typeof(CastSpellEvent), typeDiscriminator: "CastSpell")]
[JsonDerivedType(typeof(Crouch), typeDiscriminator: "Crouch")]
[JsonDerivedType(typeof(DamageGrip), typeDiscriminator: "DamageGrip")]
[JsonDerivedType(typeof(DealDamage), typeDiscriminator: "DealDamage")]
[JsonDerivedType(typeof(DetachItem), typeDiscriminator: "DetachItem")]
[JsonDerivedType(typeof(Ethereal), typeDiscriminator: "Ethereal")]
[JsonDerivedType(typeof(Footstep), typeDiscriminator: "Footstep")]
[JsonDerivedType(typeof(Grip), typeDiscriminator: "Grip")]
[JsonDerivedType(typeof(Gunfire), typeDiscriminator: "Gunfire")]
[JsonDerivedType(typeof(Immortal), typeDiscriminator: "Immortal")]
[JsonDerivedType(typeof(Invisible), typeDiscriminator: "Invisible")]
[JsonDerivedType(typeof(Jump), typeDiscriminator: "Jump")]
[JsonDerivedType(typeof(Move), typeDiscriminator: "Move")]
[JsonDerivedType(typeof(OverkillGrip), typeDiscriminator: "OverkillGrip")]
[JsonDerivedType(typeof(PlayEffect), typeDiscriminator: "PlayEffect")]
[JsonDerivedType(typeof(PlaySound), typeDiscriminator: "PlaySound")]
[JsonDerivedType(typeof(ReleaseGrip), typeDiscriminator: "ReleaseGrip")]
[JsonDerivedType(typeof(RemoveStatus), typeDiscriminator: "RemoveStatus")]
[JsonDerivedType(typeof(SetItemAttach), typeDiscriminator: "SetItemAttach")]
[JsonDerivedType(typeof(SpawnMissile), typeDiscriminator: "SpawnMissile")]
[JsonDerivedType(typeof(SpecialAbilityAction), typeDiscriminator: "SpecialAbility")]
[JsonDerivedType(typeof(Suicide), typeDiscriminator: "Suicide")]
[JsonDerivedType(typeof(ThrowGrip), typeDiscriminator: "ThrowGrip")]
[JsonDerivedType(typeof(Tongue), typeDiscriminator: "Tongue")]
[JsonDerivedType(typeof(WeaponVisibility), typeDiscriminator: "WeaponVisibility")]
public class AnimationAction
{
protected ActionType _type;
public float ActionStart { get; set; }
public float ActionEnd { get; set; }
public virtual void Write(BinaryWriter bw)
{
bw.Write(_type.ToString());
bw.Write(ActionStart);
bw.Write(ActionEnd);
}
public static AnimationAction GetAction(ActionType aType, BinaryReader br)
{
AnimationAction action;
float start = br.ReadSingle();
float end = br.ReadSingle();
if (aType == ActionType.Block)
{
action = new Block() { WeaponSlot = br.ReadInt32() };
}
else if (aType == ActionType.BreakFree)
{
action = new BreakFree() { Magnitude = br.ReadSingle(), WeaponSlot = br.ReadInt32() };
}
else if (aType == ActionType.CameraShake)
{
br.ReadString();
action = new CameraShake() { Duration = br.ReadSingle(), Magnitude = br.ReadSingle() };
}
else if (aType == ActionType.CastSpell)
{
action = new CastSpellEvent() { FromStaff = br.ReadBoolean() };
if (!(action as CastSpellEvent)!.FromStaff)
{
(action as CastSpellEvent)!.Bone = br.ReadString();
}
}
else if (aType == ActionType.Crouch)
{
action = new Crouch() { Radius = br.ReadSingle(), Length = br.ReadSingle() };
}
else if (aType == ActionType.DamageGrip)
{
bool dmgOwner = br.ReadBoolean();
Damage[] damage = new Damage[br.ReadInt32()];
for (int i = 0; i < damage.Length; i++)
{
damage[i].AttackProperty = (AttackProperties)br.ReadInt32();
damage[i].Element = (Elements)br.ReadInt32();
damage[i].Amount = br.ReadSingle();
damage[i].Magnitude = br.ReadSingle();
}
action = new DamageGrip() { DamageOwner = dmgOwner, Damages = damage };
}
else if (aType == ActionType.DealDamage)
{
action = new DealDamage() { WeaponSlot = br.ReadInt32(), Target = (Targets)br.ReadByte() };
}
else if (aType == ActionType.DetachItem)
{
action = new DetachItem { WeaponSlot = br.ReadInt32(), Velocity = new Vector3(br) };
}
else if (aType == ActionType.Ethereal)
{
action = new Ethereal() { IsEthereal = br.ReadBoolean(), EtherealAlpha = br.ReadSingle(), EtherealSpeed = br.ReadSingle() };
}
else if (aType == ActionType.Footstep)
{
action = new Footstep();
}
else if (aType == ActionType.Grip)
{
action = new Grip() { GripType = (GripType)br.ReadByte(), Radius = br.ReadSingle(), BreakFreeTolerance = br.ReadSingle(), BoneA = br.ReadString(), BoneB = br.ReadString(), FinishOnGrip = br.ReadBoolean() };
}
else if (aType == ActionType.Gunfire)
{
action = new Gunfire() { WeaponSlot = br.ReadInt32(), Accuracy = br.ReadSingle() };
}
else if (aType == ActionType.Immortal)
{
action = new Immortal() { Collide = br.ReadBoolean() };
}
else if (aType == ActionType.Invisible)
{
action = new Invisible() { Shimmer = br.ReadBoolean() };
}
else if (aType == ActionType.Jump)
{
float elevation = br.ReadSingle();
float minRange = 0;
float maxRange = 0;
if (br.ReadBoolean())
{
minRange = br.ReadSingle();
}
if (br.ReadBoolean())
{
maxRange = br.ReadSingle();
}
action = new Jump() { Elevation = elevation, MinRange = minRange, MaxRange = maxRange };
}
else if (aType == ActionType.Move)
{
action = new Move() { Velocity = new Vector3(br) };
}
else if (aType == ActionType.OverkillGrip)
{
action = new OverkillGrip();
}
else if (aType == ActionType.PlayEffect)
{
action = new PlayEffect() { Bone = br.ReadString(), Attached = br.ReadBoolean(), Effect = br.ReadString(), Value = br.ReadSingle() };
}
else if (aType == ActionType.PlaySound)
{
action = new PlaySound() { Cue = br.ReadString(), Bank = (Banks)br.ReadInt32() };
}
else if (aType == ActionType.ReleaseGrip)
{
action = new ReleaseGrip();
}
else if (aType == ActionType.RemoveStatus)
{
action = new RemoveStatus() { Status = br.ReadString() };
}
else if (aType == ActionType.SetItemAttach)
{
action = new SetItemAttach() { ItemSlot = br.ReadInt32(), Bone = br.ReadString() };
}
else if (aType == ActionType.SpawnMissile)
{
action = new SpawnMissile() { WeaponSlot = br.ReadInt32(), Velocity = new Vector3(br), Aligned = br.ReadBoolean() };
}
else if (aType == ActionType.SpecialAbility)
{
SpecialAbility spec = new();
int weaponSlot = br.ReadInt32();
if (weaponSlot < 0)
{
spec.Type = br.ReadString();
spec.Animation = br.ReadString();
spec.Hash = br.ReadString();
spec.Elements = new Elements[br.ReadInt32()];
for (int i = 0; i < spec.Elements.Length; i++)
{
spec.Elements[i] = (Elements)br.ReadInt32();
}
}
action = new SpecialAbilityAction() { WeaponSlot = weaponSlot, SpecialAbilityInstance = spec };
}
else if (aType == ActionType.Suicide)
{
action = new Suicide() { Overkill = br.ReadBoolean() };
}
else if (aType == ActionType.ThrowGrip)
{
action = new ThrowGrip();
}
else if (aType == ActionType.Tongue)
{
action = new Tongue() { MaxLength = br.ReadSingle() };
}
else if (aType == ActionType.WeaponVisibility)
{
action = new WeaponVisibility() { WeaponSlot = br.ReadInt32(), Visible = br.ReadBoolean() };
}
else
{
throw new Exception(aType.ToString());
}
action.ActionStart = start;
action.ActionEnd = end;
return action;
}
}
public class Block : AnimationAction
{
public int WeaponSlot { get; set; }
public Block()
{
_type = ActionType.Block;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
}
}
public class BreakFree : AnimationAction
{
public float Magnitude { get; set; }
public int WeaponSlot { get; set; }
public BreakFree()
{
_type = ActionType.BreakFree;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Magnitude);
bw.Write(WeaponSlot);
}
}
public class CameraShake : AnimationAction
{
public float Duration { get; set; }
public float Magnitude { get; set; }
public CameraShake()
{
_type = ActionType.CameraShake;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(string.Empty);
bw.Write(Duration);
bw.Write(Magnitude);
}
}
public class CastSpellEvent : AnimationAction
{
public bool FromStaff { get; set; }
public string Bone { get; set; }
public CastSpellEvent()
{
_type = ActionType.CastSpell;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(FromStaff);
if (!FromStaff)
{
bw.Write(Bone!);
}
}
}
public class Crouch : AnimationAction
{
public float Radius { get; set; }
public float Length { get; set; }
public Crouch()
{
_type = ActionType.Crouch;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Radius);
bw.Write(Length);
}
}
public class DamageGrip : AnimationAction
{
public bool DamageOwner { get; set; }
public Damage[] Damages { get; set; }
public DamageGrip()
{
_type = ActionType.DamageGrip;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(DamageOwner);
bw.Write(Damages!.Length);
foreach (Damage damage in Damages)
{
bw.Write((int)damage.AttackProperty);
bw.Write((int)damage.Element);
bw.Write(damage.Amount);
bw.Write(damage.Magnitude);
}
}
}
public class DealDamage : AnimationAction
{
public int WeaponSlot { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter<Targets>))]
public Targets Target { get; set; }
public DealDamage()
{
_type = ActionType.DealDamage;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
bw.Write((byte)Target);
}
}
public class DetachItem : AnimationAction
{
public int WeaponSlot { get; set; }
public Vector3 Velocity { get; set; }
public DetachItem()
{
_type = ActionType.DetachItem;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
Velocity.Write(bw);
}
}
public class Ethereal : AnimationAction
{
public bool IsEthereal { get; set; }
public float EtherealAlpha { get; set; }
public float EtherealSpeed { get; set; }
public Ethereal()
{
_type = ActionType.Ethereal;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(IsEthereal);
bw.Write(EtherealAlpha);
bw.Write(EtherealSpeed);
}
}
public class Footstep : AnimationAction
{
public Footstep()
{
_type = ActionType.Footstep;
}
}
public class Grip : AnimationAction
{
[JsonConverter(typeof(JsonStringEnumConverter<GripType>))]
public GripType GripType { get; set; }
public float Radius { get; set; }
public float BreakFreeTolerance { get; set; }
public string BoneA { get; set; }
public string BoneB { get; set; }
public bool FinishOnGrip { get; set; }
public Grip()
{
_type = ActionType.Grip;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write((byte)GripType);
bw.Write(Radius);
bw.Write(BreakFreeTolerance);
bw.Write(BoneA!);
bw.Write(BoneB!);
bw.Write(FinishOnGrip);
}
}
public class Gunfire : AnimationAction
{
public int WeaponSlot { get; set; }
public float Accuracy { get; set; }
public Gunfire()
{
_type = ActionType.Gunfire;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
bw.Write(Accuracy);
}
}
public class Immortal : AnimationAction
{
public bool Collide { get; set; }
public Immortal()
{
_type = ActionType.Immortal;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Collide);
}
}
public class Invisible : AnimationAction
{
public bool Shimmer { get; set; }
public Invisible()
{
_type = ActionType.Invisible;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Shimmer);
}
}
public class Jump : AnimationAction
{
public float Elevation { get; set; }
public float MinRange { get; set; }
public float MaxRange { get; set; }
public Jump()
{
_type = ActionType.Jump;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Elevation);
bool hasMin = MinRange != 0;
bool hasMax = MaxRange != 0;
bw.Write(hasMin);
if (hasMin)
{
bw.Write(MinRange);
}
bw.Write(hasMax);
if (hasMax)
{
bw.Write(MaxRange);
}
}
}
public class Move : AnimationAction
{
public Vector3 Velocity { get; set; }
public Move()
{
_type = ActionType.Move;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
Velocity.Write(bw);
}
}
public class OverkillGrip : AnimationAction
{
public OverkillGrip()
{
_type = ActionType.OverkillGrip;
}
}
public class PlayEffect : AnimationAction
{
public string Bone { get; set; }
public bool Attached { get; set; }
public string Effect { get; set; }
public float Value { get; set; }
public PlayEffect()
{
_type = ActionType.PlayEffect;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Bone!);
bw.Write(Attached);
bw.Write(Effect!);
bw.Write(Value);
}
}
public class PlaySound : AnimationAction
{
public string Cue { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter<Banks>))]
public Banks Bank { get; set; }
public PlaySound()
{
_type = ActionType.PlaySound;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Cue!);
bw.Write((int)Bank);
}
}
public class ReleaseGrip : AnimationAction
{
public ReleaseGrip()
{
_type = ActionType.ReleaseGrip;
}
}
public class RemoveStatus : AnimationAction
{
public string Status { get; set; }
public RemoveStatus()
{
_type = ActionType.RemoveStatus;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Status!);
}
}
public class SetItemAttach : AnimationAction
{
public int ItemSlot { get; set; }
public string Bone { get; set; }
public SetItemAttach()
{
_type = ActionType.SetItemAttach;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(ItemSlot);
bw.Write(Bone);
}
}
public class SpawnMissile : AnimationAction
{
public int WeaponSlot { get; set; }
public Vector3 Velocity { get; set; }
public bool Aligned { get; set; }
public SpawnMissile()
{
_type = ActionType.SpawnMissile;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
Velocity.Write(bw);
bw.Write(Aligned);
}
}
public class SpecialAbilityAction : AnimationAction
{
public int WeaponSlot { get; set; }
public SpecialAbility SpecialAbilityInstance { get; set; }
public SpecialAbilityAction()
{
_type = ActionType.SpecialAbility;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
if (WeaponSlot < 0)
{
bw.Write(SpecialAbilityInstance!.Type!);
bw.Write(SpecialAbilityInstance.Animation!);
bw.Write(SpecialAbilityInstance.Hash!);
bw.Write(SpecialAbilityInstance.Elements!.Length);
for (int i = 0; i < SpecialAbilityInstance.Elements.Length; i++)
{
bw.Write((int)SpecialAbilityInstance.Elements[i]);
}
}
}
}
public class Suicide : AnimationAction
{
public bool Overkill { get; set; }
public Suicide()
{
_type = ActionType.Suicide;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(Overkill);
}
}
public class ThrowGrip : AnimationAction
{
public ThrowGrip()
{
_type = ActionType.ThrowGrip;
}
}
public class Tongue : AnimationAction
{
public float MaxLength { get; set; }
public Tongue()
{
_type = ActionType.Tongue;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(MaxLength);
}
}
public class WeaponVisibility : AnimationAction
{
public int WeaponSlot { get; set; }
public bool Visible { get; set; }
public WeaponVisibility()
{
_type = ActionType.WeaponVisibility;
}
public override void Write(BinaryWriter bw)
{
base.Write(bw);
bw.Write(WeaponSlot);
bw.Write(Visible);
}
}
} | 0 | 0.934482 | 1 | 0.934482 | game-dev | MEDIA | 0.943104 | game-dev | 0.979909 | 1 | 0.979909 |
lllyasviel/YGOProUnity_V2 | 1,576 | Assets/ArtSystem/arrow/ArrowCtrl/LoopPathAnim.cs |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LoopPathAnim : MonoBehaviour
{
// public GameObject m_kStartObject = null;
// public GameObject m_kEndObject = null;
private MegaShapeArc m_kShapeArc = null;
public List<MegaWorldPathDeform> m_kMWPD_List =
new List<MegaWorldPathDeform>();
public float m_fOffsetValueStep = 1.0f;
void Start ()
{
m_kShapeArc = GetComponent<MegaShapeArc> ();
// m_kStartObject.transform.position = m_kShapeArc.splines [0].knots [0].p;
// m_kEndObject.transform.position =
// m_kShapeArc.splines [0].knots[ m_kShapeArc.splines [0].knots.Count-1 ].p;
foreach(MegaWorldPathDeform iter in m_kMWPD_List)
{
if( iter.GetComponent<AnimUnit>() )
{
iter.GetComponent<AnimUnit>().setMegaShape(m_kShapeArc);
//Debug.Log("set shaps...");
}
}
}
void Update ()
{
}
void LateUpdate()
{
// m_kShapeArc.splines [0].knots [0].p = m_kStartObject.transform.position;
//
// m_kShapeArc.splines [0].knots [m_kShapeArc.splines [0].knots.Count - 1].p =
// m_kEndObject.transform.position;
}
//得到曲线路径长度 --CardGame
public float getShapeLen()
{
return m_kShapeArc.GetCurveLength(0);
}
//添加到箭头组成尾部 --CardGame
public void moveToTail(MegaWorldPathDeform mwpd)
{
if( m_kMWPD_List.Contains(mwpd) )
{
float val =
m_kMWPD_List[m_kMWPD_List.Count-1].
GetComponent<AnimUnit>().getAccumOffset() + m_fOffsetValueStep;
mwpd.GetComponent<AnimUnit>().setAccumOffset(val);
m_kMWPD_List.Remove(mwpd);
m_kMWPD_List.Add(mwpd);
}
}
}
| 0 | 0.75235 | 1 | 0.75235 | game-dev | MEDIA | 0.863518 | game-dev | 0.923845 | 1 | 0.923845 |
506638093/spine-optimize | 6,732 | spine-csharp/src/IkConstraint.cs | /******************************************************************************
* Spine Runtimes Software License
* Version 2.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software (typically granted by licensing Spine), you
* may not (a) modify, translate, adapt or otherwise create derivative works,
* improvements of the Software or develop new applications using the Software
* or (b) remove, delete, alter or obscure any trademarks or any copyright,
* trademark, patent or other intellectual property or proprietary rights
* notices on or in the Software, including any copy thereof. Redistributions
* in binary or source form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
namespace Spine {
public class IkConstraint {
private const float radDeg = 180 / (float)Math.PI;
internal IkConstraintData data;
internal List<Bone> bones = new List<Bone>();
internal Bone target;
internal int bendDirection;
internal float mix;
public IkConstraintData Data { get { return data; } }
public List<Bone> Bones { get { return bones; } }
public Bone Target { get { return target; } set { target = value; } }
public int BendDirection { get { return bendDirection; } set { bendDirection = value; } }
public float Mix { get { return mix; } set { mix = value; } }
public IkConstraint (IkConstraintData data, Skeleton skeleton) {
if (data == null) throw new ArgumentNullException("data cannot be null.");
if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
this.data = data;
mix = data.mix;
bendDirection = data.bendDirection;
bones = new List<Bone>(data.bones.Count);
foreach (BoneData boneData in data.bones)
bones.Add(skeleton.FindBone(boneData.name));
target = skeleton.FindBone(data.target.name);
}
public void apply () {
Bone target = this.target;
List<Bone> bones = this.bones;
switch (bones.Count) {
case 1:
apply(bones[0], target.worldX, target.worldY, mix);
break;
case 2:
apply(bones[0], bones[1], target.worldX, target.worldY, bendDirection, mix);
break;
}
}
override public String ToString () {
return data.name;
}
/// <summary>Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified
/// in the world coordinate system.</summary>
static public void apply (Bone bone, float targetX, float targetY, float alpha) {
float parentRotation = (!bone.data.inheritRotation || bone.parent == null) ? 0 : bone.parent.worldRotation;
float rotation = bone.rotation;
float rotationIK = (float)Math.Atan2(targetY - bone.worldY, targetX - bone.worldX) * radDeg;
if (bone.worldFlipX != (bone.worldFlipY != Bone.yDown)) rotationIK = -rotationIK;
rotationIK -= parentRotation;
bone.rotationIK = rotation + (rotationIK - rotation) * alpha;
}
/// <summary>Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as
/// possible. The target is specified in the world coordinate system.</summary>
/// <param name="child">Any descendant bone of the parent.</param>
static public void apply (Bone parent, Bone child, float targetX, float targetY, int bendDirection, float alpha) {
float childRotation = child.rotation, parentRotation = parent.rotation;
if (alpha == 0) {
child.rotationIK = childRotation;
parent.rotationIK = parentRotation;
return;
}
float positionX, positionY;
Bone parentParent = parent.parent;
if (parentParent != null) {
parentParent.worldToLocal(targetX, targetY, out positionX, out positionY);
targetX = (positionX - parent.x) * parentParent.worldScaleX;
targetY = (positionY - parent.y) * parentParent.worldScaleY;
} else {
targetX -= parent.x;
targetY -= parent.y;
}
if (child.parent == parent) {
positionX = child.x;
positionY = child.y;
} else {
child.parent.localToWorld(child.x, child.y, out positionX, out positionY);
parent.worldToLocal(positionX, positionY, out positionX, out positionY);
}
float childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY;
float offset = (float)Math.Atan2(childY, childX);
float len1 = (float)Math.Sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX;
// Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/
float cosDenom = 2 * len1 * len2;
if (cosDenom < 0.0001f) {
child.rotationIK = childRotation + ((float)Math.Atan2(targetY, targetX) * radDeg - parentRotation - childRotation)
* alpha;
return;
}
float cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom;
if (cos < -1)
cos = -1;
else if (cos > 1)
cos = 1;
float childAngle = (float)Math.Acos(cos) * bendDirection;
float adjacent = len1 + len2 * cos, opposite = len2 * (float)Math.Sin(childAngle);
float parentAngle = (float)Math.Atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite);
float rotation = (parentAngle - offset) * radDeg - parentRotation;
if (rotation > 180)
rotation -= 360;
else if (rotation < -180) //
rotation += 360;
parent.rotationIK = parentRotation + rotation * alpha;
rotation = (childAngle + offset) * radDeg - childRotation;
if (rotation > 180)
rotation -= 360;
else if (rotation < -180) //
rotation += 360;
child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha;
}
}
}
| 0 | 0.896178 | 1 | 0.896178 | game-dev | MEDIA | 0.924997 | game-dev | 0.976964 | 1 | 0.976964 |
3arthqu4ke/phobot | 2,949 | src/main/java/me/earth/phobot/modules/client/GraphDebugRenderer.java | package me.earth.phobot.modules.client;
import lombok.RequiredArgsConstructor;
import me.earth.phobot.event.RenderEvent;
import me.earth.phobot.pathfinder.mesh.MeshNode;
import me.earth.phobot.pathfinder.mesh.NavigationMeshManager;
import me.earth.phobot.util.render.Renderer;
import me.earth.pingbypass.api.event.listeners.generic.Listener;
import net.minecraft.client.Minecraft;
import java.awt.*;
import java.util.Set;
@RequiredArgsConstructor
public class GraphDebugRenderer extends Listener<RenderEvent> {
private final NavigationMeshManager navigationMeshManager;
private final Pathfinding module;
private final Minecraft mc;
@Override
public void onEvent(RenderEvent event) {
if (module.getRender().getValue()) {
assert mc.player != null;
for (int x = (int) (mc.player.getX() - 10); x <= mc.player.getX() + 10; x++) {
for (int z = (int) (mc.player.getZ() - 10); z <= mc.player.getZ() + 10; z++) {
Set<MeshNode> nodes = navigationMeshManager.getXZMap().get(x, z);
if (nodes != null) {
for (MeshNode node : nodes) {
if (node.isValid() && node.distanceSq(mc.player.position()) <= 100) {
for (int i = 0; i < MeshNode.OFFSETS.length; i++) {
double xOff = MeshNode.OFFSETS[i].getX();
double zOff = MeshNode.OFFSETS[i].getZ();
MeshNode adjacent = node.getAdjacent()[i];
Color color = Color.GREEN;
if (adjacent == null) {
continue;
} else if (!adjacent.isValid()) {
color = Color.RED;
}
// TODO: maybe make line point somewhere?
event.getLineColor().set(color);
event.getAabb().set(
node.getX() + 0.5 + xOff / 3.9,
node.getY(),
node.getZ() + 0.5 + zOff / 3.9,
node.getX() + 0.5 + xOff / 3.9 + 0.01,
node.getY(),
node.getZ() + 0.5 + zOff / 3.9 + 0.01
);
Renderer.startLines(1.5f, true);
Renderer.drawAABBOutline(event);
Renderer.end(true);
}
}
}
}
}
}
}
}
}
| 0 | 0.874723 | 1 | 0.874723 | game-dev | MEDIA | 0.918873 | game-dev | 0.938781 | 1 | 0.938781 |
warycat/rustgym | 3,214 | leetcode/src/d2/_289_game_of_life.rs | struct Solution;
#[derive(Copy, Clone)]
enum State {
Dead = 0,
Live = 1,
LiveToDead = 2,
DeadToLive = 3,
LiveToLive = 4,
DeadToDead = 5,
Unknown = 6,
}
impl State {
fn from_i32(x: i32) -> State {
match x {
0 => State::Dead,
1 => State::Live,
2 => State::LiveToDead,
3 => State::DeadToLive,
4 => State::LiveToLive,
5 => State::DeadToDead,
_ => State::Unknown,
}
}
fn to_i32(self) -> i32 {
self as i32
}
fn to_live(self) -> i32 {
match self {
State::LiveToDead | State::Live | State::LiveToLive => 1,
_ => 0,
}
}
fn next(self, neighbors: i32) -> State {
match self {
State::Live => match neighbors {
0 | 1 => State::LiveToDead,
2 | 3 => State::LiveToLive,
_ => State::LiveToDead,
},
State::Dead => match neighbors {
3 => State::DeadToLive,
_ => State::DeadToDead,
},
State::LiveToDead => State::Dead,
State::DeadToLive => State::Live,
State::LiveToLive => State::Live,
State::DeadToDead => State::Dead,
State::Unknown => State::Unknown,
}
}
}
impl Solution {
fn game_of_life(board: &mut Vec<Vec<i32>>) {
let n = board.len();
let m = board[0].len();
for i in 0..n {
for j in 0..m {
let mut neighbors = 0;
if i > 0 {
neighbors += State::from_i32(board[i - 1][j]).to_live();
}
if j > 0 {
neighbors += State::from_i32(board[i][j - 1]).to_live();
}
if i + 1 < n {
neighbors += State::from_i32(board[i + 1][j]).to_live();
}
if j + 1 < m {
neighbors += State::from_i32(board[i][j + 1]).to_live();
}
if i > 0 && j > 0 {
neighbors += State::from_i32(board[i - 1][j - 1]).to_live();
}
if i + 1 < n && j > 0 {
neighbors += State::from_i32(board[i + 1][j - 1]).to_live();
}
if i + 1 < n && j + 1 < m {
neighbors += State::from_i32(board[i + 1][j + 1]).to_live();
}
if i > 0 && j + 1 < m {
neighbors += State::from_i32(board[i - 1][j + 1]).to_live();
}
let current: State = State::from_i32(board[i][j]);
board[i][j] = current.next(neighbors).to_i32();
}
}
for i in 0..n {
for j in 0..m {
board[i][j] = State::from_i32(board[i][j]).next(0).to_i32()
}
}
}
}
#[test]
fn test() {
let mut board: Vec<Vec<i32>> = vec_vec_i32![[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]];
let res: Vec<Vec<i32>> = vec_vec_i32![[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]];
Solution::game_of_life(&mut board);
assert_eq!(board, res);
}
| 0 | 0.567162 | 1 | 0.567162 | game-dev | MEDIA | 0.330244 | game-dev | 0.884555 | 1 | 0.884555 |
BattleDawnNZ/ProceduralAnimation | 2,159 | Library/PackageCache/com.unity.cinemachine@2.5.0/Runtime/Components/CinemachineSameAsFollowTarget.cs | using Cinemachine.Utility;
using UnityEngine;
using UnityEngine.Serialization;
namespace Cinemachine
{
/// <summary>
/// This is a CinemachineComponent in the Aim section of the component pipeline.
/// Its job is to match the orientation of the Follow target.
/// </summary>
[DocumentationSorting(DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[SaveDuringPlay]
public class CinemachineSameAsFollowTarget : CinemachineComponentBase
{
/// <summary>
/// How much time it takes for the aim to catch up to the target's rotation
/// </summary>
[Tooltip("How much time it takes for the aim to catch up to the target's rotation")]
[FormerlySerializedAs("m_AngularDamping")]
public float m_Damping = 0;
Quaternion m_PreviousReferenceOrientation = Quaternion.identity;
/// <summary>True if component is enabled and has a Follow target defined</summary>
public override bool IsValid { get { return enabled && FollowTarget != null; } }
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Aim stage</summary>
public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } }
/// <summary>Orients the camera to match the Follow target's orientation</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Not used.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
if (!IsValid)
return;
Quaternion dampedOrientation = FollowTargetRotation;
if (deltaTime >= 0)
{
float t = Damper.Damp(1, m_Damping, deltaTime);
dampedOrientation = Quaternion.Slerp(
m_PreviousReferenceOrientation, FollowTargetRotation, t);
}
m_PreviousReferenceOrientation = dampedOrientation;
curState.RawOrientation = dampedOrientation;
}
}
}
| 0 | 0.843748 | 1 | 0.843748 | game-dev | MEDIA | 0.926555 | game-dev | 0.946834 | 1 | 0.946834 |
runuo/runuo | 2,651 | Scripts/Engines/Quests/Core/Items/QuestItem.cs | using System;
using Server;
using Server.Mobiles;
namespace Server.Engines.Quests
{
public abstract class QuestItem : Item
{
public QuestItem( int itemID ) : base( itemID )
{
}
public QuestItem( Serial serial ) : base( serial )
{
}
public abstract bool CanDrop( PlayerMobile pm );
public virtual bool Accepted { get { return Deleted; } }
public override bool DropToWorld( Mobile from, Point3D p )
{
bool ret = base.DropToWorld( from, p );
if ( ret && !Accepted && Parent != from.Backpack )
{
if ( from.AccessLevel > AccessLevel.Player )
{
return true;
}
else if ( !(from is PlayerMobile) || CanDrop( (PlayerMobile)from ) )
{
return true;
}
else
{
from.SendLocalizedMessage( 1049343 ); // You can only drop quest items into the top-most level of your backpack while you still need them for your quest.
return false;
}
}
else
{
return ret;
}
}
public override bool DropToMobile( Mobile from, Mobile target, Point3D p )
{
bool ret = base.DropToMobile( from, target, p );
if ( ret && !Accepted && Parent != from.Backpack )
{
if ( from.AccessLevel > AccessLevel.Player )
{
return true;
}
else if ( !(from is PlayerMobile) || CanDrop( (PlayerMobile)from ) )
{
return true;
}
else
{
from.SendLocalizedMessage( 1049344 ); // You decide against trading the item. You still need it for your quest.
return false;
}
}
else
{
return ret;
}
}
public override bool DropToItem( Mobile from, Item target, Point3D p )
{
bool ret = base.DropToItem( from, target, p );
if ( ret && !Accepted && Parent != from.Backpack )
{
if ( from.AccessLevel > AccessLevel.Player )
{
return true;
}
else if ( !(from is PlayerMobile) || CanDrop( (PlayerMobile)from ) )
{
return true;
}
else
{
from.SendLocalizedMessage( 1049343 ); // You can only drop quest items into the top-most level of your backpack while you still need them for your quest.
return false;
}
}
else
{
return ret;
}
}
public override DeathMoveResult OnParentDeath( Mobile parent )
{
if ( parent is PlayerMobile && !CanDrop( (PlayerMobile)parent ) )
return DeathMoveResult.MoveToBackpack;
else
return base.OnParentDeath( parent );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 0 | 0.984455 | 1 | 0.984455 | game-dev | MEDIA | 0.949216 | game-dev | 0.981892 | 1 | 0.981892 |
hutian23/ETScript | 9,741 | Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/Box2D/Component/b2BodySystem.cs | using Box2DSharp.Common;
using Box2DSharp.Dynamics;
using ET.Event;
using Vector2 = System.Numerics.Vector2;
namespace ET.Client
{
[FriendOf(typeof(b2Body))]
public static class b2BodySystem
{
public class B2bodyPreStepSystem : PreStepSystem<b2Body>
{
protected override void PreStepUpdate(b2Body self)
{
self.SetAngle(self.angle);
self.SetLinearVelocity(self.velocity);
}
}
public class B2bodyPostStepSystem : PostStepSystem<b2Body>
{
protected override void PosStepUpdate(b2Body self)
{
//1. 渲染层同步逻辑层刚体的位置
self.SyncTrans();
}
}
public class B2bodyFrameLateUpdateSystem : FrameLateUpdateSystem<b2Body>
{
protected override void FrameLateUpdate(b2Body self)
{
//2. 清空当前帧缓冲区
self.triggerEnterBuffers.Clear();
self.triggerStayBuffers.Clear();
self.triggerExitBuffers.Clear();
self.collisionEnterBuffers.Clear();
self.collisionStayBuffers.Clear();
self.collisionExitBuffers.Clear();
}
}
[FriendOf(typeof(b2WorldManager))]
public class b2BodyDestroySystem : DestroySystem<b2Body>
{
protected override void Destroy(b2Body self)
{
b2WorldManager.Instance.DestroyBody(self.body);
self.body = null;
self.unitId = 0;
self.filterSet.Clear();
self.b2BoxDict.Clear();
self.flip = FlipState.Left;
self.angle = 0f;
self.velocity = Vector2.Zero;
self.hertz = 0;
self.triggerEnterBuffers.Clear();
self.triggerStayBuffers.Clear();
self.triggerExitBuffers.Clear();
self.collisionEnterBuffers.Clear();
self.collisionStayBuffers.Clear();
self.collisionExitBuffers.Clear();
}
}
#region b2Box
public static void DestroyFixture(this b2Body self, Fixture fixture)
{
if (b2WorldManager.Instance.IsLocked())
{
Log.Error($"cannot destroy fixture while b2World is locked!!");
return;
}
self.body.DestroyFixture(fixture);
}
public static Fixture CreateFixture(this b2Body self,FixtureDef fixtureDef)
{
if (b2WorldManager.Instance.IsLocked())
{
Log.Error($"cannot create fixture while b2World is locked!!");
return null;
}
return self.body.CreateFixture(fixtureDef);
}
/// <summary>
/// 激活刚体
/// 刚体处于未激活状态下,不会参与碰撞、射线检测、查询
/// 未激活刚体仍然可以创建夹具、关节
/// </summary>
public static void SetEnable(this b2Body self, bool isEnable)
{
self.body.IsEnabled = isEnable;
}
private static bool ContainBox(this b2Body self, string boxName)
{
return self.b2BoxDict.ContainsKey(boxName);
}
public static b2Box GetBox(this b2Body self, string boxName)
{
if (!self.b2BoxDict.TryGetValue(boxName, out long id))
{
Log.Error($"cannot found b2Box. boxName: {boxName}");
return null;
}
return self.GetChild<b2Box>(id);
}
public static b2Box AddBox(this b2Body self, string boxName)
{
if (self.ContainBox(boxName))
{
Log.Error($"already exist b2Box. boxName: {boxName} unit.instanceId: {self.unitId}");
return null;
}
b2Box b2Box = self.AddChild<b2Box>(true);
self.b2BoxDict.Add(boxName, b2Box.Id);
return b2Box;
}
public static void DestroyBox(this b2Body self, string boxName)
{
if (!self.b2BoxDict.Remove(boxName, out long id))
{
Log.Error($"cannot found b2Box. boxName: {boxName}");
return;
}
b2Box box = self.GetChild<b2Box>(id);
box.Dispose();
}
/// <summary>
/// 删除指定HitboxType的夹具
/// </summary>
/// <param name="self"></param>
/// <param name="filter">HitboxType.Hit | HitboxType.Hurt </param>
public static void DestroyBoxes(this b2Body self, HitboxType filter)
{
ListComponent<long> ids = ListComponent<long>.Create(); // 池化管理
foreach (var kv in self.b2BoxDict)
{
b2Box box = self.GetChild<b2Box>(kv.Value);
if ((box.GetBoxType() & filter) != 0)
{
ids.Add(box.Id); // note: 不能在集合内删除元素
}
}
foreach (long id in ids)
{
b2Box box = self.GetChild<b2Box>(id);
self.b2BoxDict.Remove(box.GetBoxName());
box.Dispose();
}
ids.Dispose();
}
#endregion
#region ContactFilter
public static void RegistFilter(this b2Body self, int filterType)
{
self.filterSet.Add(filterType);
}
public static void RemoveFilter(this b2Body self, int filterType)
{
self.filterSet.Remove(filterType);
}
/// <summary>
/// 控制夹具是否发生碰撞
/// </summary>
/// <param name="self"></param>
/// <param name="instanceIdA">b2Box.InstanceId</param>
/// <param name="instanceIdB">b2Box.InstanceId</param>
/// <returns></returns>
public static bool CollideCheck(this b2Body self, long instanceIdA, long instanceIdB)
{
bool canCollide = true;
foreach (int filter in self.filterSet)
{
canCollide = EventSystem.Instance.Invoke<B2FilterCallback, bool>(filter, new B2FilterCallback() { instanceIdA = instanceIdA, instanceIdB = instanceIdB });
if (!canCollide) break;
}
return canCollide;
}
#endregion
#region Flip
/// <summary>
/// 设置刚体朝向,渲染层同步朝向
/// </summary>
public static void SetFlip(this b2Body self, FlipState flipState)
{
self.SetFlip((int)flipState);
}
public static void SetFlip(this b2Body self, int flip)
{
EventSystem.Instance.Invoke(new UpdateFlipCallback(){instanceId = self.InstanceId, flip = flip});
}
public static int GetFlip(this b2Body self)
{
return (int)self.flip;
}
#endregion
#region Angle
public static void SetAngle(this b2Body self, float angle)
{
self.angle = angle;
self.body.SetTransform(self.GetPosition(), self.angle * UnityEngine.Mathf.Deg2Rad);
self.SyncTrans();
}
public static float GetAngle(this b2Body self)
{
return self.angle;
}
public static float GetRadian(this b2Body self)
{
return self.GetAngle() * UnityEngine.Mathf.Deg2Rad;
}
#endregion
public static int GetHertz(this b2Body self)
{
return self.hertz;
}
public static void SetHertz(this b2Body self, int hertz)
{
self.hertz = hertz;
}
#region Velocity
//真实速度 = 当前帧速度 * 朝向 * TimeScale
public static void SetLinearVelocity(this b2Body self, Vector2 velocity)
{
Vector2 realVelocity = velocity * (self.hertz / 60f) * new Vector2(-self.GetFlip(), 1);
self.velocity = velocity;
self.body.SetLinearVelocity(realVelocity);
}
public static Vector2 GetVelocity(this b2Body self)
{
return self.velocity;
}
public static void SetVelocity(this b2Body self, Vector2 value)
{
self.velocity = value;
}
public static void SetVelocityY(this b2Body self, float velocityY)
{
self.velocity.Y = velocityY;
}
public static void SetVelocityX(this b2Body self, float velocityX)
{
self.velocity.X = velocityX;
}
#endregion
#region Transform
public static void SetPosition(this b2Body self, Vector2 position)
{
self.body.SetTransform(position, 0f);
}
public static Vector2 GetPosition(this b2Body self)
{
return self.body.GetPosition();
}
public static Transform GetTransform(this b2Body self)
{
return self.body.GetTransform();
}
public static void SyncTrans(this b2Body self)
{
Unit unit = Root.Instance.Get(self.unitId) as Unit;
UnityEngine.GameObject go = unit.GetComponent<GameObjectComponent>().GameObject;
Transform trans = self.body.GetTransform();
go.transform.position = trans.Position.ToUnityVector3();
go.transform.eulerAngles = new UnityEngine.Vector3(0, 0, trans.Rotation.Angle * UnityEngine.Mathf.Rad2Deg);
go.transform.localScale = new UnityEngine.Vector3(self.GetFlip(), 1, 1);
}
#endregion
}
} | 0 | 0.790267 | 1 | 0.790267 | game-dev | MEDIA | 0.758753 | game-dev | 0.929463 | 1 | 0.929463 |
Dn-Programming-Core-Management/Dn-FamiTracker | 1,878 | Source/ChannelsMMC5.h | /*
** Dn-FamiTracker - NES/Famicom sound tracker
** Copyright (C) 2020-2025 D.P.C.M.
** FamiTracker Copyright (C) 2005-2020 Jonathan Liss
** 0CC-FamiTracker Copyright (C) 2014-2018 HertzDevil
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see https://www.gnu.org/licenses/.
*/
#pragma once
//
// Derived channels, MMC5
//
class CChannelHandlerMMC5 : public CChannelHandler {
public:
CChannelHandlerMMC5();
void ResetChannel() override;
void RefreshChannel() override;
int getDutyMax() const override;
protected:
static const char MAX_DUTY;
void HandleNoteData(stChanNote *pNoteData, int EffColumns) override;
bool HandleEffect(effect_t EffNum, unsigned char EffParam) override; // // //
void HandleEmptyNote() override;
void HandleCut() override;
void HandleRelease() override;
bool CreateInstHandler(inst_type_t Type) override; // // //
int ConvertDuty(int Duty) const override; // // //
void ClearRegisters() override;
CString GetCustomEffectString() const override; // // //
void resetPhase();
protected:
// // //
bool m_bHardwareEnvelope; // // // (constant volume flag, bit 4)
bool m_bEnvelopeLoop; // // // (halt length counter flag, bit 5 / triangle bit 7)
bool m_bResetEnvelope; // // //
int m_iLengthCounter; // // //
int m_iLastPeriod; // // // moved to subclass
}; | 0 | 0.904818 | 1 | 0.904818 | game-dev | MEDIA | 0.49298 | game-dev,embedded-firmware | 0.524089 | 1 | 0.524089 |
HunterPie/HunterPie-legacy | 38,301 | HunterPie.Core/Core/Monsters/Monster.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using HunterPie.Core.Definitions;
using HunterPie.Core.Enums;
using HunterPie.Core.Monsters;
using HunterPie.Logger;
using HunterPie.Memory;
using HunterPie.Core.Events;
using HunterPie.Core.Native;
namespace HunterPie.Core
{
public class Monster
{
// Private vars
private long monsterAddress;
private string id;
private float health;
private float stamina;
private bool isTarget;
private int isSelect; //0 = None, 1 = This, 2 = Other
private float enrageTimer = 0;
private float sizeMultiplier;
private int actionId;
private bool isAlive;
private bool isCaptured;
private AlatreonState alatreonElement;
public long MonsterAddress
{
get => monsterAddress;
private set
{
if (value != monsterAddress)
{
if (monsterAddress != 0)
{
Id = null;
FoundEnrageInMemory = false;
}
monsterAddress = value;
}
}
}
/// <summary>
/// Number of this monster
/// </summary>
public int MonsterNumber { get; private set; }
/// <summary>
/// Monster name
/// </summary>
public string Name { get; private set; }
private MonsterInfo MonsterInfo => MonsterData.MonstersInfo[GameId];
/// <summary>
/// Monster EM Id
/// </summary>
public string Id
{
get => id;
private set
{
if (!string.IsNullOrEmpty(value) && id != value)
{
if (Health > 0)
{
// Temporary until I figure out the crash reason
Name = GMD.GetMonsterNameByEm(value);
id = value;
IsCaptured = false;
GetMonsterWeaknesses();
IsAlive = true;
CreateMonsterParts(MonsterInfo.MaxParts);
GetMonsterPartsInfo();
GetMonsterAilments();
GetMonsterSizeModifier();
CaptureThreshold = MonsterInfo.Capture;
IsActuallyAlive = true;
Dispatch(OnMonsterSpawn);
}
}
else if (string.IsNullOrEmpty(value) && id != value)
{
isAlive = IsActuallyAlive = false;
Dispatch(OnMonsterDespawn);
DestroyParts();
id = value;
}
}
}
/// <summary>
/// Monster in-game Id
/// </summary>
public int GameId { get; private set; }
/// <summary>
/// Monster size multiplier
/// </summary>
public float SizeMultiplier
{
get => sizeMultiplier;
private set
{
if (value <= 0) return;
if (value != sizeMultiplier)
{
sizeMultiplier = value;
Debugger.Debug($"{Name} Size multiplier: {sizeMultiplier}");
Dispatch(OnCrownChange);
}
}
}
/// <summary>
/// Monster size crown name
/// </summary>
public string Crown => MonsterInfo.GetCrownByMultiplier(SizeMultiplier);
/// <summary>
/// Monster maximum health
/// </summary>
public float MaxHealth { get; private set; }
/// <summary>
/// Monster current health
/// </summary>
public float Health
{
get => health;
private set
{
if (value != health)
{
health = value;
Dispatch(OnHPUpdate);
}
}
}
/// <summary>
/// Monster weaknesses
/// </summary>
public Dictionary<string, int> Weaknesses { get; private set; }
/// <summary>
/// Normalized health percentage (<see cref="Health"/> / <see cref="MaxHealth"/>)
/// </summary>
public float HPPercentage { get; private set; } = 1;
/// <summary>
/// Whether this monster is the current target
/// </summary>
public bool IsTarget
{
get => isTarget;
private set
{
if (value != isTarget)
{
isTarget = value;
Dispatch(OnTargetted);
}
}
}
/// <summary>
/// Whether this monster is selected
/// </summary>
public int IsSelect
{
get => isSelect;
private set
{
if (value != isSelect)
{
isSelect = value;
Dispatch(OnTargetted);
}
}
}
/// <summary>
/// Whether this monster is alive
/// </summary>
public bool IsAlive
{
get => isAlive;
private set
{
if (!value && isAlive)
{
IsActuallyAlive = isAlive = value;
Dispatch(OnMonsterDeath);
DestroyParts();
} else
{
isAlive = value;
}
}
}
/// <summary>
/// Same as <see cref="IsAlive"/> but is only set to true after everything is initialized
/// </summary>
public bool IsActuallyAlive { get; private set; }
/// <summary>
/// Current enrage timer
/// </summary>
public float EnrageTimer
{
get => enrageTimer;
private set
{
if (value != enrageTimer)
{
if (value > 0 && enrageTimer == 0)
{
Dispatch(OnEnrage);
}
else if (value == 0 && enrageTimer > 0)
{
Dispatch(OnUnenrage);
}
enrageTimer = value;
Dispatch(OnEnrageTimerUpdate);
}
}
}
/// <summary>
/// Enrage maximum duration
/// </summary>
public float EnrageTimerStatic { get; private set; }
/// <summary>
/// Whether this monster is enraged
/// </summary>
public bool IsEnraged => enrageTimer > 0;
private bool FoundEnrageInMemory { get; set; }
/// <summary>
/// Current monster stamina
/// </summary>
public float Stamina
{
get => stamina;
private set
{
if ((int)value != (int)stamina)
{
stamina = value;
Dispatch(OnStaminaUpdate);
}
}
}
/// <summary>
/// Maximum monster stamina
/// </summary>
public float MaxStamina { get; private set; }
/// <summary>
/// Monster threshold to be captured
/// </summary>
public float CaptureThreshold { get; private set; }
/// <summary>
/// Whether this monster is captured
/// </summary>
public bool IsCaptured
{
get => isCaptured;
set
{
if (value && value != isCaptured)
{
isCaptured = value;
IsActuallyAlive = isAlive = !isCaptured;
Dispatch(OnMonsterCapture);
DestroyParts();
} else if (!value && value != isCaptured)
{
isCaptured = false;
}
}
}
public readonly bool[] AliveMonsters = { false, false, false };
/// <summary>
/// Current action Id
/// </summary>
public int ActionId
{
get => actionId;
set
{
if (actionId != value)
{
actionId = value;
Dispatch(OnActionChange);
Debugger.Debug($"{Name} -> {ActionReferenceName} (Action: {value})");
}
}
}
/// <summary>
/// Filtered stringified action name
/// </summary>
public string ActionName { get; private set; }
/// <summary>
/// Raw stringified action name
/// </summary>
public string ActionReferenceName { get; private set; }
/// <summary>
/// Current Alatreon element, used only by Alatreon
/// </summary>
public AlatreonState AlatreonElement
{
get => alatreonElement;
private set
{
if (value != alatreonElement)
{
alatreonElement = value;
Dispatch(OnAlatreonElementShift);
}
}
}
/// <summary>
/// Whether the local player is currently the party host
/// </summary>
public bool IsLocalHost { get; internal set; }
/// <summary>
/// Current monster parts
/// </summary>
public List<Part> Parts = new List<Part>();
/// <summary>
/// Current monster ailments
/// </summary>
public List<Ailment> Ailments = new List<Ailment>();
/// <summary>
/// Current monster position
/// </summary>
public readonly Vector3 Position = new Vector3(0, 0, 0);
/// <summary>
/// Current monster model data
/// </summary>
public sMonsterModelData ModelData { get; private set; }
// Threading
ThreadStart monsterInfoScanRef;
Thread monsterInfoScan;
#region Events
public delegate void MonsterEvents(object source, EventArgs args);
public delegate void MonsterSpawnEvents(object source, MonsterSpawnEventArgs args);
public delegate void MonsterUpdateEvents(object source, MonsterUpdateEventArgs args);
/// <summary>
/// Dispatched when a monster spawns
/// </summary>
public event MonsterSpawnEvents OnMonsterSpawn;
/// <summary>
/// Dispatched when all monster ailments are loaded
/// </summary>
public event MonsterEvents OnMonsterAilmentsCreate;
/// <summary>
/// Dispatched when a monster despawns (either leaves area or after it's dead/captured body despawns)
/// </summary>
public event MonsterEvents OnMonsterDespawn;
/// <summary>
/// Dispatched when a monster is killed
/// </summary>
public event MonsterEvents OnMonsterDeath;
/// <summary>
/// Dispatched when a monster is captured
/// </summary>
public event MonsterEvents OnMonsterCapture;
/// <summary>
/// Dispatched when a monster is targeted by the local player
/// </summary>
public event MonsterEvents OnTargetted;
/// <summary>
/// Dispatched when the monster crown size is changed
/// </summary>
public event MonsterEvents OnCrownChange;
/// <summary>
/// Dispatched when the monster health value changes
/// </summary>
public event MonsterUpdateEvents OnHPUpdate;
/// <summary>
/// Dispatched when the monster stamina value changes
/// </summary>
public event MonsterUpdateEvents OnStaminaUpdate;
/// <summary>
/// Dispatched when a monster executes a new action
/// </summary>
public event MonsterUpdateEvents OnActionChange;
/// <summary>
/// Dispatched when a monster becomes enraged
/// </summary>
public event MonsterUpdateEvents OnEnrage;
/// <summary>
/// Dispatched when a monster becomes unenraged
/// </summary>
public event MonsterUpdateEvents OnUnenrage;
/// <summary>
/// Dispatched when the monster enrage timer is updated
/// </summary>
public event MonsterUpdateEvents OnEnrageTimerUpdate;
/// <summary>
/// Dispatched when the monster scan is finished
/// </summary>
public event MonsterEvents OnMonsterScanFinished;
/// <summary>
/// Dispatched when Alatreon shifts to another element <br/>
/// <b>Used only by Alatreon.</b>
/// </summary>
public event MonsterEvents OnAlatreonElementShift;
private void Dispatch(MonsterSpawnEvents e)
{
if (e is null)
return;
MonsterSpawnEventArgs args = new MonsterSpawnEventArgs(this);
foreach (MonsterSpawnEvents del in e.GetInvocationList())
{
try
{
del(this, args);
} catch (Exception err)
{
Debugger.Error($"Error on callback \"{del.Method.Name}\": {err.Message}");
}
}
}
private void Dispatch(MonsterEvents e)
{
if (e is null)
return;
foreach (MonsterEvents del in e.GetInvocationList())
{
try
{
del(this, EventArgs.Empty);
}
catch (Exception err)
{
Debugger.Error($"Error on callback \"{del.Method.Name}\": {err.Message}");
}
}
}
private void Dispatch(MonsterUpdateEvents e)
{
if (e is null)
return;
MonsterUpdateEventArgs args = new MonsterUpdateEventArgs(this);
foreach (MonsterUpdateEvents del in e.GetInvocationList())
{
try
{
del(this, args);
}
catch (Exception err)
{
Debugger.Error($"Error on callback \"{del.Method.Name}\": {err.Message}");
}
}
}
private void DispatchScanFinished()
{
if (OnMonsterScanFinished == null)
{
return;
}
foreach (MonsterEvents sub in OnMonsterScanFinished.GetInvocationList())
{
try
{
sub(this, EventArgs.Empty);
}
catch (Exception err)
{
Debugger.Error($"Exception in {sub.Method.Name}: {err.Message}");
OnMonsterScanFinished -= sub;
}
}
}
#endregion
public Monster(int initMonsterNumber)
{
MonsterNumber = initMonsterNumber;
}
~Monster()
{
Id = null;
Weaknesses?.Clear();
}
internal void StartThreadingScan()
{
monsterInfoScanRef = new ThreadStart(ScanMonsterInfo);
monsterInfoScan = new Thread(monsterInfoScanRef)
{
Name = $"Kernel_Monster.{MonsterNumber}"
};
monsterInfoScan.SetApartmentState(ApartmentState.STA);
Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_MONSTER_SCANNER_INITIALIZED']").Replace("{MonsterNumber}", MonsterNumber.ToString()));
monsterInfoScan.Start();
}
internal void StopThread() => monsterInfoScan.Abort();
private void ScanMonsterInfo()
{
while (Kernel.GameIsRunning)
{
GetMonsterAddress();
GetMonsterId();
GetMonsterSizeModifier();
GetMonsterStamina();
GetMonsterAilments();
GetMonsterPartsInfo();
GetPartsTenderizeInfo();
GetMonsterAction();
GetMonsterEnrageTimer();
GetTargetMonsterAddress();
GetAlatreonCurrentElement();
GetMonsterModelData();
DispatchScanFinished();
Thread.Sleep(ConfigManager.Settings.Overlay.GameScanDelay);
}
Thread.Sleep(1000);
ScanMonsterInfo();
}
/// <summary>
/// Removes all Parts and Ailments from this monster. This should be called whenever the monster despawns
/// </summary>
private void DestroyParts()
{
foreach (Part monsterPart in Parts)
{
monsterPart.Destroy();
}
Parts.Clear();
foreach (Ailment monsterAilment in Ailments)
{
monsterAilment.Destroy();
}
Ailments.Clear();
}
private void GetMonsterAddress()
{
long address = Address.GetAddress("BASE") + Address.GetAddress("MONSTER_OFFSET");
// This will give us the third monster's address, so we can find the second and first monster with it
long ThirdMonsterAddress = Kernel.ReadMultilevelPtr(address, Address.GetOffsets("MonsterOffsets"));
switch (MonsterNumber)
{
case 3:
MonsterAddress = ThirdMonsterAddress;
break;
case 2:
MonsterAddress = Kernel.Read<long>(ThirdMonsterAddress - 0x30) + 0x40;
break;
case 1:
MonsterAddress = Kernel.Read<long>(Kernel.Read<long>(ThirdMonsterAddress - 0x30) + 0x10) + 0x40;
break;
default:
break;
}
}
/// <summary>
/// Gets the current monster health and max health.
/// </summary>
private void GetMonsterHealth()
{
long MonsterHealthPtr = Kernel.Read<long>(MonsterAddress + Offsets.MonsterHPComponentOffset);
float MonsterTotalHealth = Kernel.Read<float>(MonsterHealthPtr + 0x60);
float MonsterCurrentHealth = Kernel.Read<float>(MonsterHealthPtr + 0x64);
if (MonsterCurrentHealth <= MonsterTotalHealth && MonsterTotalHealth > 0)
{
MaxHealth = MonsterTotalHealth;
Health = MonsterCurrentHealth;
HPPercentage = Health / MaxHealth == 0 ? 1 : Health / MaxHealth;
}
else
{
MaxHealth = 0;
Health = 0;
HPPercentage = 1;
}
}
/// <summary>
/// Gets the current monster EM and GameId
/// </summary>
private void GetMonsterId()
{
long NamePtr = Kernel.Read<long>(MonsterAddress + Offsets.MonsterNamePtr);
string MonsterEm = Kernel.ReadString(NamePtr + 0x0C, 64);
if (!string.IsNullOrEmpty(MonsterEm))
{
// Validates the em string
string[] MonsterEmParsed = MonsterEm.Split('\\');
if (MonsterEmParsed.ElementAtOrDefault(3) == null)
{
Id = null;
return;
}
MonsterEm = MonsterEmParsed.LastOrDefault();
if (MonsterEm.StartsWith("em"))
{
GameId = Kernel.Read<int>(MonsterAddress + Offsets.MonsterGameIDOffset);
if (!MonsterData.MonstersInfo.ContainsKey(GameId))
{
if (!MonsterEm.StartsWith("ems"))
{
Debugger.Debug($"Unmapped monster Detected: ID:{GameId} | EM: {MonsterEm} | Name: {Name}");
}
Id = null;
Health = 0;
MaxHealth = 0;
HPPercentage = 1;
return;
}
else
{
GetMonsterHealth();
if (Id != MonsterInfo.Em && Health > 0)
Debugger.Debug($"Found new monster ID: {GameId} ({MonsterEm}) #{MonsterNumber} @ 0x{MonsterAddress:X}");
Id = MonsterInfo.Em;
return;
}
}
}
Id = null;
}
private void GetMonsterModelData()
{
if (!IsAlive)
return;
sMonsterModelData data = Kernel.ReadStructure<sMonsterModelData>(MonsterAddress + 0x160);
Position.Update(data.pos);
ModelData = data;
}
/// <summary>
/// Gets the monster action
/// </summary>
private void GetMonsterAction()
{
if (!IsAlive)
{
return;
}
// This is our rcx
long actionPointer = MonsterAddress + 0x61C8;
// This will give us the action id, we'll need it later on to get the action reference name
int actionId = Kernel.Read<int>(actionPointer + 0xB0);
// mov rax,[rcx+rax*8+68] ;our rax is pretty much always 2
actionPointer = Kernel.Read<long>(actionPointer + (2 * 8) + 0x68);
// mov rax,[rax+rdx*8]
actionPointer = Kernel.Read<long>(actionPointer + actionId * 8);
actionPointer = Kernel.Read<long>(actionPointer);
// call qword ptr [r8 + 20] ;r8 is our actionPointer
actionPointer = Kernel.Read<long>(actionPointer + 0x20);
uint actionOffset = Kernel.Read<uint>(actionPointer + 3);
// lea rax,[actionRef]
long actionRef = actionPointer + actionOffset + 7;
// cmp [rax+08],rcx
actionRef = Kernel.Read<long>(actionRef + 8);
string actionRefString = Kernel.ReadString(actionRef, 64);
ActionReferenceName = actionRefString;
ActionName = Monster.ParseActionString(actionRefString);
IsAlive = !DetectDeath(actionRefString);
IsCaptured = actionRefString.Contains("Capture");
ActionId = actionId;
}
/// <summary>
/// Gets monster size
/// </summary>
private void GetMonsterSizeModifier()
{
if (!IsAlive) return;
float SizeModifier = Kernel.Read<float>(MonsterAddress + 0x7730);
if (SizeModifier <= 0 || SizeModifier >= 2) SizeModifier = 1;
SizeMultiplier = Kernel.Read<float>(MonsterAddress + 0x188) / SizeModifier;
}
/// <summary>
/// Builds monster weakness dictionary
/// </summary>
private void GetMonsterWeaknesses() => Weaknesses = MonsterInfo.Weaknesses.ToDictionary(w => w.Id, w => w.Stars);
private void GetMonsterEnrageTimer()
{
if (!IsAlive) return;
sMonsterStatus enrage = Kernel.ReadStructure<sMonsterStatus>(MonsterAddress + 0x1BE30);
EnrageTimer = enrage.Duration;
EnrageTimerStatic = enrage.MaxDuration;
if (!FoundEnrageInMemory && Ailments.Count > 0)
{
AilmentInfo info = MonsterData.GetAilmentInfoById(999);
Ailment enrageTracker = new Ailment(MonsterAddress + 0x1BE30, info);
enrageTracker.SetAilmentInfo(sMonsterStatus.Convert(enrage), IsLocalHost, 999);
Ailments.Add(enrageTracker);
FoundEnrageInMemory = true;
}
}
private void GetTargetMonsterAddress()
{
if (ConfigManager.Settings.Overlay.MonstersComponent.UseLockonInsteadOfPin)
{
long LockonAddress = Kernel.ReadMultilevelPtr(Address.GetAddress("BASE") + Address.GetAddress("EQUIPMENT_OFFSET"), Address.GetOffsets("PlayerLockonOffsets"));
// This will give us the monster target index
int MonsterLockonIndex = Kernel.Read<int>(LockonAddress - 0x7C);
if (MonsterLockonIndex == -1)
{
IsTarget = false;
IsSelect = 0;
return;
}
// And this one will give us the actual monster index in that target slot
LockonAddress = LockonAddress - 0x7C - 0x19F8;
int MonsterIndexInSlot = Kernel.Read<int>(LockonAddress + (MonsterLockonIndex * 8));
if (MonsterIndexInSlot > 2 || MonsterIndexInSlot < 0)
{
IsTarget = false;
IsSelect = 0;
return;
}
// And then we get then we can finally get the monster index
List<int> MonsterSlotIndexes = new List<int>();
for (int i = 0; i < 3; i++) MonsterSlotIndexes.Add(Kernel.Read<int>(LockonAddress + 0x6C + (4 * i)));
int[] MonsterIndexes = MonsterSlotIndexes.ToArray();
if (MonsterIndexes[2] == -1 && MonsterIndexes[1] == -1 && AliveMonsters.Where(v => v == true).Count() == 1)
{
IsTarget = IsAlive;
}
else if (MonsterIndexes[2] == -1 && MonsterIndexes[1] != -1 && AliveMonsters.Where(v => v == true).Count() == 2)
{
if (!AliveMonsters[0])
{
IsTarget = MonsterIndexes[MonsterIndexInSlot] + 1 == (MonsterNumber - 1);
}
else if (!AliveMonsters[1])
{
IsTarget = MonsterIndexes[MonsterIndexInSlot] * 2 == (MonsterNumber - 1);
}
else
{
IsTarget = MonsterIndexes[MonsterIndexInSlot] == (MonsterNumber - 1);
}
}
else
{
IsTarget = MonsterIndexes[MonsterIndexInSlot] == (MonsterNumber - 1);
}
IsSelect = IsTarget ? 1 : 2;
}
else
{
long TargettedMonsterAddress = Kernel.ReadMultilevelPtr(Address.GetAddress("BASE") + Address.GetAddress("MONSTER_SELECTED_OFFSET"), Address.GetOffsets("MonsterSelectedOffsets"));
long selectedPtr = Kernel.Read<long>(Address.GetAddress("BASE") + Address.GetAddress("MONSTER_TARGETED_OFFSET")); //probably want an offset for this
bool isSelect = Kernel.Read<long>(selectedPtr + 0x128) != 0x0 && Kernel.Read<long>(selectedPtr + 0x130) != 0x0 && Kernel.Read<long>(selectedPtr + 0x160) != 0x0;
long SelectedMonsterAddress = Kernel.Read<long>(selectedPtr + 0x148);
IsTarget = TargettedMonsterAddress == 0 ? SelectedMonsterAddress == MonsterAddress : TargettedMonsterAddress == MonsterAddress;
if (!isSelect)
{
IsSelect = 0; // nothing is selected
}
else if (IsTarget)
{
IsSelect = 1; // this monster is selected
}
else
{
IsSelect = 2; // another monster is selected
}
}
}
/// <summary>
/// Creates monster parts based on how many parts it has in MonsterData.xml
/// </summary>
/// <param name="numberOfParts">Number of parts</param>
private void CreateMonsterParts(int numberOfParts)
{
for (int i = 0; i < numberOfParts; i++)
{
Part part = new Part(this, MonsterInfo.Parts[i], i);
Parts.Add(part);
}
}
private void GetMonsterPartsInfo()
{
if (!IsAlive || IsCaptured) return;
long MonsterPartPtr = Kernel.Read<long>(MonsterAddress + 0x1D058);
// If the Monster Part Ptr is still 0, then the monster hasn't fully spawn yet
if (MonsterPartPtr == Kernel.NULLPTR)
return;
long MonsterPartAddress = MonsterPartPtr + 0x40;
long MonsterRemovablePartAddress = MonsterPartPtr + 0x1FC8;
int NormalPartIndex = 0;
uint RemovablePartIndex = 0;
for (int pIndex = 0; pIndex < MonsterInfo.MaxParts; pIndex++)
{
Part CurrentPart = Parts[pIndex];
PartInfo CurrentPartInfo = MonsterInfo.Parts[pIndex];
if (CurrentPartInfo.IsRemovable)
{
if (CurrentPart.Address > 0)
{
sMonsterRemovablePart MonsterRemovablePartData = Kernel.ReadStructure<sMonsterRemovablePart>(CurrentPart.Address);
// Alatreon explosion level
if (GameId == 87 && MonsterRemovablePartData.unk3.Index == 3)
{
MonsterRemovablePartData.Data.Counter = Kernel.Read<int>(MonsterAddress + 0x20920);
}
CurrentPart.SetPartInfo(MonsterRemovablePartData.Data, IsLocalHost);
}
else
{
while (MonsterRemovablePartAddress < MonsterRemovablePartAddress + 0x120 * 32)
{
// Every 15 parts there's a 8 bytes gap between the old removable part block
// and the next part block
if (Kernel.Read<long>(MonsterRemovablePartAddress) <= 0xA0)
{
MonsterRemovablePartAddress += 0x8;
}
sMonsterRemovablePart MonsterRemovablePartData = Kernel.ReadStructure<sMonsterRemovablePart>(MonsterRemovablePartAddress);
if (CurrentPartInfo.Skip || (MonsterRemovablePartData.unk3.Index == CurrentPartInfo.Index && MonsterRemovablePartData.Data.MaxHealth > 0))
{
CurrentPart.Address = MonsterRemovablePartAddress;
CurrentPart.IsRemovable = true;
CurrentPart.SetPartInfo(MonsterRemovablePartData.Data, IsLocalHost);
Debugger.Debug($"Removable Part Structure <{Name}> ({CurrentPart.Name}) [0x{MonsterRemovablePartAddress:X}]");
RemovablePartIndex++;
do
{
MonsterRemovablePartAddress += 0x78;
} while (MonsterRemovablePartData.Equals(Kernel.ReadStructure<sMonsterRemovablePart>(MonsterRemovablePartAddress)));
break;
}
MonsterRemovablePartAddress += 0x78;
}
}
}
else
{
if (CurrentPart.Address > 0)
{
sMonsterPart MonsterPartData = Kernel.ReadStructure<sMonsterPart>(CurrentPart.Address);
CurrentPart.SetPartInfo(MonsterPartData.Data, IsLocalHost);
}
else
{
sMonsterPart MonsterPartData = Kernel.ReadStructure<sMonsterPart>(MonsterPartAddress + (NormalPartIndex * 0x1F8));
CurrentPart.Address = MonsterPartAddress + (NormalPartIndex * 0x1F8);
CurrentPart.Group = CurrentPartInfo.GroupId;
CurrentPart.TenderizedIds = CurrentPartInfo.TenderizeIds;
CurrentPart.SetPartInfo(MonsterPartData.Data, IsLocalHost);
Debugger.Debug($"Part Structure <{Name}> ({CurrentPart.Name}) [0x{CurrentPart.Address:X}]");
NormalPartIndex++;
}
}
}
}
private void GetMonsterStamina()
{
if (!IsAlive)
return;
long MonsterStaminaAddress = MonsterAddress + 0x1C0F0;
MaxStamina = Kernel.Read<float>(MonsterStaminaAddress + 0x4);
float stam = Kernel.Read<float>(MonsterStaminaAddress);
Stamina = stam <= MaxStamina ? stam : MaxStamina;
}
private void GetMonsterAilments()
{
if (!IsAlive)
return;
if (Ailments.Count > 0)
{
foreach (Ailment ailment in Ailments)
{
sMonsterAilment updatedData;
switch (ailment.Type)
{
case AilmentType.Status:
sMonsterStatus updatedStatus = Kernel.ReadStructure<sMonsterStatus>(ailment.Address);
updatedData = sMonsterStatus.Convert(updatedStatus);
break;
default:
updatedData = Kernel.ReadStructure<sMonsterAilment>(ailment.Address);
break;
}
ailment.SetAilmentInfo(updatedData, IsLocalHost);
}
}
else
{
long MonsterAilmentListPtrs = MonsterAddress + 0x1BC40;
long MonsterAilmentPtr = Kernel.Read<long>(MonsterAilmentListPtrs);
while (MonsterAilmentPtr > 1)
{
// There's a gap of 0x148 bytes between the pointer and the sMonsterAilment structure
sMonsterAilment AilmentData = Kernel.ReadStructure<sMonsterAilment>(MonsterAilmentPtr + 0x148);
if ((int)AilmentData.Id > MonsterData.AilmentsInfo.Count)
{
MonsterAilmentListPtrs += sizeof(long);
MonsterAilmentPtr = Kernel.Read<long>(MonsterAilmentListPtrs);
continue;
}
var AilmentInfo = MonsterData.GetAilmentInfoById(AilmentData.Id);
// Check if this Ailment can be skipped and therefore not be tracked at all
bool SkipElderDragonTrap = MonsterInfo.Capture == 0 && AilmentInfo.Group == "TRAP";
if (SkipElderDragonTrap || (AilmentInfo.CanSkip && !ConfigManager.Settings.HunterPie.Debug.ShowUnknownStatuses))
{
MonsterAilmentListPtrs += sizeof(long);
MonsterAilmentPtr = Kernel.Read<long>(MonsterAilmentListPtrs);
continue;
}
Ailment MonsterAilment = new Ailment(MonsterAilmentPtr + 0x148, AilmentInfo);
MonsterAilment.SetAilmentInfo(AilmentData, IsLocalHost);
Debugger.Debug($"sMonsterAilment <{Name}> ({MonsterAilment.Name}) [0x{MonsterAilmentPtr + 0x148:X}]");
Ailments.Add(MonsterAilment);
MonsterAilmentListPtrs += sizeof(long);
MonsterAilmentPtr = Kernel.Read<long>(MonsterAilmentListPtrs);
}
// Depending on the scan delay, the OnMonsterSpawn event can be dispatched before the ailments are created.
// To fix that, we dispatch a OnMonsterAilmentsCreate too.
if (IsActuallyAlive && Ailments.Count > 0)
{
Dispatch(OnMonsterAilmentsCreate);
}
}
}
private void GetAlatreonCurrentElement()
{
bool IsAlatreon = GameId == 87;
if (!IsAlive || !IsAlatreon) return;
int alatreonElement = Kernel.Read<int>(MonsterAddress + 0x20910);
if (alatreonElement <= 3 && alatreonElement > 0)
{
AlatreonElement = (AlatreonState)alatreonElement;
}
}
private void GetPartsTenderizeInfo()
{
if (!IsAlive || Parts.Count == 0) return;
for (uint i = 0; i < 10; i++)
{
sTenderizedPart tenderizedData = Kernel.ReadStructure<sTenderizedPart>(MonsterAddress + 0x1C458 + (i * 0x40));
if (tenderizedData.PartId != uint.MaxValue)
{
//Debugger.Debug(tenderizedData.PartId);
foreach (Part validPart in Parts.Where(p => p.TenderizedIds != null && p.TenderizedIds.Contains(tenderizedData.PartId)))
{
validPart.SetTenderizeInfo(tenderizedData);
}
}
}
}
public static string ParseActionString(string actionRef)
{
string actionRefName = actionRef.Split('<').FirstOrDefault().Split(':').LastOrDefault();
return string.Concat(actionRefName.Select((c, i) => i > 0 && char.IsUpper(c) ? " " + c.ToString() : c.ToString()));
}
public static bool DetectDeath(string actionRef)
{
return (actionRef.Contains("Die") && !actionRef.Contains("DieSleep")) || (actionRef.Contains("Dead") && !actionRef.Contains("Deadly"));
}
}
}
| 0 | 0.86966 | 1 | 0.86966 | game-dev | MEDIA | 0.946125 | game-dev | 0.882985 | 1 | 0.882985 |
fishfolk/jumpy | 4,643 | src/core/input.rs | //! Player and editor input types.
use std::array;
use bones_framework::input::PlayerControls;
use crate::{prelude::*, MAX_PLAYERS};
pub fn install(session: &mut SessionBuilder) {
session.init_resource::<MatchInputs>();
}
/// The inputs for each player in this simulation frame.
#[derive(Clone, Debug, HasSchema)]
pub struct MatchInputs {
pub players: [PlayerInput; MAX_PLAYERS as usize],
}
impl Default for MatchInputs {
fn default() -> Self {
Self {
players: array::from_fn(|_| default()),
}
}
}
impl PlayerControls<'_, PlayerControl> for MatchInputs {
type ControlSource = ControlSource;
type ControlMapping = PlayerControlMapping;
type InputCollector = PlayerInputCollector;
fn update_controls(&mut self, collector: &mut PlayerInputCollector) {
(0..MAX_PLAYERS as usize).for_each(|i| {
let player_input = &mut self.players[i];
if let Some(source) = &player_input.control_source {
player_input.control = *collector.get_control(i, *source);
}
});
}
fn get_control_source(&self, player_idx: usize) -> Option<ControlSource> {
self.players.get(player_idx).unwrap().control_source
}
fn get_control(&self, player_idx: usize) -> &PlayerControl {
&self.players.get(player_idx).unwrap().control
}
fn get_control_mut(&mut self, player_idx: usize) -> &mut PlayerControl {
&mut self.players.get_mut(player_idx).unwrap().control
}
}
/// Player input, not just controls, but also other status that comes from the player, such as the
/// selected player and whether the player is actually active.
#[derive(Default, Clone, Debug, HasSchema)]
pub struct PlayerInput {
/// Whether or not the player is present.
pub active: bool,
/// The selected player skin.
pub selected_player: Handle<PlayerMeta>,
/// The selected player hat.
pub selected_hat: Option<Handle<HatMeta>>,
/// The player control input
pub control: PlayerControl,
/// The editor inputs the player is making, if any.
pub editor_input: Option<EditorInput>,
/// If this is [`None`] it means the player is an AI, or remote player in networked game.
pub control_source: Option<ControlSource>,
/// Whether or not this is an AI player.
pub is_ai: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocatedTileLayer {
pub layer_index: u32,
pub located_tiles: Vec<(UVec2, u32, TileCollisionKind)>,
}
#[derive(Clone, HasSchema, Default, Debug)]
pub struct ElementLayer {
pub layer_index: u32,
pub located_elements: Vec<(Vec2, Handle<ElementMeta>)>,
}
/// The editor inputs that a player may make.
#[derive(Clone, Debug)]
pub enum EditorInput {
/// Spawn an element onto the map.
SpawnElement {
/// The handle to the element that is being spawned.
handle: Handle<ElementMeta>,
/// The translation to spawn the element with.
translation: Vec2,
/// The map layer index to spawn the element on.
layer: u8,
},
MoveEntity {
/// The entity to move.
entity: Entity,
/// The amount to move the entity.
pos: Vec2,
},
DeleteEntity {
/// The entity to delete.
entity: Entity,
},
/// Create a new layer
CreateLayer {
/// The name of the layer.
id: String,
},
/// Rename a map layer.
RenameLayer {
/// The index of the layer to rename.
layer: u8,
/// The new name of the layer.
name: String,
},
DeleteLayer {
layer: u8,
},
/// Move a layer up or down.
MoveLayer {
/// The layer to move
layer: u8,
/// Whether or not to move the layer down. If false, move the layer up.
down: bool,
},
/// Update the tilemap of a layer.
SetTilemap {
/// The layer index of the layer to update.
layer: u8,
/// The handle to the tilemap to use or [`None`] to clear the tilemap.
handle: Option<Handle<Atlas>>,
},
SetTile {
/// The layer index of the layer to update
layer: u8,
/// The position of the tile to set
pos: UVec2,
/// The index in the tilemap to set the tile, or [`None`] to delete the tile.
tilemap_tile_idx: Option<u32>,
/// The tile collision kind
collision: TileCollisionKind,
},
RenameMap {
name: String,
},
RandomizeTiles {
tile_layers: Vec<LocatedTileLayer>,
element_layers: Vec<ElementLayer>,
tile_size: Vec2,
},
}
| 0 | 0.92244 | 1 | 0.92244 | game-dev | MEDIA | 0.952914 | game-dev | 0.963361 | 1 | 0.963361 |
ascott18/TellMeWhen | 9,428 | Components/Core/Conditions/Categories/PlayerCombatStats-Retail.lua | -- --------------------
-- TellMeWhen
-- Originally by NephMakes
-- Other contributions by:
-- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol,
-- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune
-- Currently maintained by
-- Cybeloras of Aerie Peak
-- --------------------
if not TMW then return end
local TMW = TMW
local L = TMW.L
local print = TMW.print
local CNDT = TMW.CNDT
local Env = CNDT.Env
local min, format = min, format
Env.UnitStat = UnitStat
Env.GetHaste = GetHaste
Env.GetExpertise = GetExpertise
Env.GetCritChance = GetCritChance
Env.GetSpellCritChance = GetSpellCritChance
Env.GetMasteryEffect = GetMasteryEffect
Env.GetSpellBonusDamage = GetSpellBonusDamage
Env.GetSpellBonusHealing = GetSpellBonusHealing
TMW:RegisterUpgrade(71008, {
replacements = {
RANGEAP = "MELEEAP",
RANGEDCRIT = "MELEECRIT",
RANGEDHASTE = "MELEEHASTE",
SPELLHEALING = "SPELLDMG",
SPELLCRIT = "MELEECRIT",
SPELLHASTE = "MELEEHASTE",
},
condition = function(self, condition)
if self.replacements[condition.Type] then
condition.Type = self.replacements[condition.Type]
end
end,
})
local ConditionCategory = CNDT:GetCategory("STATS", 6, L["CNDTCAT_STATS"], true, true)
ConditionCategory:RegisterCondition(1, "STRENGTH", {
text = _G["SPELL_STAT1_NAME"],
range = 2000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_nature_strength",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[UnitStat("player", 1) c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_STATS", "player")
end,
})
ConditionCategory:RegisterCondition(2, "AGILITY", {
text = _G["SPELL_STAT2_NAME"],
range = 2000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_holy_blessingofagility",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[UnitStat("player", 2) c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_STATS", "player")
end,
})
ConditionCategory:RegisterCondition(3, "STAMINA", {
text = _G["SPELL_STAT3_NAME"],
range = 2000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_holy_wordfortitude",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[UnitStat("player", 3) c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_STATS", "player")
end,
})
ConditionCategory:RegisterCondition(4, "INTELLECT", {
text = _G["SPELL_STAT4_NAME"],
range = 2000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_holy_magicalsentry",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[UnitStat("player", 4) c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_STATS", "player")
end,
})
ConditionCategory:RegisterSpacer(5)
ConditionCategory:RegisterCondition(6, "MELEECRIT", {
text = STAT_CRITICAL_STRIKE,
percent = true,
formatter = TMW.C.Formatter.PERCENT,
min = 0,
max = 100,
unit = PLAYER,
icon = "Interface\\Icons\\Ability_CriticalStrike",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[max(GetCritChance(), GetSpellCritChance(2))/100 c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("COMBAT_RATING_UPDATE")
end,
})
ConditionCategory:RegisterCondition(7, "MELEEHASTE", {
text = STAT_HASTE,
percent = true,
formatter = TMW.C.Formatter.PLUSPERCENT,
min = 0,
range = 100,
unit = PLAYER,
icon = "Interface\\Icons\\spell_nature_bloodlust",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetHaste()/100 c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_ATTACK_SPEED", "player")
end,
})
ConditionCategory:RegisterCondition(8, "MASTERY", {
text = STAT_MASTERY,
min = 0,
range = 100,
formatter = TMW.C.Formatter.PERCENT,
unit = PLAYER,
icon = "Interface\\Icons\\spell_holy_championsbond",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetMasteryEffect() c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("MASTERY_UPDATE")
end,
})
ConditionCategory:RegisterCondition(9, "EXPERTISE", { -- DEPRECATED
text = _G["COMBAT_RATING_NAME"..CR_EXPERTISE],
funcstr = "DEPRECATED",
min = 0,
range = 100,
})
ConditionCategory:RegisterSpacer(10)
ConditionCategory:RegisterCondition(11, "SPIRIT", {
text = _G["SPELL_STAT5_NAME"],
range = 2000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_shadow_burningspirit",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[UnitStat("player", 5) c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_STATS", "player")
end,
})
ConditionCategory:RegisterCondition(13, "MULTISTRIKE", {
text = STAT_MULTISTRIKE,
min = 0,
range = 50,
step = 0.1,
formatter = TMW.C.Formatter.PERCENT,
unit = PLAYER,
icon = "Interface\\Icons\\Ability_UpgradeMoonGlaive",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = "DEPRECATED",
})
ConditionCategory:RegisterCondition(14, "LIFESTEAL", {
text = STAT_LIFESTEAL,
min = 0,
range = 10,
step = 0.1,
formatter = TMW.C.Formatter.PERCENT,
unit = PLAYER,
icon = "Interface\\Icons\\Spell_Shadow_LifeDrain02",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetLifesteal() c.Operator c.Level]],
Env = {
GetLifesteal = GetLifesteal,
},
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("LIFESTEAL_UPDATE")
end,
})
ConditionCategory:RegisterCondition(15, "VERSATILITY", {
text = STAT_VERSATILITY,
min = 0,
range = 50,
step = 0.1,
formatter = TMW.C.Formatter.PERCENT,
unit = PLAYER,
icon = "Interface\\Icons\\achievement_dungeon_icecrown_frostmourne",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetCombatRatingBonus(CR_VERSATILITY_DAMAGE_DONE) + GetVersatilityBonus(CR_VERSATILITY_DAMAGE_DONE) c.Operator c.Level]],
Env = {
CR_VERSATILITY_DAMAGE_DONE = CR_VERSATILITY_DAMAGE_DONE,
GetCombatRatingBonus = GetCombatRatingBonus,
GetVersatilityBonus = GetVersatilityBonus,
},
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("COMBAT_RATING_UPDATE")
end,
})
ConditionCategory:RegisterCondition(16, "AVOIDANCE", {
text = STAT_AVOIDANCE,
min = 0,
range = 10,
step = 0.1,
formatter = TMW.C.Formatter.PERCENT,
unit = PLAYER,
icon = "Interface\\Icons\\spell_shadow_shadowward",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetAvoidance() c.Operator c.Level]],
Env = {
GetAvoidance = GetAvoidance,
},
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("AVOIDANCE_UPDATE")
end,
})
ConditionCategory:RegisterSpacer(30)
local UnitAttackPower = UnitAttackPower
ConditionCategory:RegisterCondition(30.5, "MELEEAP", {
text = STAT_ATTACK_POWER,
range = 5000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\INV_Sword_04",
tcoords = CNDT.COMMON.standardtcoords,
Env = {
MELEEAP_UnitAttackPower = function(unit)
local base, pos, neg = UnitAttackPower(unit)
return base + pos + neg
end,
},
funcstr = [[MELEEAP_UnitAttackPower("player") c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("UNIT_ATTACK_POWER", "player")
end,
})
if MAX_SPELL_SCHOOLS ~= 7 then
TMW:Error("MAX_SPELL_SCHOOLS has changed, so the spell school dependent conditions need updating")
end
local GetSpellBonusDamage = GetSpellBonusDamage
ConditionCategory:RegisterCondition(31, "SPELLDMG", {
text = STAT_SPELLPOWER,
range = 5000,
unit = PLAYER,
formatter = TMW.C.Formatter.COMMANUMBER,
icon = "Interface\\Icons\\spell_fire_flamebolt",
tcoords = CNDT.COMMON.standardtcoords,
Env = {
SPELLDMG_GetSpellBonusDamage = function()
return min(
GetSpellBonusDamage(2),
GetSpellBonusDamage(3),
GetSpellBonusDamage(4),
GetSpellBonusDamage(5),
GetSpellBonusDamage(6),
GetSpellBonusDamage(7)
)
end,
},
funcstr = [[SPELLDMG_GetSpellBonusDamage() c.Operator c.Level]],
events = function(ConditionObject, c)
return
ConditionObject:GenerateNormalEventString("PLAYER_DAMAGE_DONE_MODS"),
ConditionObject:GenerateNormalEventString("SPELL_POWER_CHANGED") --TMW.ISMOP
end,
})
Env.GetManaRegen = GetManaRegen
ConditionCategory:RegisterCondition(35, "MANAREGEN", {
text = MANA_REGEN,
range = 1000/5,
unit = PLAYER,
texttable = function(k) return format(L["MP5"], TMW.C.Formatter.COMMANUMBER:Format(k)*5) end,
icon = "Interface\\Icons\\spell_magic_managain",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[GetManaRegen() c.Operator c.Level]], -- anyone know of an event that can be reliably listened to to get this?
})
ConditionCategory:RegisterCondition(36, "MANAREGENCOMBAT", {
text = MANA_REGEN_COMBAT,
range = 1000/5,
unit = PLAYER,
texttable = function(k) return format(L["MP5"], TMW.C.Formatter.COMMANUMBER:Format(k)*5) end,
icon = "Interface\\Icons\\spell_frost_summonwaterelemental",
tcoords = CNDT.COMMON.standardtcoords,
funcstr = [[select(2, GetManaRegen()) c.Operator c.Level]],
})
| 0 | 0.844976 | 1 | 0.844976 | game-dev | MEDIA | 0.728648 | game-dev,desktop-app | 0.646419 | 1 | 0.646419 |
ruby/ruby-bench | 2,263 | benchmarks/lee/bench/sequential.rb | # This benchmark solves the testBoard.
require 'benchmark/ips'
require_relative '../lib/lee'
board = Lee.read_board(File.expand_path('../inputs/testBoard.txt', __dir__))
def expand(board, obstructed, depth, route)
start_point = route.a
end_point = route.b
# From benchmarking - we're better of allocating a new cost-matrix each time rather than zeroing
cost = Lee::Matrix.new(board.height, board.width)
cost[start_point.y, start_point.x] = 1
wavefront = [start_point]
loop do
new_wavefront = []
wavefront.each do |point|
point_cost = cost[point.y, point.x]
Lee.adjacent(board, point).each do |adjacent|
next if obstructed[adjacent.y, adjacent.x] == 1 && adjacent != route.b
current_cost = cost[adjacent.y, adjacent.x]
new_cost = point_cost + Lee.cost(depth[adjacent.y, adjacent.x])
if current_cost == 0 || new_cost < current_cost
cost[adjacent.y, adjacent.x] = new_cost
new_wavefront.push adjacent
end
end
end
raise 'stuck' if new_wavefront.empty?
break if cost[end_point.y, end_point.x] > 0 && cost[end_point.y, end_point.x] < new_wavefront.map { |marked| cost[marked.y, marked.x] }.min
wavefront = new_wavefront
end
cost
end
def solve(board, route, cost)
start_point = route.b
end_point = route.a
solution = [start_point]
loop do
adjacent = Lee.adjacent(board, solution.last)
lowest_cost = adjacent
.reject { |a| cost[a.y, a.x].zero? }
.min_by { |a| cost[a.y, a.x] }
solution.push lowest_cost
break if lowest_cost == end_point
end
solution.reverse
end
def lay(depth, solution)
solution.each do |point|
depth[point.y, point.x] += 1
end
end
def solve_board(board)
obstructed = Lee::Matrix.new(board.height, board.width)
board.pads.each do |pad|
obstructed[pad.y, pad.x] = 1
end
depth = Lee::Matrix.new(board.height, board.width)
solutions = {}
board.routes.each do |route|
cost = expand(board, obstructed, depth, route)
solution = solve(board, route, cost)
lay depth, solution
solutions[route] = solution
end
solutions
end
Benchmark.ips do |x|
x.time = 30
x.warmup = 30
x.report('testBoard') do
solve_board(board)
end
end
| 0 | 0.870392 | 1 | 0.870392 | game-dev | MEDIA | 0.36109 | game-dev | 0.899169 | 1 | 0.899169 |
goldeneye-source/ges-code | 54,379 | game/server/ai_behavior_assault.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "ai_behavior_assault.h"
#include "ai_navigator.h"
#include "ai_memory.h"
#include "ai_squad.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar ai_debug_assault("ai_debug_assault", "0");
BEGIN_DATADESC( CRallyPoint )
DEFINE_KEYFIELD( m_AssaultPointName, FIELD_STRING, "assaultpoint" ),
DEFINE_KEYFIELD( m_RallySequenceName, FIELD_STRING, "rallysequence" ),
DEFINE_KEYFIELD( m_flAssaultDelay, FIELD_FLOAT, "assaultdelay" ),
DEFINE_KEYFIELD( m_iPriority, FIELD_INTEGER, "priority" ),
DEFINE_KEYFIELD( m_iStrictness, FIELD_INTEGER, "strict" ),
DEFINE_KEYFIELD( m_bForceCrouch, FIELD_BOOLEAN, "forcecrouch" ),
DEFINE_KEYFIELD( m_bIsUrgent, FIELD_BOOLEAN, "urgent" ),
DEFINE_FIELD( m_hLockedBy, FIELD_EHANDLE ),
DEFINE_FIELD( m_sExclusivity, FIELD_SHORT ),
DEFINE_OUTPUT( m_OnArrival, "OnArrival" ),
END_DATADESC();
//---------------------------------------------------------
// Purpose: Communicate exclusivity
//---------------------------------------------------------
int CRallyPoint::DrawDebugTextOverlays()
{
int offset;
offset = BaseClass::DrawDebugTextOverlays();
if ( (m_debugOverlays & OVERLAY_TEXT_BIT) )
{
switch( m_sExclusivity )
{
case RALLY_EXCLUSIVE_NOT_EVALUATED:
EntityText( offset, "Exclusive: Not Evaluated", 0 );
break;
case RALLY_EXCLUSIVE_YES:
EntityText( offset, "Exclusive: YES", 0 );
break;
case RALLY_EXCLUSIVE_NO:
EntityText( offset, "Exclusive: NO", 0 );
break;
default:
EntityText( offset, "Exclusive: !?INVALID?!", 0 );
break;
}
offset++;
if( IsLocked() )
EntityText( offset, "LOCKED.", 0 );
else
EntityText( offset, "Available", 0 );
offset++;
}
return offset;
}
//---------------------------------------------------------
// Purpose: If a rally point is 'exclusive' that means that
// anytime an NPC is anywhere on the assault chain that
// begins with this rally point, the assault is considered
// 'exclusive' and no other NPCs will be allowed to use it
// until the current NPC clears the entire assault chain
// or dies.
//
// If exclusivity has not been determined the first time
// this function is called, it will be computed and cached
//---------------------------------------------------------
bool CRallyPoint::IsExclusive()
{
#ifndef HL2_EPISODIC // IF NOT EPISODIC
// This 'exclusivity' concept is new to EP2. We're only willing to
// risk causing problems in EP1, so emulate the old behavior if
// we are not EPISODIC. We must do this by setting m_sExclusivity
// so that ent_text will properly report the state.
m_sExclusivity = RALLY_EXCLUSIVE_NO;
#else
if( m_sExclusivity == RALLY_EXCLUSIVE_NOT_EVALUATED )
{
// We need to evaluate! Walk the chain of assault points
// and if *ANY* assault points on this assault chain
// are set to Never Time Out then set this rally point to
// be exclusive to stop other NPC's walking down the chain
// and ending up clumped up at the infinite rally point.
CAssaultPoint *pAssaultEnt = (CAssaultPoint *)gEntList.FindEntityByName( NULL, m_AssaultPointName );
if( !pAssaultEnt )
{
// Well, this is awkward. Leave it up to other assault code to tattle on the missing assault point.
// We will just assume this assault is not exclusive.
m_sExclusivity = RALLY_EXCLUSIVE_NO;
return false;
}
// Otherwise, we start by assuming this assault chain is not exclusive.
m_sExclusivity = RALLY_EXCLUSIVE_NO;
if( pAssaultEnt )
{
CAssaultPoint *pFirstAssaultEnt = pAssaultEnt; //some assault chains are circularly linked
do
{
if( pAssaultEnt->m_bNeverTimeout )
{
// We found a never timeout assault point! That makes this whole chain exclusive.
m_sExclusivity = RALLY_EXCLUSIVE_YES;
break;
}
pAssaultEnt = (CAssaultPoint *)gEntList.FindEntityByName( NULL, pAssaultEnt->m_NextAssaultPointName );
} while( (pAssaultEnt != NULL) && (pAssaultEnt != pFirstAssaultEnt) );
}
}
#endif// HL2_EPISODIC
return (m_sExclusivity == RALLY_EXCLUSIVE_YES);
}
BEGIN_DATADESC( CAssaultPoint )
DEFINE_KEYFIELD( m_AssaultHintGroup, FIELD_STRING, "assaultgroup" ),
DEFINE_KEYFIELD( m_NextAssaultPointName, FIELD_STRING, "nextassaultpoint" ),
DEFINE_KEYFIELD( m_flAssaultTimeout, FIELD_FLOAT, "assaulttimeout" ),
DEFINE_KEYFIELD( m_bClearOnContact, FIELD_BOOLEAN, "clearoncontact" ),
DEFINE_KEYFIELD( m_bAllowDiversion, FIELD_BOOLEAN, "allowdiversion" ),
DEFINE_KEYFIELD( m_flAllowDiversionRadius, FIELD_FLOAT, "allowdiversionradius" ),
DEFINE_KEYFIELD( m_bNeverTimeout, FIELD_BOOLEAN, "nevertimeout" ),
DEFINE_KEYFIELD( m_iStrictness, FIELD_INTEGER, "strict" ),
DEFINE_KEYFIELD( m_bForceCrouch, FIELD_BOOLEAN, "forcecrouch" ),
DEFINE_KEYFIELD( m_bIsUrgent, FIELD_BOOLEAN, "urgent" ),
DEFINE_FIELD( m_bInputForcedClear, FIELD_BOOLEAN ),
DEFINE_KEYFIELD( m_flAssaultPointTolerance, FIELD_FLOAT, "assaulttolerance" ),
DEFINE_FIELD( m_flTimeLastUsed, FIELD_TIME ),
// Inputs
DEFINE_INPUTFUNC( FIELD_BOOLEAN, "SetClearOnContact", InputSetClearOnContact ),
DEFINE_INPUTFUNC( FIELD_BOOLEAN, "SetAllowDiversion", InputSetAllowDiversion ),
DEFINE_INPUTFUNC( FIELD_BOOLEAN, "SetForceClear", InputSetForceClear ),
// Outputs
DEFINE_OUTPUT( m_OnArrival, "OnArrival" ),
DEFINE_OUTPUT( m_OnAssaultClear, "OnAssaultClear" ),
END_DATADESC();
LINK_ENTITY_TO_CLASS( assault_rallypoint, CRallyPoint ); // just a copy of info_target for now
LINK_ENTITY_TO_CLASS( assault_assaultpoint, CAssaultPoint ); // has its own class because it needs the entity I/O
BEGIN_DATADESC( CAI_AssaultBehavior )
DEFINE_FIELD( m_hAssaultPoint, FIELD_EHANDLE ),
DEFINE_FIELD( m_hRallyPoint, FIELD_EHANDLE ),
DEFINE_FIELD( m_AssaultCue, FIELD_INTEGER ),
DEFINE_FIELD( m_ReceivedAssaultCue, FIELD_INTEGER ),
DEFINE_FIELD( m_bHitRallyPoint, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bHitAssaultPoint, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bDiverting, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flLastSawAnEnemyAt, FIELD_FLOAT ),
DEFINE_FIELD( m_flTimeDeferScheduleSelection, FIELD_TIME ),
DEFINE_FIELD( m_AssaultPointName, FIELD_STRING )
END_DATADESC();
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::CanRunAScriptedNPCInteraction( bool bForced )
{
if ( m_AssaultCue == CUE_NO_ASSAULT )
{
// It's OK with the assault behavior, so leave it up to the base class.
return BaseClass::CanRunAScriptedNPCInteraction( bForced );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CAI_AssaultBehavior::CAI_AssaultBehavior()
{
m_AssaultCue = CUE_NO_ASSAULT;
}
//-----------------------------------------------------------------------------
// Purpose: Draw any text overlays
// Input : Previous text offset from the top
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CAI_AssaultBehavior::DrawDebugTextOverlays( int text_offset )
{
char tempstr[ 512 ];
int offset;
offset = BaseClass::DrawDebugTextOverlays( text_offset );
if ( GetOuter()->m_debugOverlays & OVERLAY_TEXT_BIT )
{
Q_snprintf( tempstr, sizeof(tempstr), "Assault Point: %s %s", STRING( m_AssaultPointName ), VecToString( m_hAssaultPoint->GetAbsOrigin() ) );
GetOuter()->EntityText( offset, tempstr, 0 );
offset++;
}
return offset;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : cue -
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::ReceiveAssaultCue( AssaultCue_t cue )
{
if ( GetOuter() )
GetOuter()->ForceDecisionThink();
m_ReceivedAssaultCue = cue;
SetCondition( COND_PROVOKED );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::AssaultHasBegun()
{
if( m_AssaultCue == CUE_DONT_WAIT && IsRunning() && m_bHitRallyPoint )
{
return true;
}
return m_ReceivedAssaultCue == m_AssaultCue;
}
//-----------------------------------------------------------------------------
// Purpose: Find an assaultpoint matching the iszAssaultPointName.
// If more than one assault point of this type is found, randomly
// use any of them EXCEPT the one most recently used.
//-----------------------------------------------------------------------------
CAssaultPoint *CAI_AssaultBehavior::FindAssaultPoint( string_t iszAssaultPointName )
{
CUtlVector<CAssaultPoint*>pAssaultPoints;
CUtlVector<CAssaultPoint*>pClearAssaultPoints;
CAssaultPoint *pAssaultEnt = (CAssaultPoint *)gEntList.FindEntityByName( NULL, iszAssaultPointName );
while( pAssaultEnt != NULL )
{
pAssaultPoints.AddToTail( pAssaultEnt );
pAssaultEnt = (CAssaultPoint *)gEntList.FindEntityByName( pAssaultEnt, iszAssaultPointName );
}
// Didn't find any?!
if( pAssaultPoints.Count() < 1 )
return NULL;
// Only found one, just return it.
if( pAssaultPoints.Count() == 1 )
return pAssaultPoints[0];
// Throw out any nodes that I cannot fit my bounding box on.
for( int i = 0 ; i < pAssaultPoints.Count() ; i++ )
{
trace_t tr;
CAI_BaseNPC *pNPC = GetOuter();
CAssaultPoint *pAssaultPoint = pAssaultPoints[i];
AI_TraceHull ( pAssaultPoint->GetAbsOrigin(), pAssaultPoint->GetAbsOrigin(), pNPC->WorldAlignMins(), pNPC->WorldAlignMaxs(), MASK_SOLID, pNPC, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction == 1.0 )
{
// Copy this into the list of clear points.
pClearAssaultPoints.AddToTail(pAssaultPoint);
}
}
// Only one clear assault point left!
if( pClearAssaultPoints.Count() == 1 )
return pClearAssaultPoints[0];
// NONE left. Just return a random assault point, knowing that it's blocked. This is the old behavior, anyway.
if( pClearAssaultPoints.Count() < 1 )
return pAssaultPoints[ random->RandomInt(0, (pAssaultPoints.Count() - 1)) ];
// We found several! First throw out the one most recently used.
// This prevents picking the same point at this branch twice in a row.
float flMostRecentTime = -1.0f; // Impossibly old
int iMostRecentIndex = -1;
for( int i = 0 ; i < pClearAssaultPoints.Count() ; i++ )
{
if( pClearAssaultPoints[i]->m_flTimeLastUsed > flMostRecentTime )
{
flMostRecentTime = pClearAssaultPoints[i]->m_flTimeLastUsed;
iMostRecentIndex = i;
}
}
Assert( iMostRecentIndex > -1 );
// Remove the most recently used
pClearAssaultPoints.Remove( iMostRecentIndex );
return pClearAssaultPoints[ random->RandomInt(0, (pClearAssaultPoints.Count() - 1)) ];
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::SetAssaultPoint( CAssaultPoint *pAssaultPoint )
{
m_hAssaultPoint = pAssaultPoint;
pAssaultPoint->m_flTimeLastUsed = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::ClearAssaultPoint( void )
{
// To announce clear means that this NPC hasn't seen any live targets in
// the assault area for the length of time the level designer has
// specified that they should be vigilant. This effectively deactivates
// the assault behavior.
// This can also be happen if an assault point has ClearOnContact set, and
// an NPC assaulting to this point has seen an enemy.
// keep track of the name of the assault point
m_AssaultPointName = m_hAssaultPoint->m_NextAssaultPointName;
// Do we need to move to another assault point?
if( m_hAssaultPoint->m_NextAssaultPointName != NULL_STRING )
{
CAssaultPoint *pNextPoint = FindAssaultPoint( m_hAssaultPoint->m_NextAssaultPointName );
if( pNextPoint )
{
SetAssaultPoint( pNextPoint );
// Send our NPC to the next assault point!
m_bHitAssaultPoint = false;
return;
}
else
{
DevMsg("**ERROR: Can't find next assault point: %s\n", STRING(m_hAssaultPoint->m_NextAssaultPointName) );
// Bomb out of assault behavior.
m_AssaultCue = CUE_NO_ASSAULT;
ClearSchedule( "Can't find next assault point" );
return;
}
}
// Just set the cue back to NO_ASSAULT. This disables the behavior.
m_AssaultCue = CUE_NO_ASSAULT;
// Exclusive or not, we unlock here. The assault is done.
UnlockRallyPoint();
// If this assault behavior has changed the NPC's hint group,
// slam that NPC's hint group back to null.
// !!!TODO: if the NPC had a different hint group before the
// assault began, we're slamming that, too! We might want
// to cache it off if this becomes a problem (sjb)
if( m_hAssaultPoint->m_AssaultHintGroup != NULL_STRING )
{
GetOuter()->SetHintGroup( NULL_STRING );
}
m_hAssaultPoint->m_OnAssaultClear.FireOutput( GetOuter(), GetOuter(), 0 );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::OnHitAssaultPoint( void )
{
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_HIT_ASSAULT_POINT );
m_bHitAssaultPoint = true;
m_hAssaultPoint->m_OnArrival.FireOutput( GetOuter(), m_hAssaultPoint, 0 );
// Set the assault hint group
if( m_hAssaultPoint->m_AssaultHintGroup != NULL_STRING )
{
SetHintGroup( m_hAssaultPoint->m_AssaultHintGroup );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::GatherConditions( void )
{
BaseClass::GatherConditions();
// If this NPC is moving towards an assault point which
// a) Has a Next Assault Point, and
// b) Is flagged to Clear On Arrival,
// then hit and clear the assault point (fire all entity I/O) and move on to the next one without
// interrupting the NPC's schedule. This provides a more fluid movement from point to point.
if( IsCurSchedule( SCHED_MOVE_TO_ASSAULT_POINT ) && hl2_episodic.GetBool() )
{
if( m_hAssaultPoint && m_hAssaultPoint->HasSpawnFlags(SF_ASSAULTPOINT_CLEARONARRIVAL) && m_hAssaultPoint->m_NextAssaultPointName != NULL_STRING )
{
float flDist = GetAbsOrigin().DistTo( m_hAssaultPoint->GetAbsOrigin() );
if( flDist <= GetOuter()->GetMotor()->MinStoppingDist() )
{
OnHitAssaultPoint();
ClearAssaultPoint();
AI_NavGoal_t goal( m_hAssaultPoint->GetAbsOrigin() );
goal.pTarget = m_hAssaultPoint;
if ( GetNavigator()->SetGoal( goal ) == false )
{
TaskFail( "Can't refresh assault path" );
}
}
}
}
if ( IsForcingCrouch() && GetOuter()->IsCrouching() )
{
ClearCondition( COND_HEAR_BULLET_IMPACT );
}
if( OnStrictAssault() )
{
// Don't get distracted. Die trying if you have to.
ClearCondition( COND_HEAR_DANGER );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_RANGE_ATTACK1:
BaseClass::StartTask( pTask );
break;
case TASK_ASSAULT_DEFER_SCHEDULE_SELECTION:
m_flTimeDeferScheduleSelection = gpGlobals->curtime + pTask->flTaskData;
TaskComplete();
break;
case TASK_ASSAULT_MOVE_AWAY_PATH:
break;
case TASK_ANNOUNCE_CLEAR:
{
// If we're at an assault point that can never be cleared, keep waiting forever (if it's the last point in the assault)
if ( m_hAssaultPoint &&
!m_hAssaultPoint->HasSpawnFlags( SF_ASSAULTPOINT_CLEARONARRIVAL ) &&
m_hAssaultPoint->m_bNeverTimeout &&
m_hAssaultPoint->m_NextAssaultPointName == NULL_STRING )
{
TaskComplete();
return;
}
ClearAssaultPoint();
TaskComplete();
}
break;
case TASK_WAIT_ASSAULT_DELAY:
{
if( m_hRallyPoint )
{
GetOuter()->SetWait( m_hRallyPoint->m_flAssaultDelay );
}
else
{
TaskComplete();
}
}
break;
case TASK_AWAIT_ASSAULT_TIMEOUT:
// Maintain vigil for as long as the level designer has asked. Wait
// and look for targets.
GetOuter()->SetWait( m_hAssaultPoint->m_flAssaultTimeout );
break;
case TASK_GET_PATH_TO_RALLY_POINT:
{
AI_NavGoal_t goal( m_hRallyPoint->GetAbsOrigin() );
goal.pTarget = m_hRallyPoint;
if ( GetNavigator()->SetGoal( goal ) == false )
{
// Try and get as close as possible otherwise
AI_NavGoal_t nearGoal( GOALTYPE_LOCATION_NEAREST_NODE, m_hRallyPoint->GetAbsOrigin(), AIN_DEF_ACTIVITY, 256 );
if ( GetNavigator()->SetGoal( nearGoal, AIN_CLEAR_PREVIOUS_STATE ) )
{
//FIXME: HACK! The internal pathfinding is setting this without our consent, so override it!
ClearCondition( COND_TASK_FAILED );
GetNavigator()->SetArrivalDirection( m_hRallyPoint->GetAbsAngles() );
TaskComplete();
return;
}
}
GetNavigator()->SetArrivalDirection( m_hRallyPoint->GetAbsAngles() );
}
break;
case TASK_FACE_RALLY_POINT:
{
UpdateForceCrouch();
GetMotor()->SetIdealYaw( m_hRallyPoint->GetAbsAngles().y );
GetOuter()->SetTurnActivity();
}
break;
case TASK_GET_PATH_TO_ASSAULT_POINT:
{
AI_NavGoal_t goal( m_hAssaultPoint->GetAbsOrigin() );
goal.pTarget = m_hAssaultPoint;
if ( GetNavigator()->SetGoal( goal ) == false )
{
// Try and get as close as possible otherwise
AI_NavGoal_t nearGoal( GOALTYPE_LOCATION_NEAREST_NODE, m_hAssaultPoint->GetAbsOrigin(), AIN_DEF_ACTIVITY, 256 );
if ( GetNavigator()->SetGoal( nearGoal, AIN_CLEAR_PREVIOUS_STATE ) )
{
//FIXME: HACK! The internal pathfinding is setting this without our consent, so override it!
ClearCondition( COND_TASK_FAILED );
GetNavigator()->SetArrivalDirection( m_hAssaultPoint->GetAbsAngles() );
TaskComplete();
return;
}
}
GetNavigator()->SetArrivalDirection( m_hAssaultPoint->GetAbsAngles() );
}
break;
case TASK_FACE_ASSAULT_POINT:
{
UpdateForceCrouch();
if( HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
// If I can already fight when I arrive, don't bother running any facing code. Let
// The combat AI do that. Turning here will only make the NPC look dumb in a combat
// situation because it will take time to turn before attacking.
TaskComplete();
}
else
{
GetMotor()->SetIdealYaw( m_hAssaultPoint->GetAbsAngles().y );
GetOuter()->SetTurnActivity();
}
}
break;
case TASK_HIT_ASSAULT_POINT:
OnHitAssaultPoint();
TaskComplete();
break;
case TASK_HIT_RALLY_POINT:
// Once we're stading on it and facing the correct direction,
// we have arrived at rally point.
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_HIT_RALLY_POINT );
m_bHitRallyPoint = true;
m_hRallyPoint->m_OnArrival.FireOutput( GetOuter(), m_hRallyPoint, 0 );
TaskComplete();
break;
case TASK_AWAIT_CUE:
if( PollAssaultCue() )
{
TaskComplete();
}
else
{
// Don't do anything if we've been told to crouch
if ( IsForcingCrouch() )
break;
else if( m_hRallyPoint->m_RallySequenceName != NULL_STRING )
{
// The cue hasn't been given yet, so set to the rally sequence.
int sequence = GetOuter()->LookupSequence( STRING( m_hRallyPoint->m_RallySequenceName ) );
if( sequence != -1 )
{
GetOuter()->ResetSequence( sequence );
GetOuter()->SetIdealActivity( ACT_DO_NOT_DISTURB );
}
}
else
{
// Only chain this task if I'm not playing a custom animation
if( GetOuter()->GetEnemy() )
{
ChainStartTask( TASK_FACE_ENEMY, 0 );
}
}
}
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_WAIT_ASSAULT_DELAY:
case TASK_AWAIT_ASSAULT_TIMEOUT:
if ( m_hAssaultPoint )
{
if ( m_hAssaultPoint->m_bInputForcedClear || (m_hAssaultPoint->m_bClearOnContact && HasCondition( COND_SEE_ENEMY )) )
{
// If we're on an assault that should clear on contact, clear when we see an enemy
TaskComplete();
}
}
if( GetOuter()->IsWaitFinished() && ( pTask->iTask == TASK_WAIT_ASSAULT_DELAY || !m_hAssaultPoint->m_bNeverTimeout ) )
{
TaskComplete();
}
break;
case TASK_FACE_RALLY_POINT:
case TASK_FACE_ASSAULT_POINT:
GetMotor()->UpdateYaw();
if( HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
// Out early if the NPC can attack.
TaskComplete();
}
if ( GetOuter()->FacingIdeal() )
{
TaskComplete();
}
break;
case TASK_AWAIT_CUE:
// If we've lost our rally point, abort
if ( !m_hRallyPoint )
{
TaskFail("No rally point.");
break;
}
if( PollAssaultCue() )
{
TaskComplete();
}
if ( IsForcingCrouch() )
break;
if( GetOuter()->GetEnemy() && m_hRallyPoint->m_RallySequenceName == NULL_STRING && !HasCondition(COND_ENEMY_OCCLUDED) )
{
// I have an enemy and I'm NOT playing a custom animation.
ChainRunTask( TASK_FACE_ENEMY, 0 );
}
break;
case TASK_WAIT_FOR_MOVEMENT:
if ( ai_debug_assault.GetBool() )
{
if ( IsCurSchedule( SCHED_MOVE_TO_ASSAULT_POINT ) )
{
NDebugOverlay::Line( WorldSpaceCenter(), GetNavigator()->GetGoalPos(), 255,0,0, true,0.1);
NDebugOverlay::Box( GetNavigator()->GetGoalPos(), -Vector(10,10,10), Vector(10,10,10), 255,0,0, 8, 0.1 );
}
else if ( IsCurSchedule( SCHED_MOVE_TO_RALLY_POINT ) )
{
NDebugOverlay::Line( WorldSpaceCenter(), GetNavigator()->GetGoalPos(), 0,255,0, true,0.1);
NDebugOverlay::Box( GetNavigator()->GetGoalPos(), -Vector(10,10,10), Vector(10,10,10), 0,255,0, 8, 0.1 );
}
}
if ( m_hAssaultPoint && (m_hAssaultPoint->m_bInputForcedClear || (m_hAssaultPoint->m_bClearOnContact && HasCondition( COND_SEE_ENEMY ))) )
{
DevMsg( "Assault Cleared due to Contact or Input!\n" );
ClearAssaultPoint();
TaskComplete();
return;
}
if ( ( ( !GetOuter()->DidChooseEnemy() && gpGlobals->curtime - GetOuter()->GetTimeEnemyAcquired() > 1 ) || !GetOuter()->GetEnemy() ) )
{
CBaseEntity *pNewEnemy = GetOuter()->BestEnemy();
if( pNewEnemy != NULL && pNewEnemy != GetOuter()->GetEnemy() )
{
GetOuter()->SetEnemy( pNewEnemy );
GetOuter()->SetState( NPC_STATE_COMBAT );
}
}
BaseClass::RunTask( pTask );
break;
default:
BaseClass::RunTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CRallyPoint *CAI_AssaultBehavior::FindBestRallyPointInRadius( const Vector &vecCenter, float flRadius )
{
VPROF_BUDGET( "CAI_AssaultBehavior::FindBestRallyPointInRadius", VPROF_BUDGETGROUP_NPCS );
const int RALLY_SEARCH_ENTS = 30;
CBaseEntity *pEntities[RALLY_SEARCH_ENTS];
int iNumEntities = UTIL_EntitiesInSphere( pEntities, RALLY_SEARCH_ENTS, vecCenter, flRadius, 0 );
CRallyPoint *pBest = NULL;
int iBestPriority = -1;
for ( int i = 0; i < iNumEntities; i++ )
{
CRallyPoint *pRallyEnt = dynamic_cast<CRallyPoint *>(pEntities[i]);
if( pRallyEnt )
{
if( !pRallyEnt->IsLocked() )
{
// Consider this point.
if( pRallyEnt->m_iPriority > iBestPriority )
{
pBest = pRallyEnt;
iBestPriority = pRallyEnt->m_iPriority;
}
}
}
}
return pBest;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint )
{
CBaseEntity *pCuePoint = NULL;
float flTolerance = 0.0f;
if( m_bHitRallyPoint && !m_bHitAssaultPoint && !AssaultHasBegun() )
{
if( m_hRallyPoint != NULL )
{
pCuePoint = m_hRallyPoint;
flTolerance = CUE_POINT_TOLERANCE;
}
}
else if( m_bHitAssaultPoint )
{
if( m_hAssaultPoint != NULL )
{
pCuePoint = m_hAssaultPoint;
flTolerance = m_hAssaultPoint->m_flAssaultPointTolerance;
}
}
if ( pCuePoint && (vLocation - pCuePoint->GetAbsOrigin()).Length2DSqr() > Square( flTolerance - 0.1 ) )
return false;
return BaseClass::IsValidShootPosition( vLocation, pNode, pHint );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CAI_AssaultBehavior::GetMaxTacticalLateralMovement( void )
{
return CUE_POINT_TOLERANCE - 0.1;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::UpdateOnRemove()
{
// Ignore exclusivity. Our NPC just died.
UnlockRallyPoint();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::OnStrictAssault( void )
{
return (m_hAssaultPoint && m_hAssaultPoint->m_iStrictness);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::UpdateForceCrouch( void )
{
if ( IsForcingCrouch() )
{
// Only force crouch when we're near the point we're supposed to crouch at
float flDistanceToTargetSqr = GetOuter()->GetAbsOrigin().DistToSqr( AssaultHasBegun() ? m_hAssaultPoint->GetAbsOrigin() : m_hRallyPoint->GetAbsOrigin() );
if ( flDistanceToTargetSqr < (64*64) )
{
GetOuter()->ForceCrouch();
}
else
{
GetOuter()->ClearForceCrouch();
}
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::IsForcingCrouch( void )
{
if ( AssaultHasBegun() )
return (m_hAssaultPoint && m_hAssaultPoint->m_bForceCrouch);
return (m_hRallyPoint && m_hRallyPoint->m_bForceCrouch);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::IsUrgent( void )
{
if ( AssaultHasBegun() )
return (m_hAssaultPoint && m_hAssaultPoint->m_bIsUrgent);
return (m_hRallyPoint && m_hRallyPoint->m_bIsUrgent);
}
//-----------------------------------------------------------------------------
// Purpose: Unlock any rally points the behavior is currently locking
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::UnlockRallyPoint( void )
{
CAI_AssaultBehavior *pBehavior;
if ( GetOuter()->GetBehavior( &pBehavior ) )
{
if( pBehavior->m_hRallyPoint )
{
pBehavior->m_hRallyPoint->Unlock( GetOuter() );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pRallyPoint -
// assaultcue -
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::SetParameters( CBaseEntity *pRallyEnt, AssaultCue_t assaultcue )
{
VPROF_BUDGET( "CAI_AssaultBehavior::SetParameters", VPROF_BUDGETGROUP_NPCS );
// Clean up any soon to be dangling rally points
UnlockRallyPoint();
// Firstly, find a rally point.
CRallyPoint *pRallyPoint = dynamic_cast<CRallyPoint *>(pRallyEnt);
if( pRallyPoint )
{
if( !pRallyPoint->IsLocked() )
{
// Claim it.
m_hRallyPoint = pRallyPoint;
m_hRallyPoint->Lock( GetOuter() );
m_AssaultCue = assaultcue;
InitializeBehavior();
return;
}
else
{
DevMsg("**ERROR: Specified a rally point that is LOCKED!\n" );
}
}
else
{
DevMsg("**ERROR: Bad RallyPoint in SetParameters\n" );
// Bomb out of assault behavior.
m_AssaultCue = CUE_NO_ASSAULT;
ClearSchedule( "Bad rally point" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : rallypointname -
// assaultcue -
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::SetParameters( string_t rallypointname, AssaultCue_t assaultcue, int rallySelectMethod )
{
VPROF_BUDGET( "CAI_AssaultBehavior::SetParameters", VPROF_BUDGETGROUP_NPCS );
// Clean up any soon to be dangling rally points
UnlockRallyPoint();
// Firstly, find a rally point.
CRallyPoint *pRallyEnt = dynamic_cast<CRallyPoint *>(gEntList.FindEntityByName( NULL, rallypointname ) );
CRallyPoint *pBest = NULL;
int iBestPriority = -1;
switch( rallySelectMethod )
{
case RALLY_POINT_SELECT_DEFAULT:
{
while( pRallyEnt )
{
if( !pRallyEnt->IsLocked() )
{
// Consider this point.
if( pRallyEnt->m_iPriority > iBestPriority )
{
// This point is higher priority. I must take it.
pBest = pRallyEnt;
iBestPriority = pRallyEnt->m_iPriority;
}
else if ( pRallyEnt->m_iPriority == iBestPriority )
{
// This point is the same priority as my current best.
// I must take it if it is closer.
Vector vecStart = GetOuter()->GetAbsOrigin();
float flNewDist, flBestDist;
flNewDist = ( pRallyEnt->GetAbsOrigin() - vecStart ).LengthSqr();
flBestDist = ( pBest->GetAbsOrigin() - vecStart ).LengthSqr();
if( flNewDist < flBestDist )
{
// Priority is already identical. Just take this point.
pBest = pRallyEnt;
}
}
}
pRallyEnt = dynamic_cast<CRallyPoint *>(gEntList.FindEntityByName( pRallyEnt, rallypointname, NULL ) );
}
}
break;
case RALLY_POINT_SELECT_RANDOM:
{
// Gather all available points into a utilvector, then pick one at random.
CUtlVector<CRallyPoint *> rallyPoints; // List of rally points that are available to choose from.
while( pRallyEnt )
{
if( !pRallyEnt->IsLocked() )
{
rallyPoints.AddToTail( pRallyEnt );
}
pRallyEnt = dynamic_cast<CRallyPoint *>(gEntList.FindEntityByName( pRallyEnt, rallypointname ) );
}
if( rallyPoints.Count() > 0 )
{
pBest = rallyPoints[ random->RandomInt(0, rallyPoints.Count()- 1) ];
}
}
break;
default:
DevMsg( "ERROR: INVALID RALLY POINT SELECTION METHOD. Assault will not function.\n");
break;
}
if( !pBest )
{
DevMsg("%s Didn't find a best rally point!\n", GetOuter()->GetEntityName().ToCStr() );
return;
}
pBest->Lock( GetOuter() );
m_hRallyPoint = pBest;
if( !m_hRallyPoint )
{
DevMsg("**ERROR: Can't find a rally point named '%s'\n", STRING( rallypointname ));
// Bomb out of assault behavior.
m_AssaultCue = CUE_NO_ASSAULT;
ClearSchedule( "Can't find rally point" );
return;
}
m_AssaultCue = assaultcue;
InitializeBehavior();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::InitializeBehavior()
{
// initialize the variables that track whether the NPC has reached (hit)
// his rally and assault points already. Be advised, having hit the point
// only means you have been to it at some point. Doesn't mean you're standing
// there still. Mainly used to understand which 'phase' of the assault an NPC
// is in.
m_bHitRallyPoint = false;
m_bHitAssaultPoint = false;
m_hAssaultPoint = 0;
m_bDiverting = false;
m_flLastSawAnEnemyAt = 0;
// Also reset the status of externally received assault cues
m_ReceivedAssaultCue = CUE_NO_ASSAULT;
CAssaultPoint *pAssaultEnt = FindAssaultPoint( m_hRallyPoint->m_AssaultPointName );
if( pAssaultEnt )
{
SetAssaultPoint(pAssaultEnt);
}
else
{
DevMsg("**ERROR: Can't find any assault points named: %s\n", STRING( m_hRallyPoint->m_AssaultPointName ));
// Bomb out of assault behavior.
m_AssaultCue = CUE_NO_ASSAULT;
ClearSchedule( "Can't find assault point" );
return;
}
// Slam the NPC's schedule so that he starts picking Assault schedules right now.
ClearSchedule( "Initializing assault behavior" );
}
//-----------------------------------------------------------------------------
// Purpose: Check conditions and see if the cue to being an assault has come.
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::PollAssaultCue( void )
{
// right now, always go when the commander says.
if( m_ReceivedAssaultCue == CUE_COMMANDER )
{
return true;
}
switch( m_AssaultCue )
{
case CUE_NO_ASSAULT:
// NO_ASSAULT never ever triggers.
return false;
break;
case CUE_ENTITY_INPUT:
return m_ReceivedAssaultCue == CUE_ENTITY_INPUT;
break;
case CUE_PLAYER_GUNFIRE:
// Any gunfire will trigger this right now (sjb)
if( HasCondition( COND_HEAR_COMBAT ) )
{
return true;
}
break;
case CUE_DONT_WAIT:
// Just keep going!
m_ReceivedAssaultCue = CUE_DONT_WAIT;
return true;
break;
case CUE_COMMANDER:
// Player told me to go, so go!
return m_ReceivedAssaultCue == CUE_COMMANDER;
break;
}
return false;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::OnRestore()
{
if ( !m_hAssaultPoint || !m_hRallyPoint )
{
Disable();
NotifyChangeBehaviorStatus();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::CanSelectSchedule()
{
if ( !GetOuter()->IsInterruptable() )
return false;
if ( GetOuter()->HasCondition( COND_RECEIVED_ORDERS ) )
return false;
// We're letting other AI run for a little while because the assault AI failed recently.
if ( m_flTimeDeferScheduleSelection > gpGlobals->curtime )
return false;
// No schedule selection if no assault is being conducted.
if( m_AssaultCue == CUE_NO_ASSAULT )
return false;
if ( !m_hAssaultPoint || !m_hRallyPoint )
{
Disable();
return false;
}
// Remember when we last saw an enemy
if ( GetEnemy() )
{
m_flLastSawAnEnemyAt = gpGlobals->curtime;
}
// If we've seen an enemy in the last few seconds, and we're allowed to divert,
// let the base AI decide what I should do.
if ( IsAllowedToDivert() )
{
// Return true, but remember that we're actually allowing them to divert
// This is done because we don't want the assault behaviour to think it's finished with the assault.
m_bDiverting = true;
}
else if ( m_bDiverting )
{
// If we were diverting, provoke us to make a new schedule selection
SetCondition( COND_PROVOKED );
m_bDiverting = false;
}
// If we're diverting, let the base AI decide everything
if ( m_bDiverting )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::BeginScheduleSelection()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::EndScheduleSelection()
{
m_bHitAssaultPoint = false;
if( m_hRallyPoint != NULL )
{
if( !m_hRallyPoint->IsExclusive() )
m_bHitRallyPoint = false;
if( !hl2_episodic.GetBool() || !m_hRallyPoint->IsExclusive() || !GetOuter()->IsAlive() )
{
// Here we unlock the rally point if it is NOT EXCLUSIVE
// -OR- the Outer is DEAD. (This gives us a head-start on
// preparing the point to take new NPCs right away. Otherwise
// we have to wait two seconds until the behavior is destroyed.)
// NOTICE that the legacy (non-episodic) support calls UnlockRallyPoint
// unconditionally on EndScheduleSelection()
UnlockRallyPoint();
}
}
GetOuter()->ClearForceCrouch();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : scheduleType -
// Output : int
//-----------------------------------------------------------------------------
int CAI_AssaultBehavior::TranslateSchedule( int scheduleType )
{
switch( scheduleType )
{
case SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK:
// This nasty schedule can allow the NPC to violate their position near
// the assault point. Translate it away to something stationary. (sjb)
return SCHED_COMBAT_FACE;
break;
case SCHED_RANGE_ATTACK1:
if ( GetOuter()->GetShotRegulator()->IsInRestInterval() )
{
if ( GetOuter()->HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
GetOuter()->VacateStrategySlot();
return SCHED_COMBAT_FACE; // @TODO (toml 07-02-03): Should do something more tactically sensible
}
break;
case SCHED_MOVE_TO_WEAPON_RANGE:
case SCHED_CHASE_ENEMY:
if( m_bHitAssaultPoint )
{
return SCHED_WAIT_AND_CLEAR;
}
else
{
return SCHED_MOVE_TO_ASSAULT_POINT;
}
break;
case SCHED_HOLD_RALLY_POINT:
if( HasCondition(COND_NO_PRIMARY_AMMO) | HasCondition(COND_LOW_PRIMARY_AMMO) )
{
return SCHED_RELOAD;
}
break;
case SCHED_MOVE_TO_ASSAULT_POINT:
{
float flDist = ( m_hAssaultPoint->GetAbsOrigin() - GetAbsOrigin() ).Length();
if ( flDist <= 12.0f )
return SCHED_AT_ASSAULT_POINT;
}
break;
}
return BaseClass::TranslateSchedule( scheduleType );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::OnStartSchedule( int scheduleType )
{
if ( scheduleType == SCHED_HIDE_AND_RELOAD ) //!!!HACKHACK
{
// Dirty the assault point flag so that we return to assault point
m_bHitAssaultPoint = false;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::ClearSchedule( const char *szReason )
{
// HACKHACK: In reality, we shouldn't be clearing the schedule ever if the assault
// behavior isn't actually in charge of the NPC. Fix after ship. For now, hacking
// a fix to Grigori failing to make it over the fence of the graveyard in d1_town_02a
if ( GetOuter()->ClassMatches( "npc_monk" ) && GetOuter()->GetState() == NPC_STATE_SCRIPT )
return;
// Don't allow it if we're in a vehicle
if ( GetOuter()->IsInAVehicle() )
return;
GetOuter()->ClearSchedule( szReason );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CAI_AssaultBehavior::IsAllowedToDivert( void )
{
if ( m_hAssaultPoint && m_hAssaultPoint->m_bAllowDiversion )
{
if ( m_hAssaultPoint->m_flAllowDiversionRadius == 0.0f || (m_bHitAssaultPoint && GetEnemy() != NULL && GetEnemy()->GetAbsOrigin().DistToSqr(m_hAssaultPoint->GetAbsOrigin()) <= Square(m_hAssaultPoint->m_flAllowDiversionRadius)) )
{
if ( m_flLastSawAnEnemyAt && ((gpGlobals->curtime - m_flLastSawAnEnemyAt) < ASSAULT_DIVERSION_TIME) )
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::BuildScheduleTestBits()
{
BaseClass::BuildScheduleTestBits();
// If we're allowed to divert, add the appropriate interrupts to our movement schedules
if ( IsAllowedToDivert() )
{
if ( IsCurSchedule( SCHED_MOVE_TO_ASSAULT_POINT ) ||
IsCurSchedule( SCHED_MOVE_TO_RALLY_POINT ) ||
IsCurSchedule( SCHED_HOLD_RALLY_POINT ) )
{
GetOuter()->SetCustomInterruptCondition( COND_NEW_ENEMY );
GetOuter()->SetCustomInterruptCondition( COND_SEE_ENEMY );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_AssaultBehavior::OnScheduleChange()
{
if( IsCurSchedule(SCHED_WAIT_AND_CLEAR, false) )
{
if( m_hAssaultPoint && m_hAssaultPoint->m_bClearOnContact )
{
if( HasCondition(COND_SEE_ENEMY) )
{
ClearAssaultPoint();
}
}
}
BaseClass::OnScheduleChange();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CAI_AssaultBehavior::SelectSchedule()
{
if ( !OnStrictAssault() )
{
if( HasCondition( COND_PLAYER_PUSHING ) )
return SCHED_ASSAULT_MOVE_AWAY;
if( HasCondition( COND_HEAR_DANGER ) )
return SCHED_TAKE_COVER_FROM_BEST_SOUND;
}
if( HasCondition( COND_CAN_MELEE_ATTACK1 ) )
return SCHED_MELEE_ATTACK1;
// If you're empty, reload before trying to carry out any assault functions.
if( HasCondition( COND_NO_PRIMARY_AMMO ) )
return SCHED_RELOAD;
if( m_bHitRallyPoint && !m_bHitAssaultPoint && !AssaultHasBegun() )
{
// If I have hit my rally point, but I haven't hit my assault point yet,
// Make sure I'm still on my rally point, cause another behavior may have moved me.
// 2D check to be within 32 units of my rallypoint.
Vector vecDiff = GetAbsOrigin() - m_hRallyPoint->GetAbsOrigin();
vecDiff.z = 0.0;
if( vecDiff.LengthSqr() > Square(CUE_POINT_TOLERANCE) )
{
// Someone moved me away. Get back to rally point.
m_bHitRallyPoint = false;
return SCHED_MOVE_TO_RALLY_POINT;
}
}
else if( m_bHitAssaultPoint )
{
// Likewise. If I have hit my assault point, make sure I'm still there. Another
// behavior (hide and reload) may have moved me away.
Vector vecDiff = GetAbsOrigin() - m_hAssaultPoint->GetAbsOrigin();
vecDiff.z = 0.0;
if( vecDiff.LengthSqr() > Square(CUE_POINT_TOLERANCE) )
{
// Someone moved me away.
m_bHitAssaultPoint = false;
}
}
// Go to my rally point, unless the assault's begun.
if( !m_bHitRallyPoint && !AssaultHasBegun() )
{
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_SQUAD_ADVANCE_TO_RALLY );
return SCHED_MOVE_TO_RALLY_POINT;
}
if( !m_bHitAssaultPoint )
{
if( m_ReceivedAssaultCue == m_AssaultCue || m_ReceivedAssaultCue == CUE_COMMANDER || m_AssaultCue == CUE_DONT_WAIT )
{
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_SQUAD_ADVANCE_TO_ASSAULT );
if ( m_hRallyPoint && !m_hRallyPoint->IsExclusive() )
{
// If this assault chain is not exclusive, then free up the rallypoint so that others can follow me
// Otherwise, we do not unlock this rally point until we are FINISHED or DEAD. It's exclusively our chain of assault
UnlockRallyPoint();// Here we go! Free up the rally point since I'm moving to assault.
}
if ( !UpdateForceCrouch() )
{
GetOuter()->ClearForceCrouch();
}
return SCHED_MOVE_TO_ASSAULT_POINT;
}
else if( HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
return SCHED_RANGE_ATTACK1;
}
else if( HasCondition( COND_NO_PRIMARY_AMMO ) )
{
// Don't run off to reload.
return SCHED_RELOAD;
}
else if( HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE ) )
{
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_UNDER_ATTACK );
return SCHED_ALERT_FACE;
}
else if( GetOuter()->GetEnemy() && !HasCondition( COND_CAN_RANGE_ATTACK1 ) && !HasCondition( COND_CAN_RANGE_ATTACK2) && !HasCondition(COND_ENEMY_OCCLUDED) )
{
return SCHED_COMBAT_FACE;
}
else
{
UpdateForceCrouch();
return SCHED_HOLD_RALLY_POINT;
}
}
if( HasCondition( COND_NO_PRIMARY_AMMO ) )
{
GetOuter()->SpeakSentence( ASSAULT_SENTENCE_COVER_NO_AMMO );
return SCHED_HIDE_AND_RELOAD;
}
if( m_hAssaultPoint->HasSpawnFlags( SF_ASSAULTPOINT_CLEARONARRIVAL ) )
{
return SCHED_CLEAR_ASSAULT_POINT;
}
if ( (!GetEnemy() || HasCondition(COND_ENEMY_OCCLUDED)) && !GetOuter()->HasConditionsToInterruptSchedule( SCHED_WAIT_AND_CLEAR ) )
{
// Don't have an enemy. Just keep an eye on things.
return SCHED_WAIT_AND_CLEAR;
}
if ( OnStrictAssault() )
{
// Don't allow the base class to select a schedule cause it will probably move the NPC.
if( !HasCondition(COND_CAN_RANGE_ATTACK1) &&
!HasCondition(COND_CAN_RANGE_ATTACK2) &&
!HasCondition(COND_CAN_MELEE_ATTACK1) &&
!HasCondition(COND_CAN_MELEE_ATTACK2) &&
!HasCondition(COND_TOO_CLOSE_TO_ATTACK) &&
!HasCondition(COND_NOT_FACING_ATTACK) )
{
return SCHED_WAIT_AND_CLEAR;
}
}
#ifdef HL2_EPISODIC
// This ugly patch fixes a bug where Combine Soldiers on an assault would not shoot through glass, because of the way
// that shooting through glass is implemented in their AI. (sjb)
if( HasCondition(COND_SEE_ENEMY) && HasCondition(COND_WEAPON_SIGHT_OCCLUDED) && !HasCondition(COND_LOW_PRIMARY_AMMO) )
{
// If they are hiding behind something that we can destroy, start shooting at it.
CBaseEntity *pBlocker = GetOuter()->GetEnemyOccluder();
if ( pBlocker && pBlocker->GetHealth() > 0 )
{
if( GetOuter()->Classify() == CLASS_COMBINE && FClassnameIs(GetOuter(), "npc_combine_s") )
{
return SCHED_SHOOT_ENEMY_COVER;
}
}
}
#endif//HL2_EPISODIC
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
//
// CAI_AssaultGoal
//
// Purpose:
//
//
//-----------------------------------------------------------------------------
class CAI_AssaultGoal : public CAI_GoalEntity
{
typedef CAI_GoalEntity BaseClass;
virtual void EnableGoal( CAI_BaseNPC *pAI );
virtual void DisableGoal( CAI_BaseNPC *pAI );
string_t m_RallyPoint;
int m_AssaultCue;
int m_RallySelectMethod;
void InputBeginAssault( inputdata_t &inputdata );
DECLARE_DATADESC();
};
BEGIN_DATADESC( CAI_AssaultGoal )
DEFINE_KEYFIELD( m_RallyPoint, FIELD_STRING, "rallypoint" ),
DEFINE_KEYFIELD( m_AssaultCue, FIELD_INTEGER, "AssaultCue" ),
DEFINE_KEYFIELD( m_RallySelectMethod, FIELD_INTEGER, "RallySelectMethod" ),
DEFINE_INPUTFUNC( FIELD_VOID, "BeginAssault", InputBeginAssault ),
END_DATADESC();
//-------------------------------------
LINK_ENTITY_TO_CLASS( ai_goal_assault, CAI_AssaultGoal );
//-------------------------------------
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultGoal::EnableGoal( CAI_BaseNPC *pAI )
{
CAI_AssaultBehavior *pBehavior;
if ( !pAI->GetBehavior( &pBehavior ) )
return;
pBehavior->SetParameters( m_RallyPoint, (AssaultCue_t)m_AssaultCue, m_RallySelectMethod );
// Duplicate the output
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_AssaultGoal::DisableGoal( CAI_BaseNPC *pAI )
{
CAI_AssaultBehavior *pBehavior;
if ( pAI->GetBehavior( &pBehavior ) )
{
pBehavior->Disable();
// Don't leave any hanging rally points locked.
pBehavior->UnlockRallyPoint();
pBehavior->ClearSchedule( "Assault goal disabled" );
}
}
//-----------------------------------------------------------------------------
// Purpose: ENTITY I/O method for telling the assault behavior to cue assault
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_AssaultGoal::InputBeginAssault( inputdata_t &inputdata )
{
int i;
for( i = 0 ; i < NumActors() ; i++ )
{
CAI_BaseNPC *pActor = GetActor( i );
if( pActor )
{
// Now use this actor to lookup the Behavior
CAI_AssaultBehavior *pBehavior;
if( pActor->GetBehavior( &pBehavior ) )
{
// GOT IT! Now tell the behavior that entity i/o wants to cue the assault.
pBehavior->ReceiveAssaultCue( CUE_ENTITY_INPUT );
}
}
}
}
AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER(CAI_AssaultBehavior)
DECLARE_TASK(TASK_GET_PATH_TO_RALLY_POINT)
DECLARE_TASK(TASK_FACE_RALLY_POINT)
DECLARE_TASK(TASK_GET_PATH_TO_ASSAULT_POINT)
DECLARE_TASK(TASK_FACE_ASSAULT_POINT)
DECLARE_TASK(TASK_AWAIT_CUE)
DECLARE_TASK(TASK_AWAIT_ASSAULT_TIMEOUT)
DECLARE_TASK(TASK_ANNOUNCE_CLEAR)
DECLARE_TASK(TASK_WAIT_ASSAULT_DELAY)
DECLARE_TASK(TASK_HIT_ASSAULT_POINT)
DECLARE_TASK(TASK_HIT_RALLY_POINT)
DECLARE_TASK(TASK_ASSAULT_DEFER_SCHEDULE_SELECTION)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MOVE_TO_RALLY_POINT,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSAULT_FAILED_TO_MOVE"
" TASK_GET_PATH_TO_RALLY_POINT 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_STOP_MOVING 0"
" TASK_FACE_RALLY_POINT 0"
" TASK_HIT_RALLY_POINT 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_HOLD_RALLY_POINT"
" "
" Interrupts"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_NO_PRIMARY_AMMO"
" COND_PLAYER_PUSHING"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSAULT_FAILED_TO_MOVE,
" Tasks"
" TASK_ASSAULT_DEFER_SCHEDULE_SELECTION 1"
" "
" Interrupts"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FAIL_MOVE_TO_RALLY_POINT,
" Tasks"
" TASK_WAIT 1"
" "
" Interrupts"
" COND_HEAR_DANGER"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
)
#ifdef HL2_EPISODIC
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HOLD_RALLY_POINT,
" Tasks"
" TASK_FACE_RALLY_POINT 0"
" TASK_AWAIT_CUE 0"
" TASK_WAIT_ASSAULT_DELAY 0"
" "
" Interrupts"
//" COND_NEW_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_PLAYER_PUSHING"
" COND_HEAR_DANGER"
" COND_HEAR_BULLET_IMPACT"
" COND_NO_PRIMARY_AMMO"
)
#else
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HOLD_RALLY_POINT,
" Tasks"
" TASK_FACE_RALLY_POINT 0"
" TASK_AWAIT_CUE 0"
" TASK_WAIT_ASSAULT_DELAY 0"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_PLAYER_PUSHING"
" COND_HEAR_DANGER"
" COND_HEAR_BULLET_IMPACT"
" COND_NO_PRIMARY_AMMO"
" COND_TOO_CLOSE_TO_ATTACK"
)
#endif//HL2_EPISODIC
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HOLD_ASSAULT_POINT,
" Tasks"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_WAIT 3"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK2"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_LOST_ENEMY"
" COND_HEAR_DANGER"
" COND_HEAR_BULLET_IMPACT"
" COND_NO_PRIMARY_AMMO"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MOVE_TO_ASSAULT_POINT,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ASSAULT_FAILED_TO_MOVE"
" TASK_GATHER_CONDITIONS 0"
" TASK_GET_PATH_TO_ASSAULT_POINT 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ASSAULT_POINT 0"
" TASK_HIT_ASSAULT_POINT 0"
" "
" Interrupts"
" COND_NO_PRIMARY_AMMO"
" COND_HEAR_DANGER"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_AT_ASSAULT_POINT,
" Tasks"
" TASK_FACE_ASSAULT_POINT 0"
" TASK_HIT_ASSAULT_POINT 0"
" "
" Interrupts"
" COND_NO_PRIMARY_AMMO"
" COND_HEAR_DANGER"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_WAIT_AND_CLEAR,
" Tasks"
" TASK_FACE_ASSAULT_POINT 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_AWAIT_ASSAULT_TIMEOUT 0"
" TASK_ANNOUNCE_CLEAR 0"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK2"
" COND_HEAR_DANGER"
" COND_HEAR_BULLET_IMPACT"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_NOT_FACING_ATTACK"
" COND_PLAYER_PUSHING"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_CLEAR_ASSAULT_POINT,
" Tasks"
" TASK_ANNOUNCE_CLEAR 0"
" "
" Interrupts"
)
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_ASSAULT_MOVE_AWAY,
" Tasks"
" TASK_MOVE_AWAY_PATH 120"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
)
AI_END_CUSTOM_SCHEDULE_PROVIDER()
| 0 | 0.99773 | 1 | 0.99773 | game-dev | MEDIA | 0.896377 | game-dev | 0.86989 | 1 | 0.86989 |
EpicSentry/P2ASW | 8,763 | src/game/client/portal2/gameui/portal2/vpuzzlemakermenu.cpp | //========= Copyright (c) 1996-2008, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=======================================================================================//
#include "cbase.h"
#if defined( PORTAL2_PUZZLEMAKER )
#include "vpuzzlemakermenu.h"
#include "VFooterPanel.h"
#include "VHybridButton.h"
#include "EngineInterface.h"
#include "IGameUIFuncs.h"
#include "gameui_util.h"
#include "vgui/ISurface.h"
#include "VGenericConfirmation.h"
#include "vpuzzlemakerbetatests.h"
#include "transitionpanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
using namespace BaseModUI;
#if !defined( NO_STEAM )
static uint32 GetObfuscatedAccountID( CSteamID &steamID )
{
uint32 accountID = steamID.GetAccountID();
if ( accountID == 0 )
{
return 0;
}
return accountID ^ ( accountID / 2 ) ^ 2825520 ;
}
#endif
CPuzzleMakerMenu::CPuzzleMakerMenu( Panel *pParent, const char *pPanelName ):
BaseClass( pParent, pPanelName ), m_pAvatar( NULL ), m_nSteamID( 0 )
{
SetDeleteSelfOnClose( true );
SetProportional( true );
SetDialogTitle( "#PORTAL2_EditorMenu_Welcome" );
#if !defined( NO_STEAM )
if ( steamapicontext && steamapicontext->SteamUser() )
{
char szEmployeeLabel[16];
char szFullEmployeeLabel[128];
wchar_t *pEmployeeText = g_pVGuiLocalize->Find( "#PORTAL2_EditorMenu_EmployeeLabel" );
V_wcstostr( pEmployeeText, V_wcslen( pEmployeeText ) + 1, szEmployeeLabel, sizeof( szEmployeeLabel ) );
CSteamID playerID = steamapicontext->SteamUser()->GetSteamID();
uint32 obfuscatedID = GetObfuscatedAccountID( playerID );
V_snprintf( szFullEmployeeLabel, sizeof( szFullEmployeeLabel ), "%s #%d", szEmployeeLabel, obfuscatedID );
SetDialogSubTitle( szFullEmployeeLabel );
m_nSteamID = playerID.ConvertToUint64();
}
#endif
//SetDialogSubTitle( "TEMP Employee #12345" );
m_pEmployeeImage = NULL;
m_pAvatarSpinner = NULL;
m_flRetryAvatarTime = -1.0f;
// clear the community map id
BASEMODPANEL_SINGLETON.SetCurrentCommunityMapID( 0 );
SetFooterEnabled( true );
UpdateFooter();
}
CPuzzleMakerMenu::~CPuzzleMakerMenu()
{
if ( m_pAvatar && m_nSteamID )
{
BaseModUI::CUIGameData::Get()->AccessAvatarImage( m_nSteamID, BaseModUI::CUIGameData::kAvatarImageRelease, CGameUiAvatarImage::LARGE );
}
}
void CPuzzleMakerMenu::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
m_pAvatarSpinner = dynamic_cast< vgui::ImagePanel * >( FindChildByName( "AvatarSpinner" ) );
m_pEmployeeImage = dynamic_cast< ImagePanel*>( FindChildByName( "ImgPlayerAvatar" ) );
if ( m_pEmployeeImage )
{
#if !defined( NO_STEAM )
if ( steamapicontext && steamapicontext->SteamUser() )
{
m_pAvatar = BaseModUI::CUIGameData::Get()->AccessAvatarImage( m_nSteamID, BaseModUI::CUIGameData::kAvatarImageRequest, CGameUiAvatarImage::LARGE );
if ( m_pAvatar == NULL )
{
m_flRetryAvatarTime = gpGlobals->curtime + 1.0f;
if ( m_pAvatarSpinner )
{
m_pAvatarSpinner->SetVisible( true );
}
}
else
{
m_pAvatarSpinner->SetVisible( false );
m_pEmployeeImage->SetImage( m_pAvatar );
}
}
#endif
}
#if !defined( NO_STEAM )
Label *pLblPlayerName = static_cast< vgui::Label *>( FindChildByName( "LblBadgePlayerName" ) );
if ( pLblPlayerName && steamapicontext->SteamFriends() )
{
pLblPlayerName->SetText( steamapicontext->SteamFriends()->GetPersonaName() );
}
#endif
/*
ImagePanel *pImgBadgeUpgrade = static_cast< ImagePanel *>( FindChildByName( "ImgBadgeUpgrade" ) );
if ( pImgBadgeUpgrade )
{
// TEMP - pick a random badge from 1 to 4
int nBadgeType = RandomInt(0,4);
if (nBadgeType == 0 )
{
pImgBadgeUpgrade->SetVisible( false );
}
else
{
char szBadgeName[ 16 ];
V_snprintf( szBadgeName, sizeof(szBadgeName), "upgrade%.2d", nBadgeType );
pImgBadgeUpgrade->SetImage( szBadgeName );
}
}
*/
UpdateFooter();
}
void CPuzzleMakerMenu::Activate()
{
BaseClass::Activate();
// Reset our avatar if we're returning to this dialog, because who knows what's happened in the meantime
if ( m_pAvatar && m_nSteamID )
{
m_pEmployeeImage->SetVisible( false );
BaseModUI::CUIGameData::Get()->AccessAvatarImage( m_nSteamID, BaseModUI::CUIGameData::kAvatarImageRelease, CGameUiAvatarImage::LARGE );
m_pAvatar = NULL;
m_flRetryAvatarTime = gpGlobals->curtime + 0.1f;
if ( m_pAvatarSpinner )
{
m_pAvatarSpinner->SetVisible( true );
}
}
UpdateFooter();
}
void CPuzzleMakerMenu::PaintBackground( void )
{
BaseClass::PaintBackground();
// Because we have some oddly floating pieces in the UI, we mark our whole region as being "dirty" to avoid weird cut-offs
// in the transition effect.
int x, y;
GetPos( x, y );
BASEMODPANEL_SINGLETON.GetTransitionEffectPanel()->MarkTilesInRect( x, y, GetWide(), GetTall(), GetWindowType() );
}
void CPuzzleMakerMenu::OnKeyCodePressed( KeyCode code )
{
int joystick = GetJoystickForCode( code );
int userId = CBaseModPanel::GetSingleton().GetLastActiveUserId();
if ( joystick != userId || joystick < 0 )
{
return;
}
switch ( GetBaseButtonCode( code ) )
{
case KEY_XBUTTON_B:
BaseClass::OnKeyCodePressed( code );
break;
default:
BaseClass::OnKeyCodePressed(code);
break;
}
}
void CPuzzleMakerMenu::FixFooter()
{
CPuzzleMakerMenu *pSelf = static_cast<CPuzzleMakerMenu*>( CBaseModPanel::GetSingleton().GetWindow( WT_EDITORMAINMENU ) );
if( pSelf )
{
pSelf->InvalidateLayout( false, true );
}
}
void CPuzzleMakerMenu::OnCommand(const char *command)
{
if ( !V_stricmp( "Cancel", command ) || !V_stricmp( "Back", command ) )
{
OnKeyCodePressed( ButtonCodeToJoystickButtonCode( KEY_XBUTTON_B, CBaseModPanel::GetSingleton().GetLastActiveUserId() ) );
}
else if ( !V_stricmp( "PlayTestChambers", command ) )
{
BASEMODPANEL_SINGLETON.SetCommunityMapQueueMode( QUEUEMODE_USER_QUEUE );
CBaseModPanel::GetSingleton().OpenWindow( WT_COMMUNITYMAP, this, true );
}
else if ( !V_stricmp( "PlayCoopChambers", command ) )
{
BASEMODPANEL_SINGLETON.SetCommunityMapQueueMode( QUEUEMODE_USER_COOP_QUEUE );
CBaseModPanel::GetSingleton().OpenWindow( WT_COMMUNITYMAP, this, true );
}
else if ( !V_stricmp( "MyChambers", command ) )
{
CBaseModPanel::GetSingleton().OpenWindow( WT_EDITORCHAMBERLIST, this, true );
}
else if ( !V_stricmp( "MyWorkshop", command ) )
{
#if !defined(NO_STEAM)
if ( steamapicontext && steamapicontext->SteamUser() )
{
CSteamID userID = steamapicontext->SteamUser()->GetSteamID();
OverlayResult_t result = BASEMODPANEL_SINGLETON.ViewAuthorsWorkshop( userID );
if( result != RESULT_OK )
{
if( result == RESULT_FAIL_OVERLAY_DISABLED )
{
GenericConfirmation* confirmation =
static_cast<GenericConfirmation*>( CBaseModPanel::GetSingleton().OpenWindow( WT_GENERICCONFIRMATION, this, true ) );
GenericConfirmation::Data_t data;
data.pWindowTitle = "#L4D360UI_SteamOverlay_Title";
data.pMessageText = "#L4D360UI_SteamOverlay_Text";
data.bOkButtonEnabled = true;
data.pfnOkCallback = CPuzzleMakerMenu::FixFooter;
confirmation->SetUsageData(data);
}
}
}
#endif // !NO_STEAM
}
else
{
BaseClass::OnCommand( command );
}
}
void CPuzzleMakerMenu::OnThink()
{
UpdateSpinner();
// if we didn't find the avatar right off keep trying
if ( m_flRetryAvatarTime > 0.0f && m_flRetryAvatarTime < gpGlobals->curtime )
{
if ( m_pAvatar == NULL && m_pEmployeeImage != NULL && steamapicontext && steamapicontext->SteamUser() )
{
m_pAvatar = BaseModUI::CUIGameData::Get()->AccessAvatarImage( m_nSteamID, BaseModUI::CUIGameData::kAvatarImageRequest, CGameUiAvatarImage::LARGE );
if ( m_pAvatar != NULL )
{
m_flRetryAvatarTime = -1.0f;
m_pEmployeeImage->SetImage( m_pAvatar );
m_pEmployeeImage->SetVisible( true );
if ( m_pAvatarSpinner )
{
m_pAvatarSpinner->SetVisible( false );
}
}
}
}
BaseClass::OnThink();
}
void CPuzzleMakerMenu::UpdateFooter()
{
CBaseModFooterPanel *pFooter = BaseModUI::CBaseModPanel::GetSingleton().GetFooterPanel();
if ( pFooter )
{
pFooter->SetButtons( FB_BBUTTON );
pFooter->SetButtonText( FB_BBUTTON, "#L4D360UI_Back" );
}
}
void CPuzzleMakerMenu::UpdateSpinner( void )
{
if ( m_pAvatarSpinner )
{
int nAnimFrame = ( uint64 )( Plat_FloatTime() * 10 );
m_pAvatarSpinner->SetFrame( nAnimFrame );
}
}
vgui::Panel *CPuzzleMakerMenu::NavigateBack( void )
{
BASEMODPANEL_SINGLETON.SetCommunityMapQueueMode( QUEUEMODE_INVALID );
BASEMODPANEL_SINGLETON.SetForceUseAlternateTileSet( false );
BASEMODPANEL_SINGLETON.GetTransitionEffectPanel()->SetExpectedDirection( false, WT_EDITORMAINMENU );
return BaseClass::NavigateBack();
}
#endif // PORTAL2_PUZZLEMAKER
| 0 | 0.90557 | 1 | 0.90557 | game-dev | MEDIA | 0.861804 | game-dev | 0.94254 | 1 | 0.94254 |
sezero/uhexen2 | 30,385 | gamecode/hc/siege/MG_AI.hc | /*
==================================================================
MG_AI.HC
Michael Gummelt Artificial Intelligence Routines!!!
US Patent# 2.56734376314532533 + E17
Hoo-hah!
==================================================================
*/
/*
==============================================
GENERAL
==============================================
*/
/*
=============
get_visibility
Checks for drf_translucent and abslight of an object,
and uses that and it's world lighting value to set it's
visibility value
>=1 = Totally visible (default)
.
.
.
<=0 = Totally invisible
This value should be used in monster aiming as well.
NOTE: This only works on players since light_level info
is taken from player's weaponmodel lighting (0-255)
=============
*/
void get_visibility (entity targ , float range_mod)
{
//NOTE: incorporate distance?
float base, divider, attack_mod;
//FIXME: .light_level gives a value of 0 if MLS_POWERMODE is on...
//Temp fix for now...
if(targ.classname!="player"||targ.drawflags&MLS_POWERMODE)
{
targ.visibility=1;
return;
}
if(targ.effects&EF_NODRAW)
{
targ.visibility=0;
return;
}
if(targ.drawflags&DRF_TRANSLUCENT&&targ.frozen<=0)
{
if(targ.model=="models/assassin.mdl")
divider=3+targ.level;//Bonus for hiding in shadows
else
divider=3; //Makes it 3 times harder to see
}
else
divider=1;
if(self.classname=="monster_pirhana"||self.classname=="monster_mezzoman")
base = 2;//pirhana and mezzomen see well, even in dark
else if(targ.drawflags&MLS_ABSLIGHT)
base=targ.abslight/2.5;
else
base = 0.8;//light_lev not set right in HW
//base=targ.light_level/75;//75 is semi-fullbright
if(range_mod)
range_mod=vlen(targ.origin-self.origin)/333;
else
range_mod = 1;
if(targ.last_attack>time - 3)//Remember where they were when fired
attack_mod=time - targ.last_attack;
targ.visibility=base/divider/range_mod + attack_mod;
}
/*
=============
float visibility_good (entity targ,float chance_mod)
MG
Does a random check to see if self can see the target based
it's visibility (calls get_visibility for that targ first)
The higher the chance_mod, the lower the chance of
good visibility.
=============
*/
float visibility_good (entity targ,float chance_mod)
{
if(!targ)
return FALSE;
get_visibility(targ,TRUE);
if(random(chance_mod)<targ.visibility)
return TRUE;
return FALSE;
}
/*
=============
float FindMonsterTarget ()
MG
Called by FindTarget, checks for anything alive and
visible within range and sets it as enemy (as long as
it's not the monster's controller, or has the same
controller). Returns TRUE if it finds something,
FALSE if not.
=============
*/
float FindMonsterTarget ()
{
entity found;
float okay;
if(self.controller.enemy!=world)
if(self.controller.enemy.flags2&FL_ALIVE)
if(self.controller.enemy!=self)
if(self.controller.enemy!=self.controller)
if(self.controller.siege_team!=self.controller.enemy.siege_team)
if(visible(self.controller.enemy))
{
self.enemy=self.controller.enemy;
return TRUE;
}
okay=FALSE;
found=findradius(self.origin,1000);
while(found!=world)
{
if(found.flags2&FL_ALIVE)
if(found!=self)
if(found!=self.controller)
if(found.siege_team)
if(found.controller!=self.controller)
if(visible(found))
{
if(coop)
{
if(found.classname!="player")
okay = TRUE;
}
else if(teamplay)
{
if(found.team!=self.controller.team)
okay = TRUE;
}
else if(dmMode==DM_SIEGE)
{
if(found.siege_team!=self.controller.siege_team)
okay = TRUE;
}
else
okay = TRUE;
if(okay)
{
self.enemy=found;
return TRUE;
}
}
found=found.chain;
}
if(self.classname=="monster_imp_lord")
self.enemy=self.controller;
return FALSE;
}
/*
==================================================================
float CheckJump()
MG
Checks to see if the enemy is not at the same level as monster
or something is blocking the path of the monster. If there is
a clear jump arc to the enemy and the monster will not land in
water or lava, the monster will attempt to jump the distance.
==================================================================
*/
float CheckJump ()
{
local vector spot1, spot2, jumpdir;
float jump_height, jumpup, ignore_height;
makevectors(self.angles);
jumpdir=normalize(self.goalentity.origin-self.origin);
jumpdir_z=0;
jump_height=jumpdir*v_forward;
if(jump_height<0.3)
return FALSE;
spot1=self.origin;
spot2=self.enemy.origin;
spot1_z=0;
spot2_z=0;
jump_height=16;
if(pointcontents(spot1+v_forward*24-'0 0 10')!=CONTENT_SOLID)
ignore_height=TRUE;
if(self.classname!="monster_mezzoman"&&!self.spiderType)
if(vlen(spot1-spot2)>256)
ignore_height=FALSE;
//also check to make sure you can't walkmove forward
if(self.last_time>time)//jump_flag>time) //Don't jump too many times in a row
{
// dprint("just jumped\n");
return FALSE;
}
if(pointcontents(self.goalentity.origin)!=CONTENT_EMPTY)
{
// dprint("goalentity in water or lava\n");
return FALSE;
}
if(!visible(self.goalentity))
{
// dprint("can't see goalentity\n");
return FALSE;
}
if(!ignore_height&&self.goalentity.absmin_z+36>=self.absmin_z&&self.classname!="monster_mezzoman")//SpiderJumpBegin
{
// dprint("not above goalentity, and not spider\n");
return FALSE;
}
if(!self.flags&FL_ONGROUND)
{
// dprint("not on ground\n");
return FALSE;
}
if(!self.goalentity.flags&FL_ONGROUND&&self.goalentity.classname!="waypoint")
{
// dprint("goalentity in air\n");
return FALSE;
}
if(!infront(self.goalentity))
{
// dprint("goalentity not in front\n");
return FALSE;
}
if(vlen(spot1-spot2)>777&&!ignore_height)
{
// dprint("too far away\n");
return FALSE;
}
if(vlen(spot1-spot2)<=100)//&&self.think!=SpiderMeleeBegin)
{
// dprint("too close & not spider\n");
return FALSE;
}
// if(self.think==SpiderJumpBegin)
// jump_height=vlen((self.goalentity.absmax+self.goalentity.absmin)*0.5-self.origin)/13;
// else
if(self.classname=="monster_mezzoman")
if(self.goalentity.absmin_z>=self.absmin_z+36)
{
jump_height=vlen((self.goalentity.absmax+self.goalentity.absmin)*0.5-self.origin)/13;
jumpup=TRUE;
}
else if(self.goalentity.absmin_z>self.absmin_z - 36)
{
if(ignore_height)
jump_height=vlen((self.goalentity.absmax+self.goalentity.absmin)*0.5-self.origin)/13;
else
{
// dprint("Mezzo: Goal not above and not below\n");
return FALSE;
}
}
spot1=self.origin;
spot1_z=self.absmax_z;
spot2=spot1;
spot2_z+=36;
traceline(spot1, spot2,FALSE,self);
if(trace_fraction<1)
{
// dprint("not enough room above\n");
return FALSE;
}
if(!jumpup)
{
float content;
// spot1+=normalize(v_forward)*((self.maxs_x+self.maxs_y)*0.5);
spot1+=jumpdir*((self.maxs_x+self.maxs_y)*0.5);
traceline(self.origin, spot1 + '0 0 36',FALSE,self);
if(trace_fraction<1)
{
// dprint("not enough room in front\n");
return FALSE;
}
traceline(spot1,spot1+jumpdir*64 - '0 0 500',FALSE,self);
content=pointcontents(trace_endpos);
if(content==CONTENT_WATER||content==CONTENT_SLIME||content==CONTENT_LAVA)
{
// dprint("won't jump in water\n");
return FALSE;
}
}
ai_face();
// self.ideal_yaw=jumpdir_y;
// ChangeYaw();
// if(self.think!=SpiderJumpBegin)
// {
self.last_time = time + 7;//jump_flag=time + 7; //Only try to jump once every 7 seconds
SightSound();
if(!jumpup)
{
self.velocity=jumpdir*jump_height*17*self.scale;
self.velocity_z = jump_height*12*self.scale;
}
else
{
self.velocity=jumpdir*jump_height*10*self.scale;
self.velocity_z = jump_height*14*self.scale;
}
self.flags(-)FL_ONGROUND;
if(self.th_jump)
self.th_jump();
else
thinktime self : 0.3;
/* }
else
{
self.level=jump_height;
return TRUE;
}*/
}
/*
====================================================================
void MonsterCheckContents ()
MG
Monsters check to see if they're in lava or under water and
do damage do themselves if appropriate.
void do_contents_dam ()
Just spawns a temporary ent to damage self, using T_Damage on
self does weird stuff- won't kill self, just become invincible
====================================================================
*/
void do_contents_dam ()
{
T_Damage(self.enemy,world,world,self.dmg);
if(self.dmg==5)
{
self.classname="contents damager";
setorigin(self,self.enemy.origin+self.enemy.view_ofs);
// DeathBubbles(1);
}
remove(self);
}
void MonsterCheckContents ()
{
if(random()>0.3)
return;
if(pointcontents(self.origin)==CONTENT_LAVA)
{
if(self.flags&FL_FIREHEAL)
{
if(self.health<self.max_health)
self.health+=1;
}
else
{
newmis=spawn();
newmis.think=do_contents_dam;
newmis.enemy=self;
newmis.dmg=30;
thinktime newmis : 0;
}
}
if(self.movetype==MOVETYPE_SWIM||self.model=="models/skullwiz.mdl"||self.netname=="golem"||self.classname=="monster_pirhana")
return;
if(pointcontents(self.origin+self.view_ofs)==CONTENT_WATER)
{
if(self.air_finished<time) //Start drowning
{
// dprint("drowning!\n");
newmis=spawn();
newmis.think=do_contents_dam;
newmis.enemy=self;
newmis.dmg=5;
thinktime newmis : 0;
}
}
else
self.air_finished=time+12;
}
/*
====================================================================
void pitch_roll_for_slope (vector slope)
(My personal favorite!)
MG
This will adjust the pitch and roll of a monster to match
a given slope - if a non-'0 0 0' slope is passed, it will
use that value, otherwise it will use the ground underneath
the monster. If it doesn't find a surface, it does nothinh\g
and returns.
====================================================================
*/
void pitch_roll_for_slope (vector slope)
{
vector new_angles,new_angles2,old_forward,old_right;
float dot,mod;
makevectors(self.angles);
old_forward=v_forward;
old_right=v_right;
if(slope=='0 0 0')
{
traceline(self.origin,self.origin-'0 0 300',TRUE,self);
if(trace_fraction>0.05&&self.movetype==MOVETYPE_STEP)
self.flags(-)FL_ONGROUND;
if(trace_fraction==1)
return;
slope=trace_plane_normal;
}
new_angles=vectoangles(slope);
new_angles_x=(90-new_angles_x)*-1;//Gets actual slope
new_angles2='0 0 0';
new_angles2_y=new_angles_y;
makevectors(new_angles2);
mod=v_forward*old_right;
if(mod<0)
mod=1;
else
mod=-1;
dot=v_forward*old_forward;
self.angles_x=dot*new_angles_x;
self.angles_z=(1-fabs(dot))*new_angles_x*mod;
}
/*
==============================================
IMP
==============================================
*/
/*
================================================================
checkenemy()
Checks to see if enemy is of the same monstertype and old enemy
is alive and visible. If so, changes back to it's last enemy.
================================================================
*/
void checkenemy (void)
{
entity oldtarget;
/* if(self.enemy==world)
{
if(!LocateTarget())
{
if(self.controller.classname=="player")
self.enemy=self.controller;
else
{
self.enemy=world;
self.think=self.th_stand;
}
}
self.goalentity=self.enemy;
return;
}
*/
if(self.enemy.classname=="player"&&self.enemy.flags2&FL_ALIVE&&self.enemy!=self.controller)
return;
if (!self.enemy.flags2&FL_ALIVE||self.enemy==self.controller)
{
if(self.controller.classname=="player")
{
self.enemy = self.controller;
self.goalentity=self.enemy;
}
else
self.enemy = world;
if (self.oldenemy.flags2&FL_ALIVE)
{
self.enemy = self.oldenemy;
self.goalentity = self.enemy;
self.think = self.th_run;
}
else if(LocateTarget())
{
self.goalentity = self.enemy;
self.think = self.th_run;
}
else
{
if(self.controller.classname=="player")
self.goalentity=self.enemy=self.controller;
else
self.goalentity=self.enemy=world;
if (self.pathentity)
self.think=self.th_walk;
else
self.think=self.th_stand;
}
thinktime self : 0;
return;
}
if(self.classname=="monster_imp_lord")
return;
if(self.oldenemy.classname=="player"&&(self.oldenemy.flags2&FL_ALIVE)&&visible(self.oldenemy))
{
if((self.model=="models/spider.mdl"||self.model=="models/scorpion.mdl")&&self.enemy.model==self.model)
self.enemy=self.oldenemy;
else
{
oldtarget=self.enemy;
self.enemy=self.oldenemy;
self.oldenemy=oldtarget;
}
self.goalentity=self.enemy;
}
}
/*
================================================================
fov()
Field-Of-View
Returns TRUE if vector from entity "from" to entity "targ" is
within "scope" degrees of entity "from"'s forward angle.
================================================================
*/
float fov(entity targ,entity from,float scope)
{
vector spot1,spot2;
float dot;
spot1=from.origin+from.view_ofs;
if(targ.classname=="player")
spot2=targ.origin+targ.proj_ofs;
else
spot2=(targ.absmin+targ.absmax)*0.5;
makevectors(from.angles);
// scope=1 - (scope/180);//converts angles into %
dot=normalize(spot2-spot1)*v_forward;
dot=180 - (dot*180);
// dprintf("FOV value : %s\n",dot);
if(dot<=scope)
return TRUE;
return FALSE;
}
/*
================================================================
check_pos_enemy()
MG
Checks to see if enemy is visible, if so, remember the spot for
waypoints, else set your waypoint at the last spot you saw him.
Also resets search_time timer if you see him.
================================================================
*/
void check_pos_enemy ()
{
if(!self.mintel)
return;
if(!visible(self.enemy))
{
self.attack_state = AS_STRAIGHT;
SetNextWaypoint();
if(self.model=="models/imp.mdl") //Imps keep looking in general area for a while
if(self.search_time<time&&self.goalentity==self.enemy&&self.trigger_field.classname=="waypoint")
self.goalentity=self.trigger_field;
}
else
{
if(self.model=="models/imp.mdl")
self.search_time=time+5; //If lose sight, keep searching for 5 secs
self.goalentity=self.enemy;
self.wallspot=(self.enemy.absmin+self.enemy.absmax)*0.5;
}
}
/*
================================================================
float clear_path (entity targ,float whole_body)
MG
returns TRUE if there is a clear shot or path between self
and "targ". "whole_body" TRUE will check for a path.
================================================================
*/
float clear_path (entity targ,float whole_body)
{
vector destiny,org;
destiny=targ.origin+targ.proj_ofs;
if(self.attack_state!=AS_FERRY)
self.attack_state = AS_STRAIGHT;
if(whole_body)
{
org=(self.absmin+self.absmax)*0.5;
// tracearea (org, destiny, '-16 -16 0','16 16 28',FALSE,self);
tracearea (org, destiny, self.mins,self.maxs,FALSE,self);
}
else
{
org=self.origin+self.proj_ofs;
traceline (org, destiny,FALSE,self);
}
if(!whole_body&&trace_ent.thingtype>=THINGTYPE_WEBS)
traceline (trace_endpos, destiny, FALSE, trace_ent);
if (trace_ent == targ)
return TRUE;
if(whole_body)
{
if(self.attack_state!=AS_FERRY)
self.attack_state = AS_SLIDING;
return FALSE;
}
if(trace_ent.health>25||!trace_ent.takedamage||(trace_ent.flags&FL_MONSTER&&trace_ent.classname!="player_sheep"))
{//Don't have a clear shot, and don't want to shoot obstruction
self.attack_state = AS_SLIDING;
return FALSE;
}
return TRUE;
}
/*
================================================================
check_view(entity targ,vector org,vector dir,float dist,float interval)
MG
Will see if it can see the targ entity along the dir
given to it- used to determine which direction a monster
should move in to get a clear line of sight to the targ.
Returns the distance it took to see targ, FALSE if couldn't.
================================================================
*/
float check_view(entity targ,vector org,vector dir,float dist,float interval)
{
float dist_counter;
newmis=spawn();
dir=normalize(dir);
while(dist_counter<dist)
{
dist_counter+=interval;
setorigin(newmis,org+dir*dist_counter);
if(visible2ent(targ,newmis))
{
traceline (newmis.origin,(targ.absmin+targ.absmax)*0.5,FALSE,self);
if (trace_ent == targ)
{
remove(newmis);
return dist_counter;
}
}
}
remove(newmis);
return FALSE;
}
/*
================================================================
vector check_axis_move (vector checkdir,float minspeed,float maxspeed)
MG
Calls check_view for enemy along given vector, and if it
fails, checks again along opposite direction on that vector.
If check_view is successful, returns the vector*the distance
along that vector at which it found the goalentity, this
"speed" maxes out at "maxpeed" and is at least "minspeed".
Not used for waypoint or path navigation, only for going
after enemies.
================================================================
*/
vector check_axis_move (vector checkdir,float minspeed,float maxspeed)
{
float go_dist;
checkdir=normalize(checkdir);
if(random()<0.5)
checkdir=checkdir*-1;
go_dist=check_view(self.enemy,self.origin+self.view_ofs,checkdir,500,30);
if(!go_dist&&random()<0.5)
{
checkdir*=-1;
go_dist=check_view(self.enemy,self.origin+self.view_ofs,checkdir,500,30);
}
if(go_dist)
{
if(go_dist>maxspeed)
go_dist=maxspeed;
else if(go_dist<minspeed)
go_dist=minspeed;
checkdir=checkdir*go_dist;
return checkdir;
}
return '0 0 0';
}
/*
================================================================
float check_z_move(float maxdist)
MG
Intended for flying monsters, will try to move up if enemy
or goalentity is above monster, down if it is below. Uses
movestep, not velocity.
Will move a maximum step of "maxdist".
Returns FALSE if blocked, TRUE if movement completed.
================================================================
*/
float check_z_move(float maxdist)
{
float goaldist;
entity targ;
if(self.enemy!=world&&visible(self.enemy))
targ=self.enemy;
else if(self.goalentity!=world)
targ=self.goalentity;
else
return FALSE;
/*What does this do?
if(fabs(targ.origin_z-self.origin_z)<48&&!visible(targ))
return FALSE; //FIXME: Find an up or down
*/
if(targ.origin_z!=self.absmin_z)
{
goaldist=(targ.absmin_z+targ.absmax_z)*0.5-(self.absmax_z+self.absmin_z)*0.5;
maxdist=fabs(maxdist);
if(fabs(goaldist)>maxdist)
if(goaldist>0)
goaldist=maxdist;
else
goaldist=maxdist*-1;
if(!movestep(0,0,goaldist, FALSE))
return FALSE;
}
return TRUE;
}
/*
====================================================================
MEDUSA
====================================================================
*/
/*
============================================================
float lineofsight(entity targ, entity from)
MG
Traces a line along "from"'s view_ofs along v_forward and returns
VRAI if it hits targ, FAUX if not, mon ami.
============================================================
*/
float lineofsight(entity targ, entity from)
{
//FIXME: account for monster's lack of pitch if z diff
vector org,dir;
if(from.classname=="player")
makevectors(from.v_angle);
/* else if(from.classname=="monster_medusa")
makevectors(from.angles+from.angle_ofs);
*/ else
makevectors(from.angles);
org=from.origin+from.view_ofs;
dir=normalize(v_forward);
traceline(org, org+dir*1000,FALSE,from);
if(trace_ent!=targ)
return FALSE;
else
{
// dprint("Line of sight from ");
// dprint(from.classname);
// dprint(" to ");
// dprint(targ.classname);
// dprint(" confirmed\n");
return TRUE;
}
}
/*
====================================================================
EIDOLON
====================================================================
*/
/*
=====================================================
entity riderpath_findbest(entity subject_path)
MG
Returns closest rider path corner that "subject_path"
leads to. Used for Rider Bosses.
=====================================================
*/
entity riderpath_findbest(entity subject_path)
{
entity search,found,best_path;
float next,num_points,position,bestdist,lastdist;
num_points = 0;
if (subject_path.next_path_1)
num_points += 1;
if (subject_path.next_path_2)
num_points += 1;
if (subject_path.next_path_3)
num_points += 1;
if (subject_path.next_path_4)
num_points += 1;
if (subject_path.next_path_5)
num_points += 1;
if (subject_path.next_path_6)
num_points += 1;
if (!num_points)
{
dprintf("rider path %s has no next points\n",subject_path.path_id);
remove(self);
return world;
}
bestdist=vlen(self.goalentity.origin-self.origin);
lastdist=bestdist;
position=0;
best_path=world;
while(position<num_points)
{
position+=1;
if (position==1)
next = subject_path.next_path_1;
else if (position==2)
next = subject_path.next_path_2;
else if (position==3)
next = subject_path.next_path_3;
else if (position==4)
next = subject_path.next_path_4;
else if (position==5)
next = subject_path.next_path_5;
else if (position==6)
next = subject_path.next_path_6;
found = world;
search = find(world, classname, "rider_path");
while(search != world && found == world)
{
if (search.path_id == next)
found = search;
else
search = find(search, classname, "rider_path");
}
if (!found)
{
dprintf("Could not find rider path %s\n",next);
remove(self);
return world;
}
else
{
lastdist=vlen(self.goalentity.origin-found.origin);
if(lastdist<bestdist)
{
best_path=found;
bestdist=lastdist;
}
}
}
if (!best_path)
return world;
return best_path;
}
/*
=====================================================================
MEZZOMAN
(Personal Favorite!)
=====================================================================
*/
/*
=========================================================
entity look_projectiles ()
MG
WARNING! Expensive, should not be called often at all!
Searches a radius 1000 around self to find projectiles
(anything with movetype bounce, flymissile, bouncemissile)
then checks to see if it's heading at self (see "heading"
function in PROJBHVR.HC). It finds the closest of these
and returns that entity. If it finds nothing, returns
"world".
=========================================================
*/
entity look_projectiles ()
{
entity found, enemy_proj;
float dist, bestdist;
found=findradius(self.origin,1000);
bestdist=1001;
while(found)
{
if(found.movetype==MOVETYPE_FLYMISSILE||found.movetype==MOVETYPE_BOUNCE||found.movetype==MOVETYPE_BOUNCEMISSILE)
if(visible(found))
{
dist=vlen(found.origin-self.origin);
if(dist<bestdist)
{
if(heading(self,found,0.9))//Try this small range for heading, but problem is, they won't split up & surround you as much...
{
bestdist=dist;
enemy_proj=found;
}
}
}
found=found.chain;
}
if(enemy_proj)
{
self.level=bestdist/vlen(enemy_proj.velocity);
return enemy_proj;
}
else
return world;
}
/*
======================================================
float solid_under(vector startpos , vector endpos)
MG
Will check in increments of 5 pixels along a given
path from startpos to endpos if there is solid gound
at least 18 pixels below (18 is the monster step-height).
If so, returns TRUE, if there is a gap anywhere along
that, returns FALSE.
Used mainly by Mezzomen to see if they should jump
across gaps at enemy.
======================================================
*/
float solid_under(vector startpos , vector endpos)
{
float diff_count;
vector dir;
dir=normalize(endpos-startpos);
diff_count=vlen(endpos-startpos)/5;
while(diff_count>0)
{
traceline(startpos,startpos-'0 0 18',TRUE,self);
if(trace_fraction==1)
return FALSE;
startpos+=dir*5;
diff_count-=1;
}
return TRUE;
}
/*
======================================================
float check_heading_left_or_right (entity object)
MG
Will check to see if the given object will be to
the left or the right of self once it gets to
self. Uses it's current position and extrapolates
based on it's heading (velocity).
Will return:
1 = left
-1 = right
0 = neither.
Special case: If called by a monster that's not
awake, will return opposite of these assuming
that the monster wants to cut off player-
only used by the Rolling Ambush Mezzomen.
======================================================
*/
float check_heading_left_or_right (entity object)
{
vector spot1, spot2, vec;
float dot, rng, reverse;
makevectors (self.angles);
spot1 = self.origin + self.view_ofs;
spot2 = object.origin;
//To get the eventual location of the projectile when it gets to him...
rng=vlen(spot1-spot2);
spot2+=normalize(object.velocity)*(rng+15);//Add a bit for good measure
vec = normalize (spot2 - spot1);
//FIXME? What about behind me?
if(object.classname=="player"&&!self.monster_awake)
{
self.monster_awake=TRUE;
sound(self,CHAN_VOICE,"mezzo/attack.wav",1,ATTN_NORM);
reverse=-1;
}
else
reverse=1;
dot = vec * v_right;
if ( dot > 0)
return -1*reverse;
dot = vec * (v_right*-1);
if ( dot > 0)
return 1*reverse;
return 0;
}
/*
======================================================
float navigate (float walkspeed)
MG
Checks to see which side of the entity is blocked
and will move in the opposite direction using
walkmove (for left-right) or movestep (for up-down)
if it can. Will move the specified distance.
If it can't move that way or it doesn't find a blocked
side, it returns false.
Meant for use with flying and swimming monsters
because movetogoal doesn't make them navigate!
======================================================
*/
float navigate (float walkspeed)
{
vector checkdir,org,new_angle;
float vert_size,horz_size;
makevectors(self.angles);
checkdir=v_right;
org=self.origin+checkdir*self.size_x;
vert_size=self.size_z/2;
horz_size=(self.size_x+self.size_y)/4;
traceline(org,org+v_forward*horz_size,FALSE,self);
if(trace_fraction==1&&!trace_allsolid)
{
checkdir=v_right*-1;
org=self.origin+checkdir*horz_size;
traceline(org,org+v_forward*horz_size,FALSE,self);
}
if(self.flags&FL_FLY||self.flags&FL_SWIM)
{
if(trace_fraction==1&&!trace_allsolid)
{
checkdir=v_up;
org=self.origin+checkdir*vert_size;
traceline(org,org+v_forward*horz_size,FALSE,self);
}
if(trace_fraction==1&&!trace_allsolid)
{
checkdir=v_up*-1;
org=self.origin+checkdir*vert_size;
traceline(org,org+v_forward*horz_size,FALSE,self);
}
}
if(trace_fraction<1||trace_allsolid)
{
if(checkdir==v_right||checkdir==v_right*-1)
{
new_angle=vectoangles(checkdir*-1);
if(!walkmove(new_angle_y,walkspeed,FALSE))
{
// dprint("Couldn't Side-step\n");
return FALSE;
}
// dprint("Side-stepped\n");
return TRUE;
}
if(checkdir==v_up)
walkspeed*=-1;
if(!movestep(0,0,walkspeed,FALSE))
{
// dprint("couldn't move up/down\n");
return FALSE;
}
// dprint("up-down move\n");
return TRUE;
}
// dprint("Not blocked\n");
return FALSE;//FOUND NO BLOCKING!!!
}
/*
=============================================================
vector extrapolate_pos_for_speed (vector p1,float pspeed,entity targ,float accept)
MG
Estimates where the "targ" will be by the time a projectile
travelling at "pspeed" leaving "org" arrives at "targ"'s origin.
It then calculates a new spot to shoot at so that the
projectile will arrive at such spot at the same time as
"targ". Will return '0 0 0' (FALSE) if there is not a clear
line of fire to the spot or if the new vector is out of the
acceptable range (based on dot product of original vec and
the new vec).
=============================================================
*/
vector extrapolate_pos_for_speed (vector p1,float pspeed,entity targ,float accept)
{
float dist1,dist2,tspeed,dot,eta1,eta2,eta_delta,failed;
vector p2,p3,targ_dir,vec1,vec2;
// dprint("Extrapolating\n");
p2=targ.origin+targ.view_ofs; //current target viewport
vec1=p2 - p1; //vector to p2
dist1=vlen(vec1); //distance to p2
vec1=normalize(vec1); //direction to p2
targ_dir=targ.velocity; //target velocity
tspeed=vlen(targ_dir); //target speed
targ_dir=normalize(targ_dir); //target direction
eta1=dist1/pspeed; //Estimated time of arrival of projectile to p2
p3=p2 + targ_dir * tspeed * eta1; //Extrapolated postion of targ at time + eta1
dist2=vlen(p3-p1); //new distance to p3
eta2=dist2/pspeed; //ETA of projectile to p3
eta_delta=eta2-eta1; //change in ETA's
p3+=targ_dir*tspeed*eta_delta*random();//Add any diff in ETA to p3's location,random a little in case they slow down
traceline(p1,p3,FALSE,self);
if(trace_fraction<1)
{
if(trace_ent.thingtype>=THINGTYPE_WEBS)
traceline (trace_endpos, p3, FALSE, trace_ent);
if(trace_fraction<1)
if(trace_ent.health>25||!trace_ent.takedamage||(trace_ent.flags&FL_MONSTER&&trace_ent.classname!="player_sheep"))
{//Don't have a clear shot, and don't want to shoot obstruction
// dprint("No clear shot\n");
self.attack_state = AS_SLIDING;
failed=TRUE;
}
}
vec2=normalize(p3-p1); //New vector to p3
dot=vec1*vec2;
if(dot<accept) //Change in dir too great
{
// dprint("Out of range\n");
failed=TRUE;
}
if(failed)
p3='0 0 0';
// else
// dprint("Successful extrapolation\n");
/*Was using this to show blue for failed extrap, red for succ.
WriteByte (MSG_BROADCAST, SVC_TEMPENTITY);
WriteByte (MSG_BROADCAST, TE_STREAM_COLORBEAM); //beam type
WriteEntity (MSG_BROADCAST, self); //owner
WriteByte (MSG_BROADCAST, 0); //tag + flags
WriteByte (MSG_BROADCAST, 20); //time
WriteByte (MSG_BROADCAST, failed); //color
WriteCoord (MSG_BROADCAST, p1_x);
WriteCoord (MSG_BROADCAST, p1_y);
WriteCoord (MSG_BROADCAST, p1_z);
WriteCoord (MSG_BROADCAST, p3_x);
WriteCoord (MSG_BROADCAST, p3_y);
WriteCoord (MSG_BROADCAST, p3_z);
*/
return p3;
}
/*
=============================================================
vector aim_adjust (entity targ)
MG
Will return a normalized offset vector based on the targ's
light level, used for monster aiming at shadow-hiding players.
=============================================================
*/
vector aim_adjust (entity targ)
{
float ofs;
vector vofs;
if(!targ)
return '0 0 0';
makevectors(self.angles);
get_visibility(targ,TRUE);
ofs=(1 - targ.visibility - skill/10)*0.1;
if(skill<3&&ofs>0)
{
vofs=v_up*0.5*random(0-ofs,ofs)+v_right*1.5*random(0-ofs,ofs);
return vofs;
}
return '0 0 0';
}
| 0 | 0.908168 | 1 | 0.908168 | game-dev | MEDIA | 0.985138 | game-dev | 0.963483 | 1 | 0.963483 |
Goob-Station/Goob-Station | 4,979 | Content.Shared/Atmos/Prototypes/GasPrototype.cs | // SPDX-FileCopyrightText: 2020 Campbell Suter <znix@znix.xyz>
// SPDX-FileCopyrightText: 2020 ComicIronic <comicironic@gmail.com>
// SPDX-FileCopyrightText: 2020 Exp <theexp111@gmail.com>
// SPDX-FileCopyrightText: 2020 Pieter-Jan Briers <pieterjan.briers@gmail.com>
// SPDX-FileCopyrightText: 2020 Víctor Aguilera Puerto <6766154+Zumorica@users.noreply.github.com>
// SPDX-FileCopyrightText: 2020 a.rudenko <creadth@gmail.com>
// SPDX-FileCopyrightText: 2020 creadth <creadth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2020 silicons <2003111+silicons@users.noreply.github.com>
// SPDX-FileCopyrightText: 2021 Metal Gear Sloth <metalgearsloth@gmail.com>
// SPDX-FileCopyrightText: 2021 Paul <ritter.paul1+git@googlemail.com>
// SPDX-FileCopyrightText: 2021 Vera Aguilera Puerto <6766154+Zumorica@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 Kevin Zheng <kevinz5000@gmail.com>
// SPDX-FileCopyrightText: 2022 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 Morb <14136326+Morb0@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 Paul Ritter <ritter.paul1@googlemail.com>
// SPDX-FileCopyrightText: 2022 Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
// SPDX-FileCopyrightText: 2022 Rane <60792108+Elijahrane@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 mirrorcult <lunarautomaton6@gmail.com>
// SPDX-FileCopyrightText: 2022 wrexbe <81056464+wrexbe@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 DrSmugleaf <DrSmugleaf@users.noreply.github.com>
// SPDX-FileCopyrightText: 2023 Visne <39844191+Visne@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: MIT
using Content.Shared.Chemistry.Reagent;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Shared.Atmos.Prototypes
{
[Prototype]
public sealed partial class GasPrototype : IPrototype
{
[DataField("name")] public string Name { get; set; } = "";
// TODO: Control gas amount necessary for overlay to appear
// TODO: Add interfaces for gas behaviours e.g. breathing, burning
[ViewVariables]
[IdDataField]
public string ID { get; private set; } = default!;
/// <summary>
/// Specific heat for gas.
/// </summary>
[DataField("specificHeat")]
public float SpecificHeat { get; private set; }
/// <summary>
/// Heat capacity ratio for gas
/// </summary>
[DataField("heatCapacityRatio")]
public float HeatCapacityRatio { get; private set; } = 1.4f;
/// <summary>
/// Molar mass of gas
/// </summary>
[DataField("molarMass")]
public float MolarMass { get; set; } = 1f;
/// <summary>
/// Minimum amount of moles for this gas to be visible.
/// </summary>
[DataField("gasMolesVisible")]
public float GasMolesVisible { get; private set; } = 0.25f;
/// <summary>
/// Visibility for this gas will be max after this value.
/// </summary>
public float GasMolesVisibleMax => GasMolesVisible * GasVisibilityFactor;
[DataField("gasVisbilityFactor")]
public float GasVisibilityFactor = Atmospherics.FactorGasVisibleMax;
/// <summary>
/// If this reagent is in gas form, this is the path to the overlay that will be used to make the gas visible.
/// </summary>
[DataField("gasOverlayTexture")]
public string GasOverlayTexture { get; private set; } = string.Empty;
/// <summary>
/// If this reagent is in gas form, this will be the path to the RSI sprite that will be used to make the gas visible.
/// </summary>
[DataField("gasOverlayState")]
public string GasOverlayState { get; set; } = string.Empty;
/// <summary>
/// State for the gas RSI overlay.
/// </summary>
[DataField("gasOverlaySprite")]
public string GasOverlaySprite { get; set; } = string.Empty;
/// <summary>
/// Path to the tile overlay used when this gas appears visible.
/// </summary>
[DataField("overlayPath")]
public string OverlayPath { get; private set; } = string.Empty;
/// <summary>
/// The reagent that this gas will turn into when inhaled.
/// </summary>
[DataField("reagent", customTypeSerializer:typeof(PrototypeIdSerializer<ReagentPrototype>))]
public string? Reagent { get; private set; } = default!;
[DataField("color")] public string Color { get; private set; } = string.Empty;
[DataField("pricePerMole")]
public float PricePerMole { get; set; } = 0;
}
} | 0 | 0.906017 | 1 | 0.906017 | game-dev | MEDIA | 0.842488 | game-dev | 0.745023 | 1 | 0.745023 |
chromealex/ME.BECS | 19,240 | Runtime/MemoryAllocator/Collections/Auto/HashSetAuto.cs | namespace ME.BECS {
using INLINE = System.Runtime.CompilerServices.MethodImplAttribute;
public unsafe struct HashSetAuto<T> : IIsCreated where T : unmanaged, System.IEquatable<T> {
public struct Enumerator {
private uint lastIndex;
private uint index;
private T current;
private safe_ptr<Slot> slotsPtr;
[INLINE(256)]
internal Enumerator(in HashSetAuto<T> set, safe_ptr<State> state) {
this.lastIndex = set.lastIndex;
this.index = 0;
this.slotsPtr = (safe_ptr<Slot>)set.slots.GetUnsafePtrCached(in state.ptr->allocator);
this.current = default;
}
[INLINE(256)]
public bool MoveNext() {
while (this.index < this.lastIndex) {
var v = this.slotsPtr + this.index;
if (v.ptr->hashCode >= 0) {
this.current = v.ptr->value;
++this.index;
return true;
}
++this.index;
}
this.index = this.lastIndex + 1u;
this.current = default;
return false;
}
public T Current => this.current;
}
public struct Slot {
internal int hashCode; // Lower 31 bits of hash code, -1 if unused
internal int next; // Index of next entry, -1 if last
internal T value;
}
public const int LOWER31_BIT_MASK = 0x7FFFFFFF;
internal MemArrayAuto<uint> buckets;
internal MemArrayAuto<Slot> slots;
internal uint count;
internal uint lastIndex;
internal int freeList;
internal uint version;
internal uint hash;
public readonly Ent ent => this.buckets.ent;
public bool IsCreated {
[INLINE(256)]
get => this.buckets.IsCreated;
}
public uint Count {
[INLINE(256)]
get => this.count;
}
[INLINE(256)]
public HashSetAuto(in Ent ent, uint capacity) {
this = default;
this.Initialize(in ent, capacity);
}
[INLINE(256)]
public HashSetAuto(in Ent ent, in HashSetAuto<T> other) {
E.IS_CREATED(other);
this = other;
this.buckets = new MemArrayAuto<uint>(in ent, in other.buckets);
this.slots = new MemArrayAuto<Slot>(in ent, in other.slots);
}
[INLINE(256)]
public HashSetAuto(in HashSetAuto<T> other) {
E.IS_CREATED(other);
this = other;
this.buckets = new MemArrayAuto<uint>(this.ent, in other.buckets);
this.slots = new MemArrayAuto<Slot>(this.ent, in other.slots);
}
[INLINE(256)]
public bool Equals(in HashSetAuto<T> other) {
E.IS_CREATED(this);
E.IS_CREATED(other);
if (this.count != other.count) return false;
if (this.hash != other.hash) return false;
if (this.count == 0u && other.count == 0u) return true;
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
var otherSlotsPtr = (safe_ptr<Slot>)other.slots.GetUnsafePtrCached();
var otherBucketsPtr = (safe_ptr<int>)other.buckets.GetUnsafePtrCached();
uint idx = 0u;
while (idx < this.lastIndex) {
var v = slotsPtr + idx;
if (v.ptr->hashCode >= 0) {
if (other.Contains(v.ptr->value, otherSlotsPtr, otherBucketsPtr) == false) {
return false;
}
}
++idx;
}
return true;
}
[INLINE(256)]
public void Set(in HashSetAuto<T> other) {
this = other;
this.buckets = new MemArrayAuto<uint>(other.ent, other.buckets);
this.slots = new MemArrayAuto<Slot>(other.ent, other.slots);
}
[INLINE(256)]
public void BurstMode(in MemoryAllocator allocator, bool state) {
this.buckets.BurstMode(in allocator, state);
this.slots.BurstMode(in allocator, state);
}
[INLINE(256)]
public void Dispose() {
this.buckets.Dispose();
this.slots.Dispose();
this = default;
}
[INLINE(256)]
public readonly MemPtr GetMemPtr() {
E.IS_CREATED(this);
return this.buckets.arrPtr;
}
[INLINE(256)]
public void ReplaceWith(in HashSetAuto<T> other) {
if (this.GetMemPtr() == other.GetMemPtr()) {
return;
}
this.Dispose();
this = other;
}
[INLINE(256)]
public readonly Enumerator GetEnumerator() {
return new Enumerator(this, this.ent.World.state);
}
/// <summary>
/// Remove all items from this set. This clears the elements but not the underlying
/// buckets and slots array. Follow this call by TrimExcess to release these.
/// </summary>
[INLINE(256)]
public void Clear() {
if (this.lastIndex > 0) {
// clear the elements so that the gc can reclaim the references.
// clear only up to m_lastIndex for m_slots
this.slots.Clear(0, this.lastIndex);
this.buckets.Clear(0, this.buckets.Length);
this.lastIndex = 0u;
this.count = 0u;
this.freeList = -1;
this.hash = 0u;
}
++this.version;
}
/// <summary>
/// Checks if this hashset contains the item
/// </summary>
/// <param name="item">item to check for containment</param>
/// <returns>true if item contained; false if not</returns>
[INLINE(256)]
public readonly bool Contains(T item) {
E.IS_CREATED(this);
uint hashCode = GetHashCode(item) & HashSetAuto<T>.LOWER31_BIT_MASK;
// see note at "HashSet" level describing why "- 1" appears in for loop
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
for (int i = (int)this.buckets[hashCode % this.buckets.Length] - 1; i >= 0; i = (slotsPtr + i).ptr->next) {
if ((slotsPtr + i).ptr->hashCode == hashCode &&
Equal((slotsPtr + i).ptr->value, item) == true) {
return true;
}
}
// either m_buckets is null or wasn't found
return false;
}
[INLINE(256)]
public readonly bool Contains(T item, safe_ptr<Slot> slotsPtr, safe_ptr<int> bucketsPtr) {
uint hashCode = GetHashCode(item) & HashSetAuto<T>.LOWER31_BIT_MASK;
for (int i = bucketsPtr[hashCode % this.buckets.Length] - 1; i >= 0; i = (slotsPtr + i).ptr->next) {
if ((slotsPtr + i).ptr->hashCode == hashCode &&
Equal((slotsPtr + i).ptr->value, item) == true) {
return true;
}
}
return false;
}
[INLINE(256)]
public readonly bool Contains(T item, uint hashCode, safe_ptr<Slot> slotsPtr, safe_ptr<int> bucketsPtr) {
for (int i = bucketsPtr[hashCode % this.buckets.Length] - 1; i >= 0; i = (slotsPtr + i).ptr->next) {
if ((slotsPtr + i).ptr->hashCode == hashCode &&
Equal((slotsPtr + i).ptr->value, item) == true) {
return true;
}
}
return false;
}
[INLINE(256)]
public void RemoveExcept(in HashSetAuto<T> other) {
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
for (int i = 0; i < this.lastIndex; i++) {
var slot = (slotsPtr + i);
if (slot.ptr->hashCode >= 0) {
var item = slot.ptr->value;
if (!other.Contains(item)) {
this.Remove(item);
if (this.count == 0) return;
}
}
}
}
[INLINE(256)]
public void Remove(in HashSetAuto<T> other) {
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
for (int i = 0; i < this.lastIndex; i++) {
var slot = (slotsPtr + i);
if (slot.ptr->hashCode >= 0) {
var item = slot.ptr->value;
if (other.Contains(item)) {
this.Remove(item);
if (this.count == 0) return;
}
}
}
}
[INLINE(256)]
public void Add(in HashSetAuto<T> other) {
var slotsPtr = (safe_ptr<Slot>)other.slots.GetUnsafePtrCached();
for (int i = 0; i < other.lastIndex; i++) {
var slot = (slotsPtr + i);
if (slot.ptr->hashCode >= 0) {
this.Add(slot.ptr->value);
}
}
}
/// <summary>
/// Remove item from this hashset
/// </summary>
/// <param name="item">item to remove</param>
/// <returns>true if removed; false if not (i.e. if the item wasn't in the HashSet)</returns>
[INLINE(256)]
public bool Remove(T item) {
if (this.buckets.IsCreated == true) {
uint hashCode = GetHashCode(item) & HashSetAuto<T>.LOWER31_BIT_MASK;
uint bucket = hashCode % this.buckets.Length;
int last = -1;
var bucketsPtr = (safe_ptr<int>)this.buckets.GetUnsafePtrCached();
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
for (int i = *(bucketsPtr + bucket).ptr - 1; i >= 0; last = i, i = (slotsPtr + i).ptr->next) {
var slot = slotsPtr + i;
if (slot.ptr->hashCode == hashCode &&
Equal(slot.ptr->value, item) == true) {
if (last < 0) {
// first iteration; update buckets
*(bucketsPtr + bucket).ptr = slot.ptr->next + 1;
}
else {
// subsequent iterations; update 'next' pointers
(slotsPtr + last).ptr->next = slot.ptr->next;
}
slot.ptr->hashCode = -1;
slot.ptr->value = default;
slot.ptr->next = this.freeList;
this.hash ^= GetHashCode(item);
++this.version;
if (--this.count == 0) {
this.lastIndex = 0;
this.freeList = -1;
} else {
this.freeList = i;
}
return true;
}
}
}
// either m_buckets is null or wasn't found
return false;
}
/// <summary>
/// Initializes buckets and slots arrays. Uses suggested capacity by finding next prime
/// greater than or equal to capacity.
/// </summary>
/// <param name="ent"></param>
/// <param name="capacity"></param>
[INLINE(256)]
private void Initialize(in Ent ent, uint capacity) {
uint size = HashHelpers.GetPrime(capacity);
this.buckets = new MemArrayAuto<uint>(in ent, size);
this.slots = new MemArrayAuto<Slot>(in ent, size);
var slots = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
for (int i = 0; i < this.slots.Length; ++i) {
(*(slots + i).ptr).hashCode = -1;
}
this.freeList = -1;
}
/// <summary>
/// Expand to new capacity. New capacity is next prime greater than or equal to suggested
/// size. This is called when the underlying array is filled. This performs no
/// defragmentation, allowing faster execution; note that this is reasonable since
/// AddIfNotPresent attempts to insert new elements in re-opened spots.
/// </summary>
[INLINE(256)]
private void IncreaseCapacity() {
uint newSize = HashHelpers.ExpandPrime(this.count);
if (newSize <= this.count) {
throw new System.ArgumentException();
}
// Able to increase capacity; copy elements to larger array and rehash
this.SetCapacity(newSize, false);
}
/// <summary>
/// Set the underlying buckets array to size newSize and rehash. Note that newSize
/// *must* be a prime. It is very likely that you want to call IncreaseCapacity()
/// instead of this method.
/// </summary>
[INLINE(256)]
private void SetCapacity(uint newSize, bool forceNewHashCodes) {
var newSlots = new MemArrayAuto<Slot>(this.ent, newSize);
if (this.slots.IsCreated == true) {
NativeArrayUtils.CopyNoChecks(in this.slots, 0, ref newSlots, 0, this.lastIndex);
}
if (forceNewHashCodes == true) {
for(int i = 0; i < this.lastIndex; i++) {
if(newSlots[i].hashCode != -1) {
newSlots[i].hashCode = (int)GetHashCode(newSlots[i].value);
}
}
}
var newBuckets = new MemArrayAuto<uint>(this.ent, newSize);
for (uint i = 0; i < this.lastIndex; ++i) {
uint bucket = (uint)(newSlots[i].hashCode % newSize);
newSlots[i].next = (int)newBuckets[bucket] - 1;
newBuckets[bucket] = i + 1;
}
if (this.slots.IsCreated == true) this.slots.Dispose();
if (this.buckets.IsCreated == true) this.buckets.Dispose();
this.slots = newSlots;
this.buckets = newBuckets;
}
/// <summary>
/// Add item to this HashSet. Returns bool indicating whether item was added (won't be
/// added if already present)
/// </summary>
/// <param name="value"></param>
/// <returns>true if added, false if already present</returns>
[INLINE(256)]
public bool Add(T value) {
E.IS_CREATED(this);
var bucketsPtr = (safe_ptr<int>)this.buckets.GetUnsafePtrCached();
var slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
uint hashCode = GetHashCode(value) & HashSetAuto<T>.LOWER31_BIT_MASK;
uint bucket = hashCode % this.buckets.Length;
for (int i = *(bucketsPtr + bucket).ptr - 1; i >= 0; i = (slotsPtr + i).ptr->next) {
var slot = slotsPtr + i;
if (slot.ptr->hashCode == hashCode &&
Equal(slot.ptr->value, value) == true) {
return false;
}
}
this.hash ^= GetHashCode(value);
uint index;
if (this.freeList >= 0) {
index = (uint)this.freeList;
this.freeList = (slotsPtr + index).ptr->next;
} else {
if (this.lastIndex == this.slots.Length) {
this.IncreaseCapacity();
// this will change during resize
bucketsPtr = (safe_ptr<int>)this.buckets.GetUnsafePtrCached();
slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
bucket = hashCode % this.buckets.Length;
}
index = this.lastIndex;
++this.lastIndex;
}
{
var slot = slotsPtr + index;
slot.ptr->hashCode = (int)hashCode;
slot.ptr->value = value;
slot.ptr->next = *(bucketsPtr + bucket).ptr - 1;
*(bucketsPtr + bucket).ptr = (int)(index + 1u);
++this.count;
++this.version;
}
return true;
}
[INLINE(256)]
public bool Add(T value, ref safe_ptr<int> bucketsPtr, ref safe_ptr<Slot> slotsPtr) {
E.IS_CREATED(this);
uint hashCode = GetHashCode(value) & HashSetAuto<T>.LOWER31_BIT_MASK;
uint bucket = hashCode % this.buckets.Length;
for (int i = *(bucketsPtr + bucket).ptr - 1; i >= 0; i = (slotsPtr + i).ptr->next) {
var slot = slotsPtr + i;
if (slot.ptr->hashCode == hashCode &&
Equal(slot.ptr->value, value) == true) {
return false;
}
}
this.hash ^= GetHashCode(value);
uint index;
if (this.freeList >= 0) {
index = (uint)this.freeList;
this.freeList = (slotsPtr + index).ptr->next;
} else {
if (this.lastIndex == this.slots.Length) {
this.IncreaseCapacity();
// this will change during resize
bucketsPtr = (safe_ptr<int>)this.buckets.GetUnsafePtrCached();
slotsPtr = (safe_ptr<Slot>)this.slots.GetUnsafePtrCached();
bucket = hashCode % this.buckets.Length;
}
index = this.lastIndex;
++this.lastIndex;
}
{
var slot = slotsPtr + index;
slot.ptr->hashCode = (int)hashCode;
slot.ptr->value = value;
slot.ptr->next = *(bucketsPtr + bucket).ptr - 1;
*(bucketsPtr + bucket).ptr = (int)(index + 1u);
++this.count;
++this.version;
}
return true;
}
[INLINE(256)]
public readonly uint GetHash() {
return this.hash;
}
[INLINE(256)]
public void CopyFrom(in HashSetAuto<T> other) {
NativeArrayUtils.CopyExact(in other.buckets, ref this.buckets);
this.slots.CopyFrom(in other.slots);
var thisBuckets = this.buckets;
var thisSlots = this.slots;
this = other;
this.buckets = thisBuckets;
this.slots = thisSlots;
}
[INLINE(256)]
public static bool Equal(T v1, T v2) {
return v1.Equals(v2);
}
[INLINE(256)]
public static uint GetHashCode(T item) {
return (uint)item.GetHashCode();
}
}
}
| 0 | 0.993151 | 1 | 0.993151 | game-dev | MEDIA | 0.504295 | game-dev | 0.980611 | 1 | 0.980611 |
SolarianZ/UnityPlayableGraphMonitorTool | 3,743 | Editor/Scripts/Pool/PlayableNodePool.cs | using System.Collections.Generic;
using GBG.PlayableGraphMonitor.Editor.Node;
using UnityEngine.Playables;
using UGraphView = UnityEditor.Experimental.GraphView.GraphView;
namespace GBG.PlayableGraphMonitor.Editor.Pool
{
public class PlayableNodePool<T> : IPlayableNodePool where T : PlayableNode, new()
{
private readonly UGraphView _graphView;
private readonly Dictionary<PlayableHandle, T> _activeNodeTable =
new Dictionary<PlayableHandle, T>();
private readonly Dictionary<PlayableHandle, T> _dormantNodeTable =
new Dictionary<PlayableHandle, T>();
public PlayableNodePool(UGraphView graphView)
{
_graphView = graphView;
}
public bool IsNodeActive(Playable playable)
{
return _activeNodeTable.ContainsKey(playable.GetHandle());
}
public T GetActiveNode(Playable playable)
{
return _activeNodeTable[playable.GetHandle()];
}
public bool TryGetActiveNode(Playable playable, out T node)
{
return _activeNodeTable.TryGetValue(playable.GetHandle(), out node);
}
public IEnumerable<T> GetActiveNodes()
{
return _activeNodeTable.Values;
}
public T Alloc(Playable playable)
{
var handle = playable.GetHandle();
if (_activeNodeTable.TryGetValue(handle, out var node))
{
return node;
}
// if (!_dormantNodeTable.Remove(handle, out node)) // Unavailable in Unity 2019
// {
// node = new T();
// _graphView.AddElement(node);
// }
if (_dormantNodeTable.TryGetValue(handle, out node))
{
_dormantNodeTable.Remove(handle);
}
else
{
node = new T();
_graphView.AddElement(node);
}
_activeNodeTable.Add(handle, node);
return node;
}
public void Recycle(T node)
{
node.Release();
var handle = node.Playable.GetHandle();
_activeNodeTable.Remove(handle);
// _dormantNodeTable.TryAdd(handle, node); // Unavailable in Unity 2019
_dormantNodeTable[handle] = node;
}
public void RecycleAllActiveNodes()
{
foreach (var node in _activeNodeTable.Values)
{
node.Release();
var handle = node.Playable.GetHandle();
_dormantNodeTable.Add(handle, node);
}
_activeNodeTable.Clear();
}
public void RemoveDormantNodesFromView()
{
_graphView.DeleteElements(_dormantNodeTable.Values);
_dormantNodeTable.Clear();
}
#region Interface
PlayableNode IPlayableNodePool.GetActiveNode(Playable playable)
{
return GetActiveNode(playable);
}
bool IPlayableNodePool.TryGetActiveNode(Playable playable, out PlayableNode node)
{
if (TryGetActiveNode(playable, out var tNode))
{
node = tNode;
return true;
}
node = null;
return false;
}
IEnumerable<PlayableNode> IPlayableNodePool.GetActiveNodes()
{
return GetActiveNodes();
}
PlayableNode IPlayableNodePool.Alloc(Playable playable)
{
return Alloc(playable);
}
void IPlayableNodePool.Recycle(PlayableNode node)
{
Recycle((T)node);
}
#endregion
}
} | 0 | 0.880147 | 1 | 0.880147 | game-dev | MEDIA | 0.914505 | game-dev | 0.648598 | 1 | 0.648598 |
HowToRts/HowToRts.github.io | 15,997 | examples/presentation/flow-field-improved/src.js | //How big the grid is in pixels
var gridWidthPx = 800, gridHeightPx = 448;
var gridPx = 32;
//Grid size in actual units
var gridWidth = gridWidthPx / gridPx;
var gridHeight = gridHeightPx / gridPx;
//Storage for the current agents and obstacles
var agents = new Array();
var obstacles = new Array();
//The physics world
var world = new B2World(B2Vec2.Zero, true);
//Defines an agent that moves
Agent = function (pos) {
this.rotation = 0;
this.maxForce = 100; //rate of acceleration
this.maxSpeed = 6; //grid squares / second
this.radius = 0.23;
this.neighbourRadius = 2;
this.maxForceSquared = this.maxForce * this.maxForce;
this.maxSpeedSquared = this.maxSpeed * this.maxSpeed;
//Create a physics body for the agent
var fixDef = new B2FixtureDef();
var bodyDef = new B2BodyDef();
fixDef.density = 20.0;
fixDef.friction = 0.0;
fixDef.restitution = 0.0;
fixDef.shape = new B2CircleShape(this.radius);
bodyDef.type = B2Body.b2_dynamicBody;
//bodyDef.linearDamping = 0.1;
bodyDef.position.SetV(pos);
this.body = world.CreateBody(bodyDef);
this.fixture = this.body.CreateFixture(fixDef);
};
Agent.prototype.position = function () {
return this.body.GetPosition();
};
Agent.prototype.velocity = function () {
return this.body.GetLinearVelocity();
};
var destination = new B2Vec2(gridWidth - 1, gridHeight / 2); //middle right
//Called to start the game
function startGame() {
//for (var yPos = 1; yPos < gridHeight - 1; yPos++) {
// agents.push(new Agent(new B2Vec2(0, yPos)));
// agents.push(new Agent(new B2Vec2(1, yPos)));
// agents.push(new Agent(new B2Vec2(2, yPos)));
//}
//for (var i = 0; i < gridHeight; i++) {
// if (i == gridHeight / 2 || i == gridHeight / 2 - 1) {
// continue;
// }
// obstacles.push(new B2Vec2(8, i));
// obstacles.push(new B2Vec2(7, i));
//}
//for (var i = 0; i < 30; i++) {
// var x = 1 + Math.floor(Math.random() * (gridWidth - 3));
// var y = Math.floor(Math.random() * (gridHeight - 2));
// obstacles.push(new B2Vec2(x, y));
//}
for (var i = 0; i < obstacles.length; i++) {
var pos = obstacles[i];
createObstacleBody(pos);
}
generateDijkstraGrid();
generateFlowField();
stage.addEventListener('stagemouseup', function (ev) {
var x = (ev.stageX / gridPx) | 0;
var y = (ev.stageY / gridPx) | 0;
var found = false;
for (var i = 0; i < obstacles.length; i++) {
if (obstacles[i].x == x && obstacles[i].y == y) {
world.DestroyBody(obstacles[i].body);
obstacles.splice(i, 1);
found = true;
break;
}
}
if (!found) {
var pos = new B2Vec2(x, y);
createObstacleBody(pos)
obstacles.push(pos);
}
redrawObstacles();
generateDijkstraGrid();
generateFlowField();
updateWeightsAndFieldVisuals(); //Call in to the renderer to redraw the weights and flow field
});
}
function createObstacleBody(pos) {
//Create a physics body for the agent
var fixDef = new B2FixtureDef();
var bodyDef = new B2BodyDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
fixDef.shape = new B2PolygonShape();
fixDef.shape.SetAsBox(0.5, 0.5);
bodyDef.type = B2Body.b2_staticBody;
bodyDef.position.SetV(pos);
pos.body = world.CreateBody(bodyDef);
pos.body.CreateFixture(fixDef);
}
function round(val) {
return val.toFixed(1);
}
var spawnTime = 0;
//called periodically to update the game
//dt is the change of time since the last update (in seconds)
function gameTick(dt) {
var i, agent;
spawnTime -= dt;
if (spawnTime < 0) {
spawnTime += 0.5;
agents.push(new Agent(new B2Vec2(0, 0)));
agents.push(new Agent(new B2Vec2(0, (gridHeight - 1) / 4)));
agents.push(new Agent(new B2Vec2(0, (gridHeight - 0) / 2)));
agents.push(new Agent(new B2Vec2(0, (gridHeight - 1) * 3 / 4)));
agents.push(new Agent(new B2Vec2(0, (gridHeight - 1))));
}
//clean out deadies
for (i = agents.length - 1; i >= 0; i--) {
agent = agents[i];
if (agent.position().x > gridWidth) {
world.DestroyBody(agent.body);
stage.removeChild(agentBitmaps[agent._id])
stage.removeChild( agentForceLines[agent._id]);
agents.splice(i, 1);
}
}
//Calculate steering and flocking forces for all agents
for (i = agents.length - 1; i >= 0; i--) {
agent = agents[i];
//Work out our behaviours
var ff = steeringBehaviourFlowField(agent);
var sep = steeringBehaviourSeparation(agent);
var alg = steeringBehaviourAlignment(agent);
var coh = steeringBehaviourCohesion(agent);
//For visually debugging forces agent.forces = [ff.Copy(), sep.Copy(), alg.Copy(), coh.Copy()];
agent.forceToApply = ff.Add(sep.Multiply(1)).Add(alg.Multiply(0.3)).Add(coh.Multiply(0.15));
var lengthSquared = agent.forceToApply.LengthSquared();
if (lengthSquared > agent.maxForceSquared) {
agent.forceToApply.Multiply(agent.maxForce / Math.sqrt(lengthSquared));
}
}
//Move agents based on forces being applied (aka physics)
for (i = agents.length - 1; i >= 0; i--) {
agent = agents[i];
//Apply the force
//console.log(i + ': ' + agent.forceToApply.x + ', ' + agent.forceToApply.y);
agent.body.ApplyImpulse(agent.forceToApply.Multiply(dt), agent.position());
//Calculate our new movement angle TODO: Should probably be done after running step
agent.rotation = agent.velocity().Angle();
}
world.Step(dt, 10, 10);
world.ClearForces();
}
function steeringBehaviourFlowField(agent) {
//Work out the force to apply to us based on the flow field grid squares we are on.
//we apply bilinear interpolation on the 4 grid squares nearest to us to work out our force.
// http://en.wikipedia.org/wiki/Bilinear_interpolation#Nonlinear
//Top left Coordinate of the 4
var floor = agent.position().Copy().Floor();
//The 4 weights we'll interpolate, see http://en.wikipedia.org/wiki/File:Bilininterp.png for the coordinates
var f00 = (isValid(floor.x, floor.y) ? flowField[floor.x][floor.y] : B2Vec2.Zero).Copy();
var f01 = (isValid(floor.x, floor.y + 1) ? flowField[floor.x][floor.y + 1] : B2Vec2.Zero).Copy();
var f10 = (isValid(floor.x + 1, floor.y) ? flowField[floor.x + 1][floor.y] : B2Vec2.Zero).Copy();
var f11 = (isValid(floor.x + 1, floor.y + 1) ? flowField[floor.x + 1][floor.y + 1] : B2Vec2.Zero).Copy();
//Do the x interpolations
var xWeight = agent.position().x - floor.x;
var top = f00.Multiply(1 - xWeight).Add(f10.Multiply(xWeight));
var bottom = f01.Multiply(1 - xWeight).Add(f11.Multiply(xWeight));
//Do the y interpolation
var yWeight = agent.position().y - floor.y;
//This is now the direction we want to be travelling in (needs to be normalized)
var desiredDirection = top.Multiply(1 - yWeight).Add(bottom.Multiply(yWeight));
desiredDirection.Normalize();
//If we are centered on a grid square with no vector this will happen
if (isNaN(desiredDirection.LengthSquared())) {
return desiredDirection.SetZero();
}
return steerTowards(agent, desiredDirection);
}
function steeringBehaviourSeek(agent, dest) {
if (dest.x == agent.position().x && dest.y == agent.position().y) {
return new B2Vec2();
}
//Desired change of location
var desired = dest.Copy().Subtract(agent.position());
//Desired velocity (move there at maximum speed)
desired.Multiply(agent.maxSpeed / desired.Length());
//The velocity change we want
var velocityChange = desired.Subtract(agent.velocity());
//Convert to a force
return velocityChange.Multiply(agent.maxForce / agent.maxSpeed);
}
function steeringBehaviourSeparation(agent) {
var totalForce = new B2Vec2();
var neighboursCount = 0;
for (var i = 0; i < agents.length; i++) {
var a = agents[i];
if (a != agent) {
var distance = agent.position().DistanceTo(a.position());
if (distance < agent.neighbourRadius && distance > 0) {
//Vector to other agent
var pushForce = agent.position().Copy().Subtract(a.position());
var length = pushForce.Normalize(); //Normalize returns the original length
var r = (agent.radius + a.radius);
totalForce.Add(pushForce.Multiply(1 - (length / agent.neighbourRadius)))
neighboursCount++;
}
}
}
if (neighboursCount == 0) {
return totalForce; //Zero
}
return totalForce.Multiply(agent.maxForce / neighboursCount);
}
function steeringBehaviourCohesion(agent) {
//Start with just our position
var centerOfMass = new B2Vec2()//agent.position().Copy();
var neighboursCount = 0;
for (var i = 0; i < agents.length; i++) {
var a = agents[i];
if (a != agent) {
var distance = agent.position().DistanceTo(a.position());
if (distance < agent.neighbourRadius) {
//sum up the position of our neighbours
centerOfMass.Add(a.position());
neighboursCount++;
}
}
}
if (neighboursCount == 0) {
return new B2Vec2();
}
//Get the average position of ourself and our neighbours
centerOfMass.Divide(neighboursCount);
//seek that position
return steeringBehaviourSeek(agent, centerOfMass);
}
function steeringBehaviourAlignment(agent) {
var averageHeading = new B2Vec2();
var neighboursCount = 0;
//for each of our neighbours (including ourself)
for (var i = 0; i < agents.length; i++) {
var a = agents[i];
var distance = agent.position().DistanceTo(a.position());
//That are within the max distance and are moving
if (distance < agent.neighbourRadius && a.velocity().Length() > 0) {
//Sum up our headings
var head = a.velocity().Copy();
head.Normalize();
averageHeading.Add(head);
neighboursCount++;
}
}
if (neighboursCount == 0) {
return averageHeading; //Zero
}
//Divide to get the average heading
averageHeading.Divide(neighboursCount);
//Steer towards that heading
return steerTowards(agent, averageHeading);
}
function steerTowards(agent, desiredDirection) {
//Multiply our direction by speed for our desired speed
var desiredVelocity = desiredDirection.Multiply(agent.maxSpeed);
//The velocity change we want
var velocityChange = desiredVelocity.Subtract(agent.velocity());
//Convert to a force
return velocityChange.Multiply(agent.maxForce / agent.maxSpeed);
}
var dijkstraGrid = new Array(gridWidth);
for (var x = 0; x < gridWidth; x++) {
dijkstraGrid[x] = new Array(gridHeight);
}
var losGrid = new Array(gridWidth);
for (x = 0; x < gridWidth; x++) {
losGrid[x] = new Array(gridHeight);
}
var flowField = new Array(gridWidth);
for (x = 0; x < gridWidth; x++) {
flowField[x] = new Array(gridHeight);
}
Math.sign = Math.sign || function (number) { return number > 0 ? 1 : number < 0 ? -1 : 0; };
function generateDijkstraGrid() {
//Generate an empty grid
//set all places as weight null, which will stand for unvisited
for (var x = 0; x < gridWidth; x++) {
var arr = dijkstraGrid[x],
arr2 = losGrid[x];
for (var y = 0; y < gridHeight; y++) {
arr[y] = null;
arr2[y] = false;
}
}
//Set all places where obstacles are as being weight MAXINT, which will stand for not able to go here
for (var i = 0; i < obstacles.length; i++) {
var t = obstacles[i];
dijkstraGrid[t.x][t.y] = Number.MAX_VALUE;
}
//flood fill out from the end point
var pathEnd = destination.Copy();
pathEnd.Round();
pathEnd.distance = 0;
dijkstraGrid[pathEnd.x][pathEnd.y] = 0;
losGrid[pathEnd.x][pathEnd.y] = true;
var toVisit = [pathEnd];
//for each node we need to visit, starting with the pathEnd
for (i = 0; i < toVisit.length; i++) {
var at = toVisit[i];
//Calculate if we have LOS
//Only need to see if don't have LOS if we aren't the end
if (at !== pathEnd) {
calculateLos(at, pathEnd);
}
var neighbours = straightNeighboursOf(at);
//for each neighbour of this node (only straight line neighbours, not diagonals)
for (var j = 0; j < neighbours.length; j++) {
var n = neighbours[j];
//We will only ever visit every node once as we are always visiting nodes in the most efficient order
if (dijkstraGrid[n.x][n.y] === null) {
n.distance = at.distance + 1;
dijkstraGrid[n.x][n.y] = n.distance;
toVisit.push(n);
}
}
}
}
function calculateLos(at, pathEnd) {
var xDif = pathEnd.x - at.x;
var yDif = pathEnd.y - at.y;
var xDifAbs = Math.abs(xDif);
var yDifAbs = Math.abs(yDif);
var hasLos = false;
var xDifOne = Math.sign(xDif);
var yDifOne = Math.sign(yDif);
//Check the direction we are furtherest from the destination on (or both if equal)
// If it has LOS then we might
//Check in the x direction
if (xDifAbs >= yDifAbs) {
if (losGrid[at.x + xDifOne][at.y]) {
hasLos = true;
}
}
//Check in the y direction
if (yDifAbs >= xDifAbs) {
if (losGrid[at.x][at.y + yDifOne]) {
hasLos = true;
}
}
//If we are not a straight line vertically/horizontally to the exit
if (yDifAbs > 0 && xDifAbs > 0) {
//If the diagonal doesn't have LOS, we don't
if (!losGrid[at.x + xDifOne][at.y + yDifOne]) {
hasLos = false;
} else if (yDifAbs === xDifAbs) {
//If we are an exact diagonal and either straight direction is a wall, we don't have LOS
if (dijkstraGrid[at.x + xDifOne][at.y] === Number.MAX_VALUE || dijkstraGrid[at.x][at.y + yDifOne] === Number.MAX_VALUE) {
hasLos = false;
}
}
}
//It's a definite now
losGrid[at.x][at.y] = hasLos;
//TODO: Could replace our distance with a direct distance?
// Might not be worth it, would need to use a priority queue for the open list.
}
function generateFlowField() {
var x, y;
//Generate an empty grid, set all places as Vector2.zero, which will stand for no good direction
for (x = 0; x < gridWidth; x++) {
var arr = flowField[x];
for (y = 0; y < gridHeight; y++) {
arr[y] = B2Vec2.Zero;
}
}
//for each grid square
for (x = 0; x < gridWidth; x++) {
for (y = 0; y < gridHeight; y++) {
//Obstacles have no flow value
if (dijkstraGrid[x][y] == Number.MAX_VALUE) {
continue;
}
if (losGrid[x][y]) {
//Just point straight at the destination
var p = flowField[x][y] = destination.Copy();
p.x -= x;
p.y -= y;
p.Normalize();
continue;
}
var pos = new B2Vec2(x, y);
var neighbours = allNeighboursOf(pos);
//Go through all neighbours and find the one with the lowest distance
var min = null;
var minDist = 0;
for (var i = 0; i < neighbours.length; i++) {
var n = neighbours[i];
var dist = dijkstraGrid[n.x][n.y] - dijkstraGrid[pos.x][pos.y];
if (dist < minDist) {
min = n;
minDist = dist;
}
}
//If we found a valid neighbour, point in its direction
if (min != null) {
var v = min.Copy().Subtract(pos);
v.Normalize();
flowField[x][y] = v;
}
}
}
}
function straightNeighboursOf(v) {
var res = [];
if (v.x > 0) {
res.push(new B2Vec2(v.x - 1, v.y));
}
if (v.y > 0) {
res.push(new B2Vec2(v.x, v.y - 1));
}
if (v.x < gridWidth - 1) {
res.push(new B2Vec2(v.x + 1, v.y));
}
if (v.y < gridHeight - 1) {
res.push(new B2Vec2(v.x, v.y + 1));
}
return res;
}
//Helper method. Returns true if this grid location is on the grid and not impassable
function isValid(x, y) {
return x >= 0 && y >= 0 && x < gridWidth && y < gridHeight && dijkstraGrid[x][y] != Number.MAX_VALUE;
}
//Returns the non-obstructed neighbours of the given grid location.
//Diagonals are only included if their neighbours are also not obstructed
function allNeighboursOf(v) {
var res = [],
x = v.x,
y = v.y;
var up = isValid(x, y - 1),
down = isValid(x, y + 1),
left = isValid(x - 1, y),
right = isValid(x + 1, y);
//We test each straight direction, then subtest the next one clockwise
if (left) {
res.push(new B2Vec2(x - 1, y));
//left up
if (up && isValid(x - 1, y - 1)) {
res.push(new B2Vec2(x - 1, y - 1));
}
}
if (up) {
res.push(new B2Vec2(x, y - 1));
//up right
if (right && isValid(x + 1, y - 1)) {
res.push(new B2Vec2(x + 1, y - 1));
}
}
if (right) {
res.push(new B2Vec2(x + 1, y));
//right down
if (down && isValid(x + 1, y + 1)) {
res.push(new B2Vec2(x + 1, y + 1));
}
}
if (down) {
res.push(new B2Vec2(x, y + 1));
//down left
if (left && isValid(x - 1, y + 1)) {
res.push(new B2Vec2(x - 1, y + 1));
}
}
return res;
} | 0 | 0.862486 | 1 | 0.862486 | game-dev | MEDIA | 0.691038 | game-dev | 0.982752 | 1 | 0.982752 |
NetLogo/models | 87,620 | HubNet Activities/Disease HubNet.nlogox | <?xml version="1.0" encoding="utf-8"?>
<model version="NetLogo 7.0.0" snapToGrid="false">
<code><![CDATA[;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variable and Breed declarations ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
globals
[
run-number
;; variables used to assign unique color and shape to clients
shape-names ;; list that holds the names of the non-sick shapes a student's turtle can have
colors ;; list that holds the colors used for students' turtles
color-names ;; list that holds the names of the colors used for students' turtles
used-shape-colors ;; list that holds the shape-color pairs that are already being used
max-possible-codes ;; total number of possible unique shape/color combinations
;; quick start instructions variables
quick-start ;; current quickstart instruction displayed in the quickstart monitor
qs-item ;; index of the current quickstart instruction
qs-items ;; list of quickstart instructions
num-infected-last-plotted ;; used in plotting only
;; number of turtles that had infected? = true the last time we plotted.
]
turtles-own
[
infected? ;; if a turtle is sick, infected? is true, otherwise, it is false
base-shape ;; original shape of a turtle
step-size ;; the amount that a turtle will go forward in the current direction
]
breed [ androids android ] ;; created by the CREATE ANDROIDS button; not controlled by anyone, but can become sick and spread sickness
breed [ students student ] ;; created and controlled by the clients
students-own
[
user-id ;; unique id, input by the client when they log in, to identify each student turtle
]
;;;;;;;;;;;;;;;;;;;;;;
;; Setup Procedures ;;
;;;;;;;;;;;;;;;;;;;;;;
to startup
hubnet-reset
setup-vars
setup-quick-start
reset-ticks
end
to setup
ask androids [ die ]
cure-all
reset-ticks
end
;; heals all sick turtles, clears and sets up the plot,
;; and clears the lists sent to the calculators
to cure-all
ask turtles
[
set infected? false
if breed = students
[ update-sick?-monitor ]
set shape base-shape
]
set run-number run-number + 1
reset-ticks
end
;; initialize global variables
to setup-vars
set shape-names ["box" "star" "wheel" "target" "cat" "dog"
"butterfly" "leaf" "car" "airplane"
"monster" "key" "cow skull" "ghost"
"cactus" "moon" "heart"]
;; these colors were chosen with the goal of having colors
;; that are readily distinguishable from each other, and that
;; have names that everyone knows (e.g. no "cyan"!), and that
;; contrast sufficiently with the red infection dots and the
;; gray androids
set colors (list white brown green yellow
(violet + 1) (sky + 1))
set color-names ["white" "brown" "green" "yellow"
"purple" "blue"]
set max-possible-codes (length colors * length shape-names)
set used-shape-colors []
set run-number 1
end
;; creates turtles that wander at random
to make-androids
create-androids number
[
move-to one-of patches
face one-of neighbors4
set color gray
set infected? false
set base-shape "android"
set shape base-shape
set step-size 1
]
end
;;;;;;;;;;;;;;;;;;;;;;;;
;; Runtime Procedures ;;
;;;;;;;;;;;;;;;;;;;;;;;;
to go
;; get commands and data from the clients
listen-clients
every 0.1
[
;;allow the androids to wander around the view
if wander? [ androids-wander ]
ask turtles with [ infected? ]
[ spread-disease ]
;; keeps track of the number of times through the go procedure (if there is at least one turtle infected)
;; use an ifelse here to avoid redundant displays because tick forces a display.
;; we only want to keep track of time once the first turtle has been infected.
ifelse count turtles with [infected?] > 0
[ tick ]
[ display ]
]
end
;; controls the motion of the androids
to androids-wander
every android-delay
[
ask androids
[
face one-of neighbors4
fd 1
]
]
end
;; additional check infect called when student moves to new patch
;; added to avoid rewarding movement
to student-move-check-infect
if infected?
[ spread-disease ]
ask other turtles-here with [ infected? ]
[ ask myself [ maybe-get-sick ] ]
end
;; spread disease to other turtles here
to spread-disease
ask other turtles-here [ maybe-get-sick ]
end
;; turtle procedure -- roll the dice and maybe get sick
to maybe-get-sick
if not infected? [
if ((random 100) + 1) <= infection-chance
[ get-sick ] ]
end
;; turtle procedure -- set the appropriate variables to make this turtle sick
to get-sick
set infected? true
set-sick-shape
if breed = students
[ update-sick?-monitor ]
end
;; turtle procedure -- change the shape of turtles to its sick shape
;; if show-sick? is true and change the shape to the base-shape if
;; show-sick? is false
to set-sick-shape
ifelse show-sick?
[
;; we want to check if the turtles shape is already a sick shape
;; to prevent flickering in the turtles
if shape != word base-shape " sick"
[ set shape word base-shape " sick" ]
]
[
;; we want to check if the turtles shape is already a base-shape
;; to prevent flickering in the turtles
if shape != base-shape
[ set shape base-shape ]
]
end
;; causes the initial infection in the turtle population --
;; infects a random healthy turtle until the desired number of
;; turtles are infected
to infect-turtles
let healthy-turtles turtles with [ not infected? ]
ifelse count healthy-turtles < initial-number-sick
[
ask healthy-turtles
[
get-sick
set-sick-shape
]
user-message "There are no more healthy turtles to infect. Infection stopped."
stop
]
[
ask n-of initial-number-sick healthy-turtles
[
get-sick
set-sick-shape
]
]
end
;;;;;;;;;;;;;;;;;;;;;;;
;; HubNet Procedures ;;
;;;;;;;;;;;;;;;;;;;;;;;
;; determines which client sent a command, and what the command was
to listen-clients
while [ hubnet-message-waiting? ]
[
hubnet-fetch-message
ifelse hubnet-enter-message?
[ create-new-student ]
[
ifelse hubnet-exit-message?
[ remove-student ]
[
ask students with [ user-id = hubnet-message-source ]
[ execute-command hubnet-message-tag ]
]
]
]
ask students
[ update-sick?-monitor ]
end
;; NetLogo knows what each student turtle is supposed to be
;; doing based on the tag sent by the node:
;; step-size - set the turtle's step-size
;; Up - make the turtle move up by step-size
;; Down - make the turtle move down by step-size
;; Right - make the turtle move right by step-size
;; Left - make the turtle move left by step-size
;; Get a Different Turtle - change the turtle's shape and color
to execute-command [command]
if command = "step-size"
[
set step-size hubnet-message
stop
]
if command = "Up"
[ execute-move 0 stop ]
if command = "Down"
[ execute-move 180 stop ]
if command = "Right"
[ execute-move 90 stop ]
if command = "Left"
[ execute-move 270 stop ]
if command = "Change Appearance"
[ execute-change-turtle stop ]
end
;; Create a turtle, set its shape, color, and position
;; and tell the node what its turtle looks like and where it is
to create-new-student
create-students 1
[
setup-student-vars
send-info-to-clients
;; we want to make sure that the clients all have the same plot ranges,
;; so when somebody logs in, set the plot ranges to themselves so that
;; everybody will have the same size plots.
set-plot-y-range plot-y-min plot-y-max
set-plot-x-range plot-x-min plot-x-max
]
end
;; sets the turtle variables to appropriate initial values
to setup-student-vars ;; turtle procedure
set user-id hubnet-message-source
set-unique-shape-and-color
move-to one-of patches
face one-of neighbors4
set infected? false
set step-size 1
end
;; pick a base-shape and color for the turtle
to set-unique-shape-and-color
let code random max-possible-codes
while [member? code used-shape-colors and count students < max-possible-codes]
[
set code random max-possible-codes
]
set used-shape-colors (lput code used-shape-colors)
set base-shape item (code mod length shape-names) shape-names
set shape base-shape
set color item (code / length shape-names) colors
end
;; report the string version of the turtle's color
to-report color-string [color-value]
report item (position color-value colors) color-names
end
;; sends the appropriate monitor information back to the client
to send-info-to-clients
hubnet-send user-id "You are a:" (word (color-string color) " " base-shape)
hubnet-send user-id "Located at:" (word "(" pxcor "," pycor ")")
update-sick?-monitor
end
to update-sick?-monitor
ifelse show-sick-on-clients?
[ hubnet-send user-id "Sick?" infected? ]
[ hubnet-send user-id "Sick?" "N/A" ]
end
;; Kill the turtle, set its shape, color, and position
;; and tell the node what its turtle looks like and where it is
to remove-student
ask students with [user-id = hubnet-message-source]
[
set used-shape-colors remove my-code used-shape-colors
die
]
end
;; translates a student turtle's shape and color into a code
to-report my-code
report (position base-shape shape-names) + (length shape-names) * (position color colors)
end
;; Cause the students to move forward step-size in new-heading's heading
to execute-move [new-heading]
set heading new-heading
fd step-size
hubnet-send user-id "Located at:" (word "(" pxcor "," pycor ")")
;; maybe infect or get infected by turtles on the patch student moved to
student-move-check-infect
end
to execute-change-turtle
ask students with [user-id = hubnet-message-source]
[
set used-shape-colors remove my-code used-shape-colors
show-turtle
set-unique-shape-and-color
hubnet-send user-id "You are a:" (word (color-string color) " " base-shape)
if infected?
[ set-sick-shape ]
]
end
;;; this procedure is handy for testing out additional shapes and colors;
;;; you can call it from the Command Center
to show-gamut
clear-all
setup-vars
create-ordered-turtles max-possible-codes [
fd max-pxcor * 0.7
if who mod 3 = 0
[ fd max-pxcor * 0.3 ]
if who mod 3 = 1
[ fd max-pxcor * 0.15 ]
set heading 0
set-unique-shape-and-color
]
ask patch 0 0 [
ask patches in-radius 2 [
sprout-androids 1 [
set shape "android"
set color gray
]
]
]
user-message (word length shape-names
" shapes * "
length colors
" colors = "
max-possible-codes
" combinations")
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Quick Start Procedures ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; instructions to quickly setup the model, and clients to run this activity
to setup-quick-start
set qs-item 0
set qs-items
[
"Teacher: Follow these directions to run the HubNet activity."
"Optional: Zoom In (see Tools in the Menu Bar)"
"Optional: Change any of the settings."
"If you want to add androids press the CREATE ANDROIDS button"
"Press the GO button."
"Everyone: Open up a HubNet Client on your machine and..."
"type your user name, select this activity and press ENTER."
"Teacher: Have the students move their turtles around to..."
"acquaint themselves with the interface."
"Press the INFECT button to start the simulation."
"Everyone: Watch the plot of the number infected."
"Teacher: To run the activity again with the same group,..."
"stop the model by pressing the GO button, if it is on."
"Change any of the settings that you would like."
"Press the CURE-ALL button to keep the androids, or SETUP to clear them"
"Teacher: Restart the simulation by pressing the GO button again."
"Infect some turtles and continue."
"Teacher: To start the simulation over with a new group,..."
"stop the model by pressing the GO button, if it is on..."
"have all the students log out..."
"or press the RESET button in the Control Center"
"start these instructions from the beginning"
]
set quick-start (item qs-item qs-items)
end
;; view the next item in the quickstart monitor
to view-next
set qs-item qs-item + 1
if qs-item >= length qs-items
[ set qs-item length qs-items - 1 ]
set quick-start (item qs-item qs-items)
end
;; view the previous item in the quickstart monitor
to view-prev
set qs-item qs-item - 1
if qs-item < 0
[ set qs-item 0 ]
set quick-start (item qs-item qs-items)
end
; Copyright 1999 Uri Wilensky and Walter Stroup.
; See Info tab for full copyright and license.]]></code>
<widgets>
<view x="297" wrappingAllowedX="false" y="120" frameRate="30.0" minPycor="-10" height="424" showTickCounter="true" patchSize="20.0" fontSize="10" wrappingAllowedY="false" width="424" tickCounterLabel="ticks" maxPycor="10" updateMode="1" maxPxcor="10" minPxcor="-10"></view>
<button x="131" y="10" height="40" disableUntilTicks="false" forever="true" kind="Observer" width="78">go</button>
<slider x="31" step="1" y="245" max="100" width="195" display="infection-chance" height="50" min="0" direction="Horizontal" default="100.0" variable="infection-chance" units="%"></slider>
<button x="131" y="55" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="77" display="infect">infect-turtles</button>
<button x="9" y="300" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="113" display="create androids">make-androids</button>
<plot x="14" autoPlotX="true" yMax="6.0" autoPlotY="true" yAxis="sick" y="520" xMin="0.0" height="197" legend="false" xMax="25.0" yMin="0.0" width="244" xAxis="time" display="Number Sick">
<setup>;; create a temporary plot pen for the current run
create-temporary-plot-pen word "run " run-number
;; cycle through a few colors so it is easy to
;; differentiate the runs.
set-plot-pen-color item (run-number mod 5) [blue red green orange violet]
;; each run starts with zero infected.
set num-infected-last-plotted 0</setup>
<update><![CDATA[let n count turtles with [infected?]
;; only plot if someone has been infected since the last time we plotted.
;; this smoothes out the plot a bit.
if n > num-infected-last-plotted [
plotxy ticks - 1 n
set num-infected-last-plotted n
]]]></update>
<pen interval="1.0" mode="0" display="not-used" color="-16777216" legend="false">
<setup></setup>
<update></update>
</pen>
</plot>
<slider x="123" step="0.1" y="355" max="10" width="150" display="android-delay" height="50" min="0" direction="Horizontal" default="0.0" variable="android-delay"></slider>
<slider x="123" step="1" y="300" max="200" width="150" display="number" height="50" min="1" direction="Horizontal" default="5.0" variable="number" units="androids"></slider>
<switch x="66" y="200" height="40" on="true" variable="show-sick?" width="126" display="show-sick?"></switch>
<switch x="10" y="345" height="40" on="true" variable="wander?" width="112" display="wander?"></switch>
<monitor x="38" precision="0" y="410" height="60" fontSize="11" width="100" display="Turtles">count turtles</monitor>
<monitor x="143" precision="0" y="410" height="60" fontSize="11" width="100" display="Number Sick">count turtles with [infected?]</monitor>
<slider x="36" step="1" y="100" max="20" width="195" display="initial-number-sick" height="50" min="1" direction="Horizontal" default="1.0" variable="initial-number-sick"></slider>
<button x="53" y="10" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="77">setup</button>
<switch x="48" y="155" height="40" on="true" variable="show-sick-on-clients?" width="170" display="show-sick-on-clients?"></switch>
<button x="87" y="475" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="93" display="clear-plot">clear-all-plots
set run-number 0</button>
<button x="273" y="75" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="118" display="Reset Instructions">setup-quick-start</button>
<button x="615" y="75" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="84" display="NEXT >>>">view-next</button>
<button x="532" y="75" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="78" display="<<< PREV">view-prev</button>
<monitor x="273" precision="0" y="10" height="60" fontSize="11" width="420" display="Quick Start Instructions- More in Info Window">quick-start</monitor>
<button x="53" y="55" height="40" disableUntilTicks="false" forever="false" kind="Observer" width="77">cure-all</button>
</widgets>
<info><
This model is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
NetLogo itself is free software for non-commercial use under the terms of the GNU General Public License ([see full license information here](https://ccl.northwestern.edu/netlogo/docs/copyright.html)).
To inquire about commercial licenses for either NetLogo or specific models from the models library, please contact netlogo-commercial-admin@ccl.northwestern.edu.
This activity and associated models and materials were created as part of the projects: PARTICIPATORY SIMULATIONS: NETWORK-BASED DESIGN FOR SYSTEMS LEARNING IN CLASSROOMS and/or INTEGRATED SIMULATION AND MODELING ENVIRONMENT. The project gratefully acknowledges the support of the National Science Foundation (REPP & ROLE programs) -- grant numbers REC #9814682 and REC-0126227.
<!-- 1999 Stroup -->]]></info>
<turtleShapes>
<shape name="default" rotatable="true" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="5"></point>
<point x="40" y="250"></point>
<point x="150" y="205"></point>
<point x="260" y="250"></point>
</polygon>
</shape>
<shape name="airplane" rotatable="true" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="0"></point>
<point x="135" y="15"></point>
<point x="120" y="60"></point>
<point x="120" y="105"></point>
<point x="15" y="165"></point>
<point x="15" y="195"></point>
<point x="120" y="180"></point>
<point x="135" y="240"></point>
<point x="105" y="270"></point>
<point x="120" y="285"></point>
<point x="150" y="270"></point>
<point x="180" y="285"></point>
<point x="210" y="270"></point>
<point x="165" y="240"></point>
<point x="180" y="180"></point>
<point x="285" y="195"></point>
<point x="285" y="165"></point>
<point x="180" y="105"></point>
<point x="180" y="60"></point>
<point x="165" y="15"></point>
</polygon>
</shape>
<shape name="airplane sick" rotatable="true" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="0"></point>
<point x="135" y="15"></point>
<point x="120" y="60"></point>
<point x="120" y="105"></point>
<point x="15" y="165"></point>
<point x="15" y="195"></point>
<point x="120" y="180"></point>
<point x="135" y="240"></point>
<point x="105" y="270"></point>
<point x="120" y="285"></point>
<point x="150" y="270"></point>
<point x="180" y="285"></point>
<point x="210" y="270"></point>
<point x="165" y="240"></point>
<point x="180" y="180"></point>
<point x="285" y="195"></point>
<point x="285" y="165"></point>
<point x="180" y="105"></point>
<point x="180" y="60"></point>
<point x="165" y="15"></point>
</polygon>
<circle x="150" y="165" marked="false" color="-684578305" diameter="90" filled="true"></circle>
</shape>
<shape name="android" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="210" y="90"></point>
<point x="240" y="195"></point>
<point x="210" y="210"></point>
<point x="165" y="90"></point>
</polygon>
<circle x="110" y="3" marked="true" color="-1920102913" diameter="80" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="105" y="88"></point>
<point x="120" y="193"></point>
<point x="105" y="240"></point>
<point x="105" y="298"></point>
<point x="135" y="300"></point>
<point x="150" y="210"></point>
<point x="165" y="300"></point>
<point x="195" y="298"></point>
<point x="195" y="240"></point>
<point x="180" y="193"></point>
<point x="195" y="88"></point>
</polygon>
<rectangle endX="172" startY="81" marked="true" color="-1920102913" endY="96" startX="127" filled="true"></rectangle>
<rectangle endX="165" startY="33" marked="false" color="255" endY="60" startX="135" filled="true"></rectangle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="90" y="90"></point>
<point x="60" y="195"></point>
<point x="90" y="210"></point>
<point x="135" y="90"></point>
</polygon>
</shape>
<shape name="android sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="210" y="90"></point>
<point x="240" y="195"></point>
<point x="210" y="210"></point>
<point x="165" y="90"></point>
</polygon>
<circle x="110" y="3" marked="true" color="-1920102913" diameter="80" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="105" y="88"></point>
<point x="120" y="193"></point>
<point x="105" y="240"></point>
<point x="105" y="298"></point>
<point x="135" y="300"></point>
<point x="150" y="210"></point>
<point x="165" y="300"></point>
<point x="195" y="298"></point>
<point x="195" y="240"></point>
<point x="180" y="193"></point>
<point x="195" y="88"></point>
</polygon>
<rectangle endX="172" startY="81" marked="true" color="-1920102913" endY="96" startX="127" filled="true"></rectangle>
<rectangle endX="165" startY="33" marked="false" color="255" endY="60" startX="135" filled="true"></rectangle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="90" y="90"></point>
<point x="60" y="195"></point>
<point x="90" y="210"></point>
<point x="135" y="90"></point>
</polygon>
<circle x="150" y="120" marked="false" color="-684578305" diameter="120" filled="true"></circle>
</shape>
<shape name="box" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="285"></point>
<point x="285" y="225"></point>
<point x="285" y="75"></point>
<point x="150" y="135"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="135"></point>
<point x="15" y="75"></point>
<point x="150" y="15"></point>
<point x="285" y="75"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="15" y="75"></point>
<point x="15" y="225"></point>
<point x="150" y="285"></point>
<point x="150" y="135"></point>
</polygon>
<line endX="150" startY="285" marked="false" color="255" endY="135" startX="150"></line>
<line endX="15" startY="135" marked="false" color="255" endY="75" startX="150"></line>
<line endX="285" startY="135" marked="false" color="255" endY="75" startX="150"></line>
</shape>
<shape name="box sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="285"></point>
<point x="270" y="225"></point>
<point x="270" y="90"></point>
<point x="150" y="150"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="150"></point>
<point x="30" y="90"></point>
<point x="150" y="30"></point>
<point x="270" y="90"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="30" y="90"></point>
<point x="30" y="225"></point>
<point x="150" y="285"></point>
<point x="150" y="150"></point>
</polygon>
<line endX="150" startY="285" marked="false" color="255" endY="150" startX="150"></line>
<line endX="30" startY="150" marked="false" color="255" endY="90" startX="150"></line>
<line endX="270" startY="150" marked="false" color="255" endY="90" startX="150"></line>
<circle x="170" y="178" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="butterfly" rotatable="false" editableColorIndex="0">
<rectangle endX="207" startY="135" marked="true" color="-1920102913" endY="224" startX="92" filled="true"></rectangle>
<circle x="158" y="53" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<circle x="165" y="180" marked="true" color="-1920102913" diameter="90" filled="true"></circle>
<circle x="45" y="180" marked="true" color="-1920102913" diameter="90" filled="true"></circle>
<circle x="8" y="53" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<line endX="253" startY="189" marked="false" color="255" endY="189" startX="43"></line>
<rectangle endX="165" startY="60" marked="true" color="-1920102913" endY="285" startX="135" filled="true"></rectangle>
<circle x="165" y="15" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<circle x="105" y="15" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<line endX="135" startY="30" marked="true" color="-1920102913" endY="60" startX="120"></line>
<line endX="180" startY="60" marked="true" color="-1920102913" endY="30" startX="165"></line>
<line endX="135" startY="60" marked="false" color="255" endY="285" startX="135"></line>
<line endX="165" startY="285" marked="false" color="255" endY="60" startX="165"></line>
</shape>
<shape name="butterfly sick" rotatable="false" editableColorIndex="0">
<rectangle endX="207" startY="135" marked="true" color="-1920102913" endY="224" startX="92" filled="true"></rectangle>
<circle x="158" y="53" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<circle x="165" y="180" marked="true" color="-1920102913" diameter="90" filled="true"></circle>
<circle x="45" y="180" marked="true" color="-1920102913" diameter="90" filled="true"></circle>
<circle x="8" y="53" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<line endX="253" startY="189" marked="false" color="255" endY="189" startX="43"></line>
<rectangle endX="165" startY="60" marked="true" color="-1920102913" endY="285" startX="135" filled="true"></rectangle>
<circle x="165" y="15" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<circle x="105" y="15" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<line endX="135" startY="30" marked="true" color="-1920102913" endY="60" startX="120"></line>
<line endX="180" startY="60" marked="true" color="-1920102913" endY="30" startX="165"></line>
<line endX="135" startY="60" marked="false" color="255" endY="285" startX="135"></line>
<line endX="165" startY="285" marked="false" color="255" endY="60" startX="165"></line>
<circle x="156" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="cactus" rotatable="false" editableColorIndex="0">
<rectangle endX="175" startY="30" marked="true" color="-1920102913" endY="177" startX="135" filled="true"></rectangle>
<rectangle endX="100" startY="105" marked="true" color="-1920102913" endY="214" startX="67" filled="true"></rectangle>
<rectangle endX="251" startY="89" marked="true" color="-1920102913" endY="167" startX="217" filled="true"></rectangle>
<rectangle endX="220" startY="151" marked="true" color="-1920102913" endY="185" startX="157" filled="true"></rectangle>
<rectangle endX="148" startY="189" marked="true" color="-1920102913" endY="233" startX="94" filled="true"></rectangle>
<rectangle endX="184" startY="162" marked="true" color="-1920102913" endY="297" startX="135" filled="true"></rectangle>
<circle x="219" y="76" marked="true" color="-1920102913" diameter="28" filled="true"></circle>
<circle x="138" y="7" marked="true" color="-1920102913" diameter="34" filled="true"></circle>
<circle x="67" y="93" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<circle x="201" y="145" marked="true" color="-1920102913" diameter="40" filled="true"></circle>
<circle x="69" y="193" marked="true" color="-1920102913" diameter="40" filled="true"></circle>
</shape>
<shape name="cactus sick" rotatable="false" editableColorIndex="0">
<rectangle endX="175" startY="30" marked="true" color="-1920102913" endY="177" startX="135" filled="true"></rectangle>
<rectangle endX="100" startY="105" marked="true" color="-1920102913" endY="214" startX="67" filled="true"></rectangle>
<rectangle endX="251" startY="89" marked="true" color="-1920102913" endY="167" startX="217" filled="true"></rectangle>
<rectangle endX="220" startY="151" marked="true" color="-1920102913" endY="185" startX="157" filled="true"></rectangle>
<rectangle endX="148" startY="189" marked="true" color="-1920102913" endY="233" startX="94" filled="true"></rectangle>
<rectangle endX="184" startY="162" marked="true" color="-1920102913" endY="297" startX="135" filled="true"></rectangle>
<circle x="219" y="76" marked="true" color="-1920102913" diameter="28" filled="true"></circle>
<circle x="138" y="7" marked="true" color="-1920102913" diameter="34" filled="true"></circle>
<circle x="67" y="93" marked="true" color="-1920102913" diameter="30" filled="true"></circle>
<circle x="201" y="145" marked="true" color="-1920102913" diameter="40" filled="true"></circle>
<circle x="69" y="193" marked="true" color="-1920102913" diameter="40" filled="true"></circle>
<circle x="156" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="car" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="300" y="180"></point>
<point x="279" y="164"></point>
<point x="261" y="144"></point>
<point x="240" y="135"></point>
<point x="226" y="132"></point>
<point x="213" y="106"></point>
<point x="203" y="84"></point>
<point x="185" y="63"></point>
<point x="159" y="50"></point>
<point x="135" y="50"></point>
<point x="75" y="60"></point>
<point x="0" y="150"></point>
<point x="0" y="165"></point>
<point x="0" y="225"></point>
<point x="300" y="225"></point>
<point x="300" y="180"></point>
</polygon>
<circle x="180" y="180" marked="false" color="255" diameter="90" filled="true"></circle>
<circle x="30" y="180" marked="false" color="255" diameter="90" filled="true"></circle>
<polygon color="255" filled="true" marked="false">
<point x="162" y="80"></point>
<point x="132" y="78"></point>
<point x="134" y="135"></point>
<point x="209" y="135"></point>
<point x="194" y="105"></point>
<point x="189" y="96"></point>
<point x="180" y="89"></point>
</polygon>
<circle x="47" y="195" marked="true" color="-1920102913" diameter="58" filled="true"></circle>
<circle x="195" y="195" marked="true" color="-1920102913" diameter="58" filled="true"></circle>
</shape>
<shape name="car sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="285" y="208"></point>
<point x="285" y="178"></point>
<point x="279" y="164"></point>
<point x="261" y="144"></point>
<point x="240" y="135"></point>
<point x="226" y="132"></point>
<point x="213" y="106"></point>
<point x="199" y="84"></point>
<point x="171" y="68"></point>
<point x="149" y="68"></point>
<point x="129" y="68"></point>
<point x="75" y="75"></point>
<point x="15" y="150"></point>
<point x="15" y="165"></point>
<point x="15" y="225"></point>
<point x="285" y="225"></point>
<point x="283" y="174"></point>
<point x="283" y="176"></point>
</polygon>
<circle x="180" y="180" marked="false" color="255" diameter="90" filled="true"></circle>
<circle x="30" y="180" marked="false" color="255" diameter="90" filled="true"></circle>
<polygon color="255" filled="true" marked="false">
<point x="195" y="90"></point>
<point x="135" y="90"></point>
<point x="135" y="135"></point>
<point x="210" y="135"></point>
<point x="195" y="105"></point>
<point x="165" y="90"></point>
</polygon>
<circle x="47" y="195" marked="true" color="-1920102913" diameter="58" filled="true"></circle>
<circle x="195" y="195" marked="true" color="-1920102913" diameter="58" filled="true"></circle>
<circle x="171" y="156" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="cat" rotatable="false" editableColorIndex="0">
<line endX="210" startY="240" marked="true" color="-1920102913" endY="240" startX="285"></line>
<line endX="165" startY="300" marked="true" color="-1920102913" endY="255" startX="195"></line>
<line endX="90" startY="240" marked="true" color="-1920102913" endY="240" startX="15"></line>
<line endX="195" startY="285" marked="true" color="-1920102913" endY="240" startX="285"></line>
<line endX="135" startY="300" marked="true" color="-1920102913" endY="255" startX="105"></line>
<line endX="150" startY="270" marked="false" color="255" endY="285" startX="150"></line>
<line endX="15" startY="75" marked="false" color="255" endY="120" startX="15"></line>
<polygon color="-1920102913" filled="true" marked="true">
<point x="300" y="15"></point>
<point x="285" y="30"></point>
<point x="255" y="30"></point>
<point x="225" y="75"></point>
<point x="195" y="60"></point>
<point x="255" y="15"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="285" y="135"></point>
<point x="210" y="135"></point>
<point x="180" y="150"></point>
<point x="180" y="45"></point>
<point x="285" y="90"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="45"></point>
<point x="120" y="210"></point>
<point x="180" y="210"></point>
<point x="180" y="45"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="180" y="195"></point>
<point x="165" y="300"></point>
<point x="240" y="285"></point>
<point x="255" y="225"></point>
<point x="285" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="180" y="225"></point>
<point x="195" y="285"></point>
<point x="165" y="300"></point>
<point x="150" y="300"></point>
<point x="150" y="255"></point>
<point x="165" y="225"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="195" y="195"></point>
<point x="195" y="165"></point>
<point x="225" y="150"></point>
<point x="255" y="135"></point>
<point x="285" y="135"></point>
<point x="285" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="15" y="135"></point>
<point x="90" y="135"></point>
<point x="120" y="150"></point>
<point x="120" y="45"></point>
<point x="15" y="90"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="195"></point>
<point x="135" y="300"></point>
<point x="60" y="285"></point>
<point x="45" y="225"></point>
<point x="15" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="225"></point>
<point x="105" y="285"></point>
<point x="135" y="300"></point>
<point x="150" y="300"></point>
<point x="150" y="255"></point>
<point x="135" y="225"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="105" y="195"></point>
<point x="105" y="165"></point>
<point x="75" y="150"></point>
<point x="45" y="135"></point>
<point x="15" y="135"></point>
<point x="15" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="285" y="120"></point>
<point x="270" y="90"></point>
<point x="285" y="15"></point>
<point x="300" y="15"></point>
</polygon>
<line endX="105" startY="285" marked="true" color="-1920102913" endY="240" startX="15"></line>
<polygon color="-1920102913" filled="true" marked="true">
<point x="15" y="120"></point>
<point x="30" y="90"></point>
<point x="15" y="15"></point>
<point x="0" y="15"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="0" y="15"></point>
<point x="15" y="30"></point>
<point x="45" y="30"></point>
<point x="75" y="75"></point>
<point x="105" y="60"></point>
<point x="45" y="15"></point>
</polygon>
<line endX="209" startY="262" marked="false" color="255" endY="262" startX="164"></line>
<line endX="208" startY="231" marked="false" color="255" endY="261" startX="223"></line>
<line endX="91" startY="262" marked="false" color="255" endY="262" startX="136"></line>
<line endX="92" startY="231" marked="false" color="255" endY="261" startX="77"></line>
</shape>
<shape name="cat sick" rotatable="false" editableColorIndex="0">
<line endX="210" startY="240" marked="true" color="-1920102913" endY="240" startX="285"></line>
<line endX="165" startY="300" marked="true" color="-1920102913" endY="255" startX="195"></line>
<line endX="90" startY="240" marked="true" color="-1920102913" endY="240" startX="15"></line>
<line endX="195" startY="285" marked="true" color="-1920102913" endY="240" startX="285"></line>
<line endX="135" startY="300" marked="true" color="-1920102913" endY="255" startX="105"></line>
<line endX="150" startY="270" marked="false" color="255" endY="285" startX="150"></line>
<line endX="15" startY="75" marked="false" color="255" endY="120" startX="15"></line>
<polygon color="-1920102913" filled="true" marked="true">
<point x="300" y="15"></point>
<point x="285" y="30"></point>
<point x="255" y="30"></point>
<point x="225" y="75"></point>
<point x="195" y="60"></point>
<point x="255" y="15"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="285" y="135"></point>
<point x="210" y="135"></point>
<point x="180" y="150"></point>
<point x="180" y="45"></point>
<point x="285" y="90"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="45"></point>
<point x="120" y="210"></point>
<point x="180" y="210"></point>
<point x="180" y="45"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="180" y="195"></point>
<point x="165" y="300"></point>
<point x="240" y="285"></point>
<point x="255" y="225"></point>
<point x="285" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="180" y="225"></point>
<point x="195" y="285"></point>
<point x="165" y="300"></point>
<point x="150" y="300"></point>
<point x="150" y="255"></point>
<point x="165" y="225"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="195" y="195"></point>
<point x="195" y="165"></point>
<point x="225" y="150"></point>
<point x="255" y="135"></point>
<point x="285" y="135"></point>
<point x="285" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="15" y="135"></point>
<point x="90" y="135"></point>
<point x="120" y="150"></point>
<point x="120" y="45"></point>
<point x="15" y="90"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="195"></point>
<point x="135" y="300"></point>
<point x="60" y="285"></point>
<point x="45" y="225"></point>
<point x="15" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="120" y="225"></point>
<point x="105" y="285"></point>
<point x="135" y="300"></point>
<point x="150" y="300"></point>
<point x="150" y="255"></point>
<point x="135" y="225"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="105" y="195"></point>
<point x="105" y="165"></point>
<point x="75" y="150"></point>
<point x="45" y="135"></point>
<point x="15" y="135"></point>
<point x="15" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="285" y="120"></point>
<point x="270" y="90"></point>
<point x="285" y="15"></point>
<point x="300" y="15"></point>
</polygon>
<line endX="105" startY="285" marked="true" color="-1920102913" endY="240" startX="15"></line>
<polygon color="-1920102913" filled="true" marked="true">
<point x="15" y="120"></point>
<point x="30" y="90"></point>
<point x="15" y="15"></point>
<point x="0" y="15"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="0" y="15"></point>
<point x="15" y="30"></point>
<point x="45" y="30"></point>
<point x="75" y="75"></point>
<point x="105" y="60"></point>
<point x="45" y="15"></point>
</polygon>
<line endX="209" startY="262" marked="false" color="255" endY="262" startX="164"></line>
<line endX="208" startY="231" marked="false" color="255" endY="261" startX="223"></line>
<line endX="91" startY="262" marked="false" color="255" endY="262" startX="136"></line>
<line endX="92" startY="231" marked="false" color="255" endY="261" startX="77"></line>
<circle x="186" y="186" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="cow skull" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="90"></point>
<point x="75" y="105"></point>
<point x="60" y="150"></point>
<point x="75" y="210"></point>
<point x="105" y="285"></point>
<point x="195" y="285"></point>
<point x="225" y="210"></point>
<point x="240" y="150"></point>
<point x="225" y="105"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="150" y="150"></point>
<point x="90" y="195"></point>
<point x="90" y="150"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="150" y="150"></point>
<point x="210" y="195"></point>
<point x="210" y="150"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="105" y="285"></point>
<point x="135" y="270"></point>
<point x="150" y="285"></point>
<point x="165" y="270"></point>
<point x="195" y="285"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="240" y="150"></point>
<point x="263" y="143"></point>
<point x="278" y="126"></point>
<point x="287" y="102"></point>
<point x="287" y="79"></point>
<point x="280" y="53"></point>
<point x="273" y="38"></point>
<point x="261" y="25"></point>
<point x="246" y="15"></point>
<point x="227" y="8"></point>
<point x="241" y="26"></point>
<point x="253" y="46"></point>
<point x="258" y="68"></point>
<point x="257" y="96"></point>
<point x="246" y="116"></point>
<point x="229" y="126"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="60" y="150"></point>
<point x="37" y="143"></point>
<point x="22" y="126"></point>
<point x="13" y="102"></point>
<point x="13" y="79"></point>
<point x="20" y="53"></point>
<point x="27" y="38"></point>
<point x="39" y="25"></point>
<point x="54" y="15"></point>
<point x="73" y="8"></point>
<point x="59" y="26"></point>
<point x="47" y="46"></point>
<point x="42" y="68"></point>
<point x="43" y="96"></point>
<point x="54" y="116"></point>
<point x="71" y="126"></point>
</polygon>
</shape>
<shape name="cow skull sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="90"></point>
<point x="75" y="105"></point>
<point x="60" y="150"></point>
<point x="75" y="210"></point>
<point x="105" y="285"></point>
<point x="195" y="285"></point>
<point x="225" y="210"></point>
<point x="240" y="150"></point>
<point x="225" y="105"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="150" y="150"></point>
<point x="90" y="195"></point>
<point x="90" y="150"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="150" y="150"></point>
<point x="210" y="195"></point>
<point x="210" y="150"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="105" y="285"></point>
<point x="135" y="270"></point>
<point x="150" y="285"></point>
<point x="165" y="270"></point>
<point x="195" y="285"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="240" y="150"></point>
<point x="263" y="143"></point>
<point x="278" y="126"></point>
<point x="287" y="102"></point>
<point x="287" y="79"></point>
<point x="280" y="53"></point>
<point x="273" y="38"></point>
<point x="261" y="25"></point>
<point x="246" y="15"></point>
<point x="227" y="8"></point>
<point x="241" y="26"></point>
<point x="253" y="46"></point>
<point x="258" y="68"></point>
<point x="257" y="96"></point>
<point x="246" y="116"></point>
<point x="229" y="126"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="60" y="150"></point>
<point x="37" y="143"></point>
<point x="22" y="126"></point>
<point x="13" y="102"></point>
<point x="13" y="79"></point>
<point x="20" y="53"></point>
<point x="27" y="38"></point>
<point x="39" y="25"></point>
<point x="54" y="15"></point>
<point x="73" y="8"></point>
<point x="59" y="26"></point>
<point x="47" y="46"></point>
<point x="42" y="68"></point>
<point x="43" y="96"></point>
<point x="54" y="116"></point>
<point x="71" y="126"></point>
</polygon>
<circle x="156" y="186" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="dog" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="300" y="165"></point>
<point x="300" y="195"></point>
<point x="270" y="210"></point>
<point x="183" y="204"></point>
<point x="180" y="240"></point>
<point x="165" y="270"></point>
<point x="165" y="300"></point>
<point x="120" y="300"></point>
<point x="0" y="240"></point>
<point x="45" y="165"></point>
<point x="75" y="90"></point>
<point x="75" y="45"></point>
<point x="105" y="15"></point>
<point x="135" y="45"></point>
<point x="165" y="45"></point>
<point x="180" y="15"></point>
<point x="225" y="15"></point>
<point x="255" y="30"></point>
<point x="225" y="30"></point>
<point x="210" y="60"></point>
<point x="225" y="90"></point>
<point x="225" y="105"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="0" y="240"></point>
<point x="120" y="300"></point>
<point x="165" y="300"></point>
<point x="165" y="285"></point>
<point x="120" y="285"></point>
<point x="10" y="221"></point>
</polygon>
<line endX="180" startY="60" marked="false" color="255" endY="45" startX="210"></line>
<line endX="90" startY="45" marked="false" color="255" endY="90" startX="90"></line>
<line endX="105" startY="90" marked="false" color="255" endY="105" startX="90"></line>
<line endX="135" startY="105" marked="false" color="255" endY="60" startX="105"></line>
<line endX="135" startY="45" marked="false" color="255" endY="60" startX="90"></line>
<line endX="135" startY="60" marked="false" color="255" endY="45" startX="135"></line>
<line endX="151" startY="203" marked="false" color="255" endY="203" startX="181"></line>
<line endX="105" startY="201" marked="false" color="255" endY="171" startX="150"></line>
<circle x="171" y="88" marked="false" color="255" diameter="34" filled="true"></circle>
<circle x="261" y="162" marked="false" color="255" diameter="30" filled="false"></circle>
</shape>
<shape name="dog sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="300" y="165"></point>
<point x="300" y="195"></point>
<point x="270" y="210"></point>
<point x="183" y="204"></point>
<point x="180" y="240"></point>
<point x="165" y="270"></point>
<point x="165" y="300"></point>
<point x="120" y="300"></point>
<point x="0" y="240"></point>
<point x="45" y="165"></point>
<point x="75" y="90"></point>
<point x="75" y="45"></point>
<point x="105" y="15"></point>
<point x="135" y="45"></point>
<point x="165" y="45"></point>
<point x="180" y="15"></point>
<point x="225" y="15"></point>
<point x="255" y="30"></point>
<point x="225" y="30"></point>
<point x="210" y="60"></point>
<point x="225" y="90"></point>
<point x="225" y="105"></point>
</polygon>
<polygon color="255" filled="true" marked="false">
<point x="0" y="240"></point>
<point x="120" y="300"></point>
<point x="165" y="300"></point>
<point x="165" y="285"></point>
<point x="120" y="285"></point>
<point x="10" y="221"></point>
</polygon>
<line endX="180" startY="60" marked="false" color="255" endY="45" startX="210"></line>
<line endX="90" startY="45" marked="false" color="255" endY="90" startX="90"></line>
<line endX="105" startY="90" marked="false" color="255" endY="105" startX="90"></line>
<line endX="135" startY="105" marked="false" color="255" endY="60" startX="105"></line>
<line endX="135" startY="45" marked="false" color="255" endY="60" startX="90"></line>
<line endX="135" startY="60" marked="false" color="255" endY="45" startX="135"></line>
<line endX="151" startY="203" marked="false" color="255" endY="203" startX="181"></line>
<line endX="105" startY="201" marked="false" color="255" endY="171" startX="150"></line>
<circle x="171" y="88" marked="false" color="255" diameter="34" filled="true"></circle>
<circle x="261" y="162" marked="false" color="255" diameter="30" filled="false"></circle>
<circle x="126" y="186" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="ghost" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="30" y="165"></point>
<point x="13" y="164"></point>
<point x="-2" y="149"></point>
<point x="0" y="135"></point>
<point x="-2" y="119"></point>
<point x="0" y="105"></point>
<point x="15" y="75"></point>
<point x="30" y="75"></point>
<point x="58" y="104"></point>
<point x="43" y="119"></point>
<point x="43" y="134"></point>
<point x="58" y="134"></point>
<point x="73" y="134"></point>
<point x="88" y="104"></point>
<point x="73" y="44"></point>
<point x="78" y="14"></point>
<point x="103" y="-1"></point>
<point x="193" y="-1"></point>
<point x="223" y="29"></point>
<point x="208" y="89"></point>
<point x="208" y="119"></point>
<point x="238" y="134"></point>
<point x="253" y="119"></point>
<point x="240" y="105"></point>
<point x="238" y="89"></point>
<point x="240" y="75"></point>
<point x="255" y="60"></point>
<point x="270" y="60"></point>
<point x="283" y="74"></point>
<point x="300" y="90"></point>
<point x="298" y="104"></point>
<point x="298" y="119"></point>
<point x="300" y="135"></point>
<point x="285" y="135"></point>
<point x="285" y="150"></point>
<point x="268" y="164"></point>
<point x="238" y="179"></point>
<point x="208" y="164"></point>
<point x="208" y="194"></point>
<point x="238" y="209"></point>
<point x="253" y="224"></point>
<point x="268" y="239"></point>
<point x="268" y="269"></point>
<point x="238" y="299"></point>
<point x="178" y="299"></point>
<point x="148" y="284"></point>
<point x="103" y="269"></point>
<point x="58" y="284"></point>
<point x="43" y="299"></point>
<point x="58" y="269"></point>
<point x="103" y="254"></point>
<point x="148" y="254"></point>
<point x="193" y="254"></point>
<point x="163" y="239"></point>
<point x="118" y="209"></point>
<point x="88" y="179"></point>
<point x="73" y="179"></point>
<point x="58" y="164"></point>
</polygon>
<line endX="215" startY="253" marked="false" color="255" endY="253" startX="189"></line>
<circle x="102" y="30" marked="false" color="255" diameter="30" filled="true"></circle>
<polygon color="255" filled="true" marked="false">
<point x="165" y="105"></point>
<point x="135" y="105"></point>
<point x="120" y="120"></point>
<point x="105" y="105"></point>
<point x="135" y="75"></point>
<point x="165" y="75"></point>
<point x="195" y="105"></point>
<point x="180" y="120"></point>
</polygon>
<circle x="160" y="30" marked="false" color="255" diameter="30" filled="true"></circle>
</shape>
<shape name="ghost sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="30" y="165"></point>
<point x="13" y="164"></point>
<point x="-2" y="149"></point>
<point x="0" y="135"></point>
<point x="-2" y="119"></point>
<point x="0" y="105"></point>
<point x="15" y="75"></point>
<point x="30" y="75"></point>
<point x="58" y="104"></point>
<point x="43" y="119"></point>
<point x="43" y="134"></point>
<point x="58" y="134"></point>
<point x="73" y="134"></point>
<point x="88" y="104"></point>
<point x="73" y="44"></point>
<point x="78" y="14"></point>
<point x="103" y="-1"></point>
<point x="193" y="-1"></point>
<point x="223" y="29"></point>
<point x="208" y="89"></point>
<point x="208" y="119"></point>
<point x="238" y="134"></point>
<point x="253" y="119"></point>
<point x="240" y="105"></point>
<point x="238" y="89"></point>
<point x="240" y="75"></point>
<point x="255" y="60"></point>
<point x="270" y="60"></point>
<point x="283" y="74"></point>
<point x="300" y="90"></point>
<point x="298" y="104"></point>
<point x="298" y="119"></point>
<point x="300" y="135"></point>
<point x="285" y="135"></point>
<point x="285" y="150"></point>
<point x="268" y="164"></point>
<point x="238" y="179"></point>
<point x="208" y="164"></point>
<point x="208" y="194"></point>
<point x="238" y="209"></point>
<point x="253" y="224"></point>
<point x="268" y="239"></point>
<point x="268" y="269"></point>
<point x="238" y="299"></point>
<point x="178" y="299"></point>
<point x="148" y="284"></point>
<point x="103" y="269"></point>
<point x="58" y="284"></point>
<point x="43" y="299"></point>
<point x="58" y="269"></point>
<point x="103" y="254"></point>
<point x="148" y="254"></point>
<point x="193" y="254"></point>
<point x="163" y="239"></point>
<point x="118" y="209"></point>
<point x="88" y="179"></point>
<point x="73" y="179"></point>
<point x="58" y="164"></point>
</polygon>
<line endX="215" startY="253" marked="false" color="255" endY="253" startX="189"></line>
<circle x="102" y="30" marked="false" color="255" diameter="30" filled="true"></circle>
<polygon color="255" filled="true" marked="false">
<point x="165" y="105"></point>
<point x="135" y="105"></point>
<point x="120" y="120"></point>
<point x="105" y="105"></point>
<point x="135" y="75"></point>
<point x="165" y="75"></point>
<point x="195" y="105"></point>
<point x="180" y="120"></point>
</polygon>
<circle x="160" y="30" marked="false" color="255" diameter="30" filled="true"></circle>
<circle x="156" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="heart" rotatable="false" editableColorIndex="0">
<circle x="152" y="19" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="105"></point>
<point x="240" y="105"></point>
<point x="270" y="135"></point>
<point x="150" y="270"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="105"></point>
<point x="60" y="105"></point>
<point x="30" y="135"></point>
<point x="150" y="270"></point>
</polygon>
<line endX="150" startY="270" marked="true" color="-1920102913" endY="135" startX="150"></line>
<rectangle endX="180" startY="90" marked="true" color="-1920102913" endY="135" startX="135" filled="true"></rectangle>
<circle x="14" y="19" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
</shape>
<shape name="heart sick" rotatable="false" editableColorIndex="0">
<circle x="152" y="19" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="105"></point>
<point x="240" y="105"></point>
<point x="270" y="135"></point>
<point x="150" y="270"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="105"></point>
<point x="60" y="105"></point>
<point x="30" y="135"></point>
<point x="150" y="270"></point>
</polygon>
<line endX="150" startY="270" marked="true" color="-1920102913" endY="135" startX="150"></line>
<rectangle endX="180" startY="90" marked="true" color="-1920102913" endY="135" startX="135" filled="true"></rectangle>
<circle x="14" y="19" marked="true" color="-1920102913" diameter="134" filled="true"></circle>
<circle x="171" y="156" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="key" rotatable="false" editableColorIndex="0">
<rectangle endX="300" startY="120" marked="true" color="-1920102913" endY="150" startX="90" filled="true"></rectangle>
<rectangle endX="300" startY="135" marked="true" color="-1920102913" endY="195" startX="270" filled="true"></rectangle>
<rectangle endX="225" startY="135" marked="true" color="-1920102913" endY="195" startX="195" filled="true"></rectangle>
<circle x="0" y="60" marked="true" color="-1920102913" diameter="150" filled="true"></circle>
<circle x="30" y="90" marked="false" color="255" diameter="90" filled="true"></circle>
</shape>
<shape name="key sick" rotatable="false" editableColorIndex="0">
<rectangle endX="300" startY="120" marked="true" color="-1920102913" endY="150" startX="90" filled="true"></rectangle>
<rectangle endX="300" startY="135" marked="true" color="-1920102913" endY="195" startX="270" filled="true"></rectangle>
<rectangle endX="225" startY="135" marked="true" color="-1920102913" endY="195" startX="195" filled="true"></rectangle>
<circle x="0" y="60" marked="true" color="-1920102913" diameter="150" filled="true"></circle>
<circle x="30" y="90" marked="false" color="255" diameter="90" filled="true"></circle>
<circle x="156" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="leaf" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="210"></point>
<point x="135" y="195"></point>
<point x="120" y="210"></point>
<point x="60" y="210"></point>
<point x="30" y="195"></point>
<point x="60" y="180"></point>
<point x="60" y="165"></point>
<point x="15" y="135"></point>
<point x="30" y="120"></point>
<point x="15" y="105"></point>
<point x="40" y="104"></point>
<point x="45" y="90"></point>
<point x="60" y="90"></point>
<point x="90" y="105"></point>
<point x="105" y="120"></point>
<point x="120" y="120"></point>
<point x="105" y="60"></point>
<point x="120" y="60"></point>
<point x="135" y="30"></point>
<point x="150" y="15"></point>
<point x="165" y="30"></point>
<point x="180" y="60"></point>
<point x="195" y="60"></point>
<point x="180" y="120"></point>
<point x="195" y="120"></point>
<point x="210" y="105"></point>
<point x="240" y="90"></point>
<point x="255" y="90"></point>
<point x="263" y="104"></point>
<point x="285" y="105"></point>
<point x="270" y="120"></point>
<point x="285" y="135"></point>
<point x="240" y="165"></point>
<point x="240" y="180"></point>
<point x="270" y="195"></point>
<point x="240" y="210"></point>
<point x="180" y="210"></point>
<point x="165" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="135" y="195"></point>
<point x="135" y="240"></point>
<point x="120" y="255"></point>
<point x="105" y="255"></point>
<point x="105" y="285"></point>
<point x="135" y="285"></point>
<point x="165" y="240"></point>
<point x="165" y="195"></point>
</polygon>
</shape>
<shape name="leaf sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="150" y="210"></point>
<point x="135" y="195"></point>
<point x="120" y="210"></point>
<point x="60" y="210"></point>
<point x="30" y="195"></point>
<point x="60" y="180"></point>
<point x="60" y="165"></point>
<point x="15" y="135"></point>
<point x="30" y="120"></point>
<point x="15" y="105"></point>
<point x="40" y="104"></point>
<point x="45" y="90"></point>
<point x="60" y="90"></point>
<point x="90" y="105"></point>
<point x="105" y="120"></point>
<point x="120" y="120"></point>
<point x="105" y="60"></point>
<point x="120" y="60"></point>
<point x="135" y="30"></point>
<point x="150" y="15"></point>
<point x="165" y="30"></point>
<point x="180" y="60"></point>
<point x="195" y="60"></point>
<point x="180" y="120"></point>
<point x="195" y="120"></point>
<point x="210" y="105"></point>
<point x="240" y="90"></point>
<point x="255" y="90"></point>
<point x="263" y="104"></point>
<point x="285" y="105"></point>
<point x="270" y="120"></point>
<point x="285" y="135"></point>
<point x="240" y="165"></point>
<point x="240" y="180"></point>
<point x="270" y="195"></point>
<point x="240" y="210"></point>
<point x="180" y="210"></point>
<point x="165" y="195"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="135" y="195"></point>
<point x="135" y="240"></point>
<point x="120" y="255"></point>
<point x="105" y="255"></point>
<point x="105" y="285"></point>
<point x="135" y="285"></point>
<point x="165" y="240"></point>
<point x="165" y="195"></point>
</polygon>
<circle x="141" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="monster" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="75" y="150"></point>
<point x="90" y="195"></point>
<point x="210" y="195"></point>
<point x="225" y="150"></point>
<point x="255" y="120"></point>
<point x="255" y="45"></point>
<point x="180" y="0"></point>
<point x="120" y="0"></point>
<point x="45" y="45"></point>
<point x="45" y="120"></point>
</polygon>
<circle x="165" y="60" marked="false" color="255" diameter="60" filled="true"></circle>
<circle x="75" y="60" marked="false" color="255" diameter="60" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="225" y="150"></point>
<point x="285" y="195"></point>
<point x="285" y="285"></point>
<point x="255" y="300"></point>
<point x="255" y="210"></point>
<point x="180" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="75" y="150"></point>
<point x="15" y="195"></point>
<point x="15" y="285"></point>
<point x="45" y="300"></point>
<point x="45" y="210"></point>
<point x="120" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="210" y="210"></point>
<point x="225" y="285"></point>
<point x="195" y="285"></point>
<point x="165" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="90" y="210"></point>
<point x="75" y="285"></point>
<point x="105" y="285"></point>
<point x="135" y="165"></point>
</polygon>
<rectangle endX="165" startY="165" marked="true" color="-1920102913" endY="270" startX="135" filled="true"></rectangle>
</shape>
<shape name="monster sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="75" y="150"></point>
<point x="90" y="195"></point>
<point x="210" y="195"></point>
<point x="225" y="150"></point>
<point x="255" y="120"></point>
<point x="255" y="45"></point>
<point x="180" y="0"></point>
<point x="120" y="0"></point>
<point x="45" y="45"></point>
<point x="45" y="120"></point>
</polygon>
<circle x="165" y="60" marked="false" color="255" diameter="60" filled="true"></circle>
<circle x="75" y="60" marked="false" color="255" diameter="60" filled="true"></circle>
<polygon color="-1920102913" filled="true" marked="true">
<point x="225" y="150"></point>
<point x="285" y="195"></point>
<point x="285" y="285"></point>
<point x="255" y="300"></point>
<point x="255" y="210"></point>
<point x="180" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="75" y="150"></point>
<point x="15" y="195"></point>
<point x="15" y="285"></point>
<point x="45" y="300"></point>
<point x="45" y="210"></point>
<point x="120" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="210" y="210"></point>
<point x="225" y="285"></point>
<point x="195" y="285"></point>
<point x="165" y="165"></point>
</polygon>
<polygon color="-1920102913" filled="true" marked="true">
<point x="90" y="210"></point>
<point x="75" y="285"></point>
<point x="105" y="285"></point>
<point x="135" y="165"></point>
</polygon>
<rectangle endX="165" startY="165" marked="true" color="-1920102913" endY="270" startX="135" filled="true"></rectangle>
<circle x="141" y="141" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="moon" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="175" y="7"></point>
<point x="83" y="36"></point>
<point x="25" y="108"></point>
<point x="27" y="186"></point>
<point x="79" y="250"></point>
<point x="134" y="271"></point>
<point x="205" y="274"></point>
<point x="281" y="239"></point>
<point x="207" y="233"></point>
<point x="152" y="216"></point>
<point x="113" y="185"></point>
<point x="104" y="132"></point>
<point x="110" y="77"></point>
<point x="132" y="51"></point>
</polygon>
</shape>
<shape name="moon sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="160" y="7"></point>
<point x="68" y="36"></point>
<point x="10" y="108"></point>
<point x="12" y="186"></point>
<point x="64" y="250"></point>
<point x="119" y="271"></point>
<point x="190" y="274"></point>
<point x="266" y="239"></point>
<point x="192" y="233"></point>
<point x="137" y="216"></point>
<point x="98" y="185"></point>
<point x="89" y="132"></point>
<point x="95" y="77"></point>
<point x="117" y="51"></point>
</polygon>
<circle x="171" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="star" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="151" y="1"></point>
<point x="185" y="108"></point>
<point x="298" y="108"></point>
<point x="207" y="175"></point>
<point x="242" y="282"></point>
<point x="151" y="216"></point>
<point x="59" y="282"></point>
<point x="94" y="175"></point>
<point x="3" y="108"></point>
<point x="116" y="108"></point>
</polygon>
</shape>
<shape name="star sick" rotatable="false" editableColorIndex="0">
<polygon color="-1920102913" filled="true" marked="true">
<point x="151" y="1"></point>
<point x="185" y="108"></point>
<point x="298" y="108"></point>
<point x="207" y="175"></point>
<point x="242" y="282"></point>
<point x="151" y="216"></point>
<point x="59" y="282"></point>
<point x="94" y="175"></point>
<point x="3" y="108"></point>
<point x="116" y="108"></point>
</polygon>
<circle x="156" y="171" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
<shape name="target" rotatable="false" editableColorIndex="0">
<circle x="0" y="0" marked="true" color="-1920102913" diameter="300" filled="true"></circle>
<circle x="30" y="30" marked="false" color="255" diameter="240" filled="true"></circle>
<circle x="60" y="60" marked="true" color="-1920102913" diameter="180" filled="true"></circle>
<circle x="90" y="90" marked="false" color="255" diameter="120" filled="true"></circle>
<circle x="120" y="120" marked="true" color="-1920102913" diameter="60" filled="true"></circle>
</shape>
<shape name="target sick" rotatable="true" editableColorIndex="0">
<circle x="0" y="0" marked="true" color="-1920102913" diameter="300" filled="true"></circle>
<circle x="30" y="30" marked="false" color="255" diameter="240" filled="true"></circle>
<circle x="60" y="60" marked="true" color="-1920102913" diameter="180" filled="true"></circle>
<circle x="90" y="90" marked="false" color="255" diameter="120" filled="true"></circle>
<circle x="120" y="120" marked="true" color="-1920102913" diameter="60" filled="true"></circle>
<circle x="163" y="163" marked="false" color="-684578305" diameter="95" filled="true"></circle>
</shape>
<shape name="wheel" rotatable="false" editableColorIndex="0">
<circle x="3" y="3" marked="true" color="-1920102913" diameter="294" filled="true"></circle>
<circle x="30" y="30" marked="false" color="255" diameter="240" filled="true"></circle>
<line endX="150" startY="285" marked="true" color="-1920102913" endY="15" startX="150"></line>
<line endX="285" startY="150" marked="true" color="-1920102913" endY="150" startX="15"></line>
<circle x="120" y="120" marked="true" color="-1920102913" diameter="60" filled="true"></circle>
<line endX="79" startY="40" marked="true" color="-1920102913" endY="269" startX="216"></line>
<line endX="269" startY="84" marked="true" color="-1920102913" endY="221" startX="40"></line>
<line endX="269" startY="216" marked="true" color="-1920102913" endY="79" startX="40"></line>
<line endX="221" startY="40" marked="true" color="-1920102913" endY="269" startX="84"></line>
</shape>
<shape name="wheel sick" rotatable="false" editableColorIndex="0">
<circle x="3" y="3" marked="true" color="-1920102913" diameter="294" filled="true"></circle>
<circle x="30" y="30" marked="false" color="255" diameter="240" filled="true"></circle>
<line endX="150" startY="285" marked="true" color="-1920102913" endY="15" startX="150"></line>
<line endX="285" startY="150" marked="true" color="-1920102913" endY="150" startX="15"></line>
<circle x="120" y="120" marked="true" color="-1920102913" diameter="60" filled="true"></circle>
<line endX="79" startY="40" marked="true" color="-1920102913" endY="269" startX="216"></line>
<line endX="269" startY="84" marked="true" color="-1920102913" endY="221" startX="40"></line>
<line endX="269" startY="216" marked="true" color="-1920102913" endY="79" startX="40"></line>
<line endX="221" startY="40" marked="true" color="-1920102913" endY="269" startX="84"></line>
<circle x="156" y="156" marked="false" color="-684578305" diameter="108" filled="true"></circle>
</shape>
</turtleShapes>
<linkShapes>
<shape name="default" curviness="0.0">
<lines>
<line x="-0.2" visible="false">
<dash value="0.0"></dash>
<dash value="1.0"></dash>
</line>
<line x="0.0" visible="true">
<dash value="1.0"></dash>
<dash value="0.0"></dash>
</line>
<line x="0.2" visible="false">
<dash value="0.0"></dash>
<dash value="1.0"></dash>
</line>
</lines>
<indicator>
<shape name="link direction" rotatable="true" editableColorIndex="0">
<line endX="90" startY="150" marked="true" color="-1920102913" endY="180" startX="150"></line>
<line endX="210" startY="150" marked="true" color="-1920102913" endY="180" startX="150"></line>
</shape>
</indicator>
</shape>
</linkShapes>
<hubNetClient>
<view x="252" wrappingAllowedX="false" y="10" frameRate="30.0" minPycor="-10" height="420" showTickCounter="true" patchSize="20.0" fontSize="13" wrappingAllowedY="false" width="420" tickCounterLabel="ticks" maxPycor="10" updateMode="1" maxPxcor="10" minPxcor="-10"></view>
<button x="91" actionKey="K" y="223" height="33" disableUntilTicks="false" forever="false" kind="Observer" width="62" display="Down"></button>
<slider x="3" step="1.0" y="102" max="5.0" width="150" display="step-size" height="50" min="1.0" direction="Horizontal" default="1.0" variable="step-size"></slider>
<monitor x="3" precision="3" y="10" height="49" fontSize="11" width="150" display="You are a:"></monitor>
<button x="3" y="64" height="33" disableUntilTicks="false" forever="false" kind="Observer" width="150" display="Change Appearance"></button>
<button x="91" actionKey="I" y="157" height="33" disableUntilTicks="false" forever="false" kind="Observer" width="62" display="Up"></button>
<button x="29" actionKey="J" y="190" height="33" disableUntilTicks="false" forever="false" kind="Observer" width="62" display="Left"></button>
<button x="153" actionKey="L" y="190" height="33" disableUntilTicks="false" forever="false" kind="Observer" width="62" display="Right"></button>
<monitor x="156" precision="3" y="64" height="49" fontSize="11" width="87" display="Sick?"></monitor>
<monitor x="156" precision="3" y="10" height="49" fontSize="11" width="87" display="Located at:"></monitor>
</hubNetClient>
<previewCommands>need-to-manually-make-preview-for-this-model</previewCommands>
</model>
| 0 | 0.585282 | 1 | 0.585282 | game-dev | MEDIA | 0.389233 | game-dev | 0.672509 | 1 | 0.672509 |
PunishXIV/Artisan | 8,257 | Artisan/CraftingLogic/CraftingProcessor.cs | using Artisan.Autocraft;
using Artisan.CraftingLogic.Solvers;
using Artisan.GameInterop;
using Artisan.RawInformation;
using Artisan.RawInformation.Character;
using ECommons.DalamudServices;
using ECommons.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Artisan.CraftingLogic;
// monitors crafting state changes and provides recommendation based on assigned solver algorithm
// TODO: toasts etc should be moved outside - this should provide events instead
public static class CraftingProcessor
{
public static Solver.Recommendation NextRec => _nextRec;
public static SolverRef ActiveSolver = new("");
public delegate void SolverStartedDelegate(Lumina.Excel.Sheets.Recipe recipe, SolverRef solver, CraftState craft, StepState initialStep);
public static event SolverStartedDelegate? SolverStarted;
public delegate void SolverFailedDelegate(Lumina.Excel.Sheets.Recipe recipe, string reason);
public static event SolverFailedDelegate? SolverFailed; // craft started, but solver couldn't
public delegate void SolverFinishedDelegate(Lumina.Excel.Sheets.Recipe recipe, SolverRef solver, CraftState craft, StepState finalStep);
public static event SolverFinishedDelegate? SolverFinished;
public delegate void RecommendationReadyDelegate(Lumina.Excel.Sheets.Recipe recipe, SolverRef solver, CraftState craft, StepState step, Solver.Recommendation recommendation);
public static event RecommendationReadyDelegate? RecommendationReady;
public static List<ISolverDefinition> SolverDefinitions = new();
private static Solver? _activeSolver; // solver for current or expected crafting session
private static uint? _expectedRecipe; // non-null and equal to recipe id if we've requested start of a specific craft (with a specific solver) and are waiting for it to start
private static Solver.Recommendation _nextRec;
public static void Setup()
{
SolverDefinitions.Add(new StandardSolverDefinition());
SolverDefinitions.Add(new ProgressOnlySolverDefinition());
SolverDefinitions.Add(new ExpertSolverDefinition());
SolverDefinitions.Add(new MacroSolverDefinition());
SolverDefinitions.Add(new ScriptSolverDefinition());
SolverDefinitions.Add(new RaphaelSolverDefintion());
Crafting.CraftStarted += OnCraftStarted;
Crafting.CraftAdvanced += OnCraftAdvanced;
Crafting.CraftFinished += OnCraftFinished;
}
public static void Dispose()
{
Crafting.CraftStarted -= OnCraftStarted;
Crafting.CraftAdvanced -= OnCraftAdvanced;
Crafting.CraftFinished -= OnCraftFinished;
}
public static IEnumerable<ISolverDefinition.Desc> GetAvailableSolversForRecipe(CraftState craft, bool returnUnsupported, Type? skipSolver = null)
{
foreach (var solver in SolverDefinitions)
{
if (solver.GetType() == skipSolver)
continue;
foreach (var f in solver.Flavours(craft))
{
if (returnUnsupported || f.UnsupportedReason.Length == 0)
{
yield return f;
}
}
yield return default;
}
}
public static ISolverDefinition.Desc? FindSolver(CraftState craft, string type, int flavour)
{
var solver = type.Length > 0 ? SolverDefinitions.Find(s => s.GetType().FullName == type) : null;
if (solver == null)
return null;
foreach (var f in solver.Flavours(craft).Where(f => f.Flavour == flavour))
return f;
return null;
}
public static ISolverDefinition.Desc GetSolverForRecipe(RecipeConfig? recipeConfig, CraftState craft)
{
var s = FindSolver(craft, recipeConfig?.SolverType ?? "", recipeConfig?.SolverFlavour ?? 0);
if (s != null)
return s.Value;
var s2 = GetAvailableSolversForRecipe(craft, false);
if (s2.Count() > 0)
return s2.MaxBy(x => x.Priority);
return default;
}
private static void OnCraftStarted(Lumina.Excel.Sheets.Recipe recipe, CraftState craft, StepState initialStep, bool trial)
{
Svc.Log.Debug($"[CProc] OnCraftStarted #{recipe.RowId} '{recipe.ItemResult.Value.Name.ToDalamudString()}' (trial={trial}) (cosmic={craft.IsCosmic}) (IQ={craft.InitialQuality}) (PQ={craft.CraftProgress}/{craft.CraftQualityMax})");
if (_expectedRecipe != null && _expectedRecipe.Value != recipe.RowId)
{
Svc.Log.Error($"Unexpected recipe started: expected {_expectedRecipe}, got {recipe.RowId}");
_activeSolver = null; // something wrong has happened
ActiveSolver = new("");
}
_expectedRecipe = null;
// we don't want any solvers running with broken gear
if (RepairManager.GetMinEquippedPercent() == 0)
{
SolverFailed?.Invoke(recipe, "You have broken gear");
_activeSolver = null;
ActiveSolver = new("");
return;
}
if (_activeSolver == null)
{
// if we didn't provide an explicit solver, create one - but make sure if we have manually assigned one, it is actually supported
var autoSolver = GetSolverForRecipe(P.Config.RecipeConfigs.GetValueOrDefault(recipe.RowId), craft);
if (autoSolver.UnsupportedReason.Length > 0)
{
SolverFailed?.Invoke(recipe, autoSolver.UnsupportedReason);
return;
}
_activeSolver = autoSolver.CreateSolver(craft);
ActiveSolver = new(autoSolver.Name, _activeSolver);
}
if (_activeSolver is ICraftValidator validator)
{
Svc.Log.Information("Validation");
var validation = validator.Validate(craft);
if (!validation)
{
SolverFailed?.Invoke(recipe, "You have mismatched stats");
_activeSolver = null;
ActiveSolver = new("");
return;
}
}
SolverStarted?.Invoke(recipe, ActiveSolver, craft, initialStep);
_nextRec = _activeSolver.Solve(craft, initialStep);
if (Simulator.CannotUseAction(craft, initialStep, _nextRec.Action, out string reason))
DuoLog.Error($"Unable to use {_nextRec.Action.NameOfAction()}: {reason}");
if (_nextRec.Action != Skills.None)
RecommendationReady?.Invoke(recipe, ActiveSolver, craft, initialStep, _nextRec);
}
private static void OnCraftAdvanced(Lumina.Excel.Sheets.Recipe recipe, CraftState craft, StepState step)
{
Svc.Log.Debug($"[CProc] OnCraftAdvanced #{recipe.RowId} (solver={ActiveSolver.Name}): {step}");
if (_activeSolver == null)
return;
if (_nextRec.Action != Skills.None && _nextRec.Action != step.PrevComboAction)
Svc.Log.Warning($"Previous action was different from recommendation: recommended {_nextRec.Action}, used {step.PrevComboAction}");
_nextRec = _activeSolver.Solve(craft, step);
Svc.Log.Debug($"Next rec is: {_nextRec.Action} on {_nextRec.Comment}");
if (Simulator.CannotUseAction(craft, step, _nextRec.Action, out string reason))
DuoLog.Error($"Unable to use {_nextRec.Action.NameOfAction()}: {reason}");
if (_nextRec.Action != Skills.None)
RecommendationReady?.Invoke(recipe, ActiveSolver, craft, step, _nextRec);
}
private static void OnCraftFinished(Lumina.Excel.Sheets.Recipe recipe, CraftState craft, StepState finalStep, bool cancelled)
{
Svc.Log.Debug($"[CProc] OnCraftFinished #{recipe.RowId} (cancel={cancelled}, solver={ActiveSolver.Name}): {finalStep}");
if (_activeSolver == null)
return;
if (!cancelled && _nextRec.Action != Skills.None && _nextRec.Action != finalStep.PrevComboAction)
Svc.Log.Warning($"Previous action was different from recommendation: recommended {_nextRec.Action}, used {finalStep.PrevComboAction}");
SolverFinished?.Invoke(recipe, ActiveSolver, craft, finalStep);
_activeSolver = null;
ActiveSolver = new("");
_nextRec = new();
}
}
| 0 | 0.917155 | 1 | 0.917155 | game-dev | MEDIA | 0.255752 | game-dev | 0.867723 | 1 | 0.867723 |
google/zooshi | 2,588 | src/components/river.h | // Copyright 2015 Google Inc. 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 specific language governing permissions and
// limitations under the License.
#ifndef FPL_ZOOSHI_COMPONENTS_RIVER_H
#define FPL_ZOOSHI_COMPONENTS_RIVER_H
#include <string>
#include <vector>
#include "components_generated.h"
#include "corgi/component.h"
#include "fplbase/mesh.h"
#include "mathfu/constants.h"
#include "mathfu/glsl_mappings.h"
#include "mathfu/matrix_4x4.h"
#include "rail_denizen.h"
namespace fpl {
namespace zooshi {
// All the relevent data for rivers ends up tossed into other components.
// (Mostly rendermesh at the moment.) This will probably be less empty
// once the river gets more animated.
struct RiverData {
RiverData()
: render_mesh_needs_update_(false),
random_seed(static_cast<unsigned int>(rand())) {}
std::vector<corgi::EntityRef> banks;
std::string rail_name;
// Flag for whether this river needs its meshes updated.
bool render_mesh_needs_update_;
// River generation has random elements, so we seed the random number
// generator the same way every time we reload the river.
unsigned int random_seed;
};
class RiverComponent : public corgi::Component<RiverData> {
public:
virtual ~RiverComponent() {}
virtual void AddFromRawData(corgi::EntityRef& entity, const void* raw_data);
virtual RawDataUniquePtr ExportRawData(const corgi::EntityRef& entity) const;
virtual void Init();
virtual void UpdateAllEntities(corgi::WorldTime /*delta_time*/);
void UpdateRiverMeshes(corgi::EntityRef entity);
// Updates the meshes for the river.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// IMPORTANT: This will break if called from any thread other than
// the main render thread. Do not call from the update thread!
void UpdateRiverMeshes();
float river_offset() const { return river_offset_; }
private:
void TriggerRiverUpdate();
void CreateRiverMesh(corgi::EntityRef& entity);
float river_offset_;
};
} // zooshi
} // fpl
CORGI_REGISTER_COMPONENT(fpl::zooshi::RiverComponent, fpl::zooshi::RiverData)
#endif // FPL_ZOOSHI_COMPONENTS_RIVER_H
| 0 | 0.916994 | 1 | 0.916994 | game-dev | MEDIA | 0.716417 | game-dev,graphics-rendering | 0.650216 | 1 | 0.650216 |
clerkma/ptex-ng | 10,607 | texlive/texk/web2c/mfluadir/otfcc/lib/bk/bkgraph.c | #include "bkgraph.h"
static bk_GraphNode *_bkgraph_grow(bk_Graph *f) {
if (f->free) {
f->length++;
f->free--;
} else {
f->length = f->length + 1;
f->free = (f->length >> 1) & 0xFFFFFF;
RESIZE(f->entries, f->length + f->free);
}
return &(f->entries[f->length - 1]);
}
static uint32_t dfs_insert_cells(bk_Block *b, bk_Graph *f, uint32_t *order) {
if (!b || b->_visitstate == VISIT_GRAY) return 0;
if (b->_visitstate == VISIT_BLACK) return b->_height;
b->_visitstate = VISIT_GRAY;
uint32_t height = 0;
for (uint32_t j = 0; j < b->length; j++) {
bk_Cell *cell = &(b->cells[j]);
if (bk_cellIsPointer(cell) && cell->p) {
uint32_t thatHeight = dfs_insert_cells(cell->p, f, order);
if (thatHeight + 1 > height) height = thatHeight + 1;
}
}
bk_GraphNode *e = _bkgraph_grow(f);
e->alias = 0;
e->block = b;
*order += 1;
e->order = *order;
e->height = b->_height = height;
b->_visitstate = VISIT_BLACK;
return height;
}
static int _by_height(const void *_a, const void *_b) {
const bk_GraphNode *a = _a;
const bk_GraphNode *b = _b;
return a->height == b->height ? a->order - b->order : b->height - a->height;
}
static int _by_order(const void *_a, const void *_b) {
const bk_GraphNode *a = _a;
const bk_GraphNode *b = _b;
return a->block && b->block && a->block->_visitstate != b->block->_visitstate // Visited first
? b->block->_visitstate - a->block->_visitstate
: a->block && b->block && a->block->_depth != b->block->_depth // By depth
? a->block->_depth - b->block->_depth
: b->order - a->order; // By order
}
bk_Graph *bk_newGraphFromRootBlock(bk_Block *b) {
bk_Graph *forest;
NEW(forest);
uint32_t tsOrder = 0;
dfs_insert_cells(b, forest, &tsOrder);
qsort(forest->entries, forest->length, sizeof(bk_GraphNode), _by_height);
for (uint32_t j = 0; j < forest->length; j++) {
forest->entries[j].block->_index = j;
forest->entries[j].alias = j;
}
return forest;
}
void bk_delete_Graph(bk_Graph *f) {
if (!f || !f->entries) return;
for (uint32_t j = 0; j < f->length; j++) {
bk_Block *b = f->entries[j].block;
if (b && b->cells) FREE(b->cells);
FREE(b);
}
FREE(f->entries);
FREE(f);
}
static uint32_t gethash(bk_Block *b) {
uint32_t h = 5381;
for (uint32_t j = 0; j < b->length; j++) {
h = ((h << 5) + h) + b->cells[j].t;
h = ((h << 5) + h);
switch (b->cells[j].t) {
case b8:
case b16:
case b32:
h += b->cells[j].z;
break;
case p16:
case p32:
case sp16:
case sp32:
if (b->cells[j].p) { h += b->cells[j].p->_index; }
break;
default:
break;
}
}
return h;
}
static bool compareblock(bk_Block *a, bk_Block *b) {
if (!a && !b) return true;
if (!a || !b) return false;
if (a->length != b->length) return false;
for (uint32_t j = 0; j < a->length; j++) {
if (a->cells[j].t != b->cells[j].t) return false;
switch (a->cells[j].t) {
case b8:
case b16:
case b32:
if (a->cells[j].z != b->cells[j].z) return false;
break;
case p16:
case p32:
case sp16:
case sp32:
if (a->cells[j].p != b->cells[j].p) return false;
break;
default:
break;
}
}
return true;
}
static bool compareEntry(bk_GraphNode *a, bk_GraphNode *b) {
if (a->hash != b->hash) return false;
return compareblock(a->block, b->block);
}
static void replaceptr(bk_Graph *f, bk_Block *b) {
for (uint32_t j = 0; j < b->length; j++) {
switch (b->cells[j].t) {
case p16:
case p32:
case sp16:
case sp32:
if (b->cells[j].p) {
uint32_t index = b->cells[j].p->_index;
while (f->entries[index].alias != index) {
index = f->entries[index].alias;
}
b->cells[j].p = f->entries[index].block;
}
break;
default:
break;
}
}
}
void bk_minimizeGraph(bk_Graph *f) {
uint32_t rear = (uint32_t)(f->length - 1);
while (rear > 0) {
uint32_t front = rear;
while (f->entries[front].height == f->entries[rear].height && front > 0) {
front--;
}
front++;
for (uint32_t j = front; j <= rear; j++) {
f->entries[j].hash = gethash(f->entries[j].block);
}
for (uint32_t j = front; j <= rear; j++) {
bk_GraphNode *a = &(f->entries[j]);
if (a->alias == j) {
for (uint32_t k = j + 1; k <= rear; k++) {
bk_GraphNode *b = &(f->entries[k]);
if (b->alias == k && compareEntry(a, b)) { b->alias = j; }
}
}
}
// replace pointers with aliased
for (uint32_t j = 0; j < front; j++) {
replaceptr(f, f->entries[j].block);
}
rear = front - 1;
}
}
static size_t otfcc_bkblock_size(bk_Block *b) {
size_t size = 0;
for (uint32_t j = 0; j < b->length; j++)
switch (b->cells[j].t) {
case b8:
size += 1;
break;
case b16:
case p16:
case sp16:
size += 2;
break;
case b32:
case p32:
case sp32:
size += 4;
break;
default:
break;
}
return size;
}
static uint32_t getoffset(size_t *offsets, bk_Block *ref, bk_Block *target, uint8_t bits) {
size_t offref = offsets[ref->_index];
size_t offtgt = offsets[target->_index];
/*
if (offtgt < offref || (offtgt - offref) >> bits) {
fprintf(stderr, "[otfcc-fea] Warning : Unable to fit offset %d into %d bits.\n",
(int32_t)(offtgt - offref), bits);
}
*/
return (uint32_t)(offtgt - offref);
}
static int64_t getoffset_untangle(size_t *offsets, bk_Block *ref, bk_Block *target) {
size_t offref = offsets[ref->_index];
size_t offtgt = offsets[target->_index];
return (int64_t)(offtgt - offref);
}
static void escalate_sppointers(bk_Block *b, bk_Graph *f, uint32_t *order, uint32_t depth) {
if (!b) return;
for (uint32_t j = 0; j < b->length; j++) {
bk_Cell *cell = &(b->cells[j]);
if (bk_cellIsPointer(cell) && cell->p && cell->t >= sp16) {
escalate_sppointers(cell->p, f, order, depth);
}
}
b->_depth = depth;
*order += 1;
f->entries[b->_index].order = *order;
}
static void dfs_attract_cells(bk_Block *b, bk_Graph *f, uint32_t *order, uint32_t depth) {
if (!b) return;
if (b->_visitstate != VISIT_WHITE) {
if (b->_depth < depth) { b->_depth = depth; }
return;
}
b->_visitstate = VISIT_GRAY;
for (uint32_t j = b->length; j-- > 0;) {
bk_Cell *cell = &(b->cells[j]);
if (bk_cellIsPointer(cell) && cell->p) { dfs_attract_cells(cell->p, f, order, depth + 1); }
}
*order += 1;
f->entries[b->_index].order = *order;
escalate_sppointers(b, f, order, depth);
b->_visitstate = VISIT_BLACK;
}
static void attract_bkgraph(bk_Graph *f) {
// Clear the visit state of all blocks
for (uint32_t j = 0; j < f->length; j++) {
f->entries[j].block->_visitstate = VISIT_WHITE;
f->entries[j].order = 0;
f->entries[j].block->_index = j;
f->entries[j].block->_depth = 0;
}
uint32_t order = 0;
dfs_attract_cells(f->entries[0].block, f, &order, 0);
qsort(f->entries, f->length, sizeof(bk_GraphNode), _by_order);
for (uint32_t j = 0; j < f->length; j++) {
f->entries[j].block->_index = j;
}
}
static bool try_untabgle_block(bk_Graph *f, bk_Block *b, size_t *offsets, uint16_t passes) {
bool didCopy = false;
for (uint32_t j = 0; j < b->length; j++) {
switch (b->cells[j].t) {
case p16:
case sp16:
if (b->cells[j].p) {
int64_t offset = getoffset_untangle(offsets, b, b->cells[j].p);
if (offset < 0 || offset > 0xFFFF) {
bk_GraphNode *e = _bkgraph_grow(f);
e->order = 0;
e->alias = 0;
e->block = bk_new_Block(bkcopy, b->cells[j].p, bkover);
b->cells[j].t = sp16;
b->cells[j].p = e->block;
didCopy = true;
}
}
break;
default:
break;
}
}
return didCopy;
}
static bool try_untangle(bk_Graph *f, uint16_t passes) {
size_t *offsets;
NEW(offsets, f->length + 1);
offsets[0] = 0;
for (uint32_t j = 0; j < f->length; j++) {
if (f->entries[j].block->_visitstate == VISIT_BLACK) {
offsets[j + 1] = offsets[j] + otfcc_bkblock_size(f->entries[j].block);
} else {
offsets[j + 1] = offsets[j];
}
}
uint32_t totalBlocks = f->length;
bool didUntangle = false;
for (uint32_t j = 0; j < totalBlocks; j++) {
if (f->entries[j].block->_visitstate == VISIT_BLACK) {
bool didCopy = try_untabgle_block(f, f->entries[j].block, offsets, passes);
didUntangle = didUntangle || didCopy;
}
}
FREE(offsets);
return didUntangle;
}
static void otfcc_build_bkblock(caryll_Buffer *buf, bk_Block *b, size_t *offsets) {
for (uint32_t j = 0; j < b->length; j++) {
switch (b->cells[j].t) {
case b8:
bufwrite8(buf, b->cells[j].z);
break;
case b16:
bufwrite16b(buf, b->cells[j].z);
break;
case b32:
bufwrite32b(buf, b->cells[j].z);
break;
case p16:
case sp16:
if (b->cells[j].p) {
bufwrite16b(buf, getoffset(offsets, b, b->cells[j].p, 16));
} else {
bufwrite16b(buf, 0);
}
break;
case p32:
case sp32:
if (b->cells[j].p) {
bufwrite32b(buf, getoffset(offsets, b, b->cells[j].p, 32));
} else {
bufwrite32b(buf, 0);
}
break;
default:
break;
}
}
}
caryll_Buffer *bk_build_Graph(bk_Graph *f) {
caryll_Buffer *buf = bufnew();
size_t *offsets;
NEW(offsets, f->length + 1);
offsets[0] = 0;
for (uint32_t j = 0; j < f->length; j++) {
if (f->entries[j].block->_visitstate == VISIT_BLACK) {
offsets[j + 1] = offsets[j] + otfcc_bkblock_size(f->entries[j].block);
} else {
offsets[j + 1] = offsets[j];
}
}
for (uint32_t j = 0; j < f->length; j++) {
if (f->entries[j].block->_visitstate == VISIT_BLACK) {
otfcc_build_bkblock(buf, f->entries[j].block, offsets);
}
}
FREE(offsets);
return buf;
}
size_t bk_estimateSizeOfGraph(bk_Graph *f) {
size_t *offsets;
NEW(offsets, f->length + 1);
offsets[0] = 0;
for (uint32_t j = 0; j < f->length; j++) {
if (f->entries[j].block->_visitstate == VISIT_BLACK) {
offsets[j + 1] = offsets[j] + otfcc_bkblock_size(f->entries[j].block);
} else {
offsets[j + 1] = offsets[j];
}
}
size_t estimatedSize = offsets[f->length];
FREE(offsets);
return estimatedSize;
}
void bk_untangleGraph(/*BORROW*/ bk_Graph *f) {
uint16_t passes = 0;
bool tangled = false;
attract_bkgraph(f);
do {
tangled = try_untangle(f, passes);
if (tangled) { attract_bkgraph(f); }
passes++;
} while (tangled && passes < 16);
}
caryll_Buffer *bk_build_Block(/*MOVE*/ bk_Block *root) {
bk_Graph *f = bk_newGraphFromRootBlock(root);
bk_minimizeGraph(f);
bk_untangleGraph(f);
caryll_Buffer *buf = bk_build_Graph(f);
bk_delete_Graph(f);
return buf;
}
caryll_Buffer *bk_build_Block_noMinimize(/*MOVE*/ bk_Block *root) {
bk_Graph *f = bk_newGraphFromRootBlock(root);
bk_untangleGraph(f);
caryll_Buffer *buf = bk_build_Graph(f);
bk_delete_Graph(f);
return buf;
}
| 0 | 0.956489 | 1 | 0.956489 | game-dev | MEDIA | 0.231029 | game-dev | 0.993293 | 1 | 0.993293 |
DaRealTurtyWurty/1.21-Tutorial-Mod | 1,592 | src/main/java/dev/turtywurty/tutorialmod/block/ExampleBEBlock.java | package dev.turtywurty.tutorialmod.block;
import dev.turtywurty.tutorialmod.block.entity.ExampleBlockEntity;
import dev.turtywurty.tutorialmod.init.BlockEntityTypeInit;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEntityProvider;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
public class ExampleBEBlock extends Block implements BlockEntityProvider {
public ExampleBEBlock(Settings settings) {
super(settings);
}
@Override
protected ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) {
if(!world.isClient) {
BlockEntity blockEntity = world.getBlockEntity(pos);
if(blockEntity instanceof ExampleBlockEntity exampleBlockEntity && player != null) {
if(!player.isSneaking()) {
exampleBlockEntity.incrementCounter();
}
player.sendMessage(Text.of(exampleBlockEntity.getCounter() + ""), true);
}
}
return ActionResult.success(world.isClient);
}
@Nullable
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return BlockEntityTypeInit.EXAMPLE_BLOCK_ENTITY.instantiate(pos, state);
}
}
| 0 | 0.655617 | 1 | 0.655617 | game-dev | MEDIA | 0.997141 | game-dev | 0.834989 | 1 | 0.834989 |
moonsharp-devs/moonsharp | 2,884 | src/MoonSharp.Interpreter/_Projects/MoonSharp.Interpreter.netcore/src/DataStructs/MultiDictionary.cs | using System.Collections.Generic;
namespace MoonSharp.Interpreter.DataStructs
{
/// <summary>
/// A Dictionary where multiple values can be associated to the same key
/// </summary>
/// <typeparam name="K">The key type</typeparam>
/// <typeparam name="V">The value type</typeparam>
internal class MultiDictionary<K, V>
{
Dictionary<K, List<V>> m_Map;
V[] m_DefaultRet = new V[0];
/// <summary>
/// Initializes a new instance of the <see cref="MultiDictionary{K, V}"/> class.
/// </summary>
public MultiDictionary()
{
m_Map = new Dictionary<K, List<V>>();
}
/// <summary>
/// Initializes a new instance of the <see cref="MultiDictionary{K, V}"/> class.
/// </summary>
/// <param name="eqComparer">The equality comparer to use in the underlying dictionary.</param>
public MultiDictionary(IEqualityComparer<K> eqComparer)
{
m_Map = new Dictionary<K, List<V>>(eqComparer);
}
/// <summary>
/// Adds the specified key. Returns true if this is the first value for a given key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool Add(K key, V value)
{
List<V> list;
if (m_Map.TryGetValue(key, out list))
{
list.Add(value);
return false;
}
else
{
list = new List<V>();
list.Add(value);
m_Map.Add(key, list);
return true;
}
}
/// <summary>
/// Finds all the values associated with the specified key.
/// An empty collection is returned if not found.
/// </summary>
/// <param name="key">The key.</param>
public IEnumerable<V> Find(K key)
{
List<V> list;
if (m_Map.TryGetValue(key, out list))
return list;
else
return m_DefaultRet;
}
/// <summary>
/// Determines whether this contains the specified key
/// </summary>
/// <param name="key">The key.</param>
public bool ContainsKey(K key)
{
return m_Map.ContainsKey(key);
}
/// <summary>
/// Gets the keys.
/// </summary>
public IEnumerable<K> Keys
{
get { return m_Map.Keys; }
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
m_Map.Clear();
}
/// <summary>
/// Removes the specified key and all its associated values from the multidictionary
/// </summary>
/// <param name="key">The key.</param>
public void Remove(K key)
{
m_Map.Remove(key);
}
/// <summary>
/// Removes the value. Returns true if the removed value was the last of a given key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool RemoveValue(K key, V value)
{
List<V> list;
if (m_Map.TryGetValue(key, out list))
{
list.Remove(value);
if (list.Count == 0)
{
Remove(key);
return true;
}
}
return false;
}
}
}
| 0 | 0.918289 | 1 | 0.918289 | game-dev | MEDIA | 0.297778 | game-dev | 0.868589 | 1 | 0.868589 |
GeneralTradingSarl/mql4_experts | 7,841 | Good EA but needs FridayClose to perform better - expert for MetaTrader 4/Expert.mq4 | //+------------------------------------------------------------------+
//| Udy Ivan Madumere.mq4 |
//| Copyright 2010, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
int TakeProfit_L = 39; // Take Profit in points
int StopLoss_L = 147; // Stop Loss in points
int TakeProfit_S = 200; // Take Profit in points
int StopLoss_S = 267; // Stop Loss in points
int TradeTime=18; // Time to enter the market
int t1=6;
int t2=2;
int delta_L=6;
int delta_S=21;
int TrailingStop = 30;
extern double lot = 0.01; // Lot size
int Orders=1; // maximal number of positions opened at a time }
int MaxOpenTime=504;
int BigLotSize = 1; // By how much lot size is multiplicated in Big lot
bool AutoLot=true;
int ticket,total,cnt;
bool cantrade=true;
double closeprice;
double tmp;
int LotSize()
// The function opens a short position with lot size=volume
{
if (AccountBalance()>=50) lot=0.02;
if (AccountBalance()>=100) lot=0.04;
if (AccountBalance()>=200) lot=0.08;
if (AccountBalance()>=300) lot=0.12;
if (AccountBalance()>=400) lot=0.16;
if (AccountBalance()>=500) lot=0.2;
if (AccountBalance()>=600) lot=0.24;
if (AccountBalance()>=700) lot=0.28;
if (AccountBalance()>=800) lot=0.32;
if (AccountBalance()>=900) lot=0.36;
if (AccountBalance()>=1000) lot=0.4;
if (AccountBalance()>=1500) lot=0.6;
if (AccountBalance()>=2000) lot=0.8;
if (AccountBalance()>=2500) lot=1.0;
if (AccountBalance()>=3000) lot=1.2;
if (AccountBalance()>=3500) lot=1.4;
if (AccountBalance()>=4000) lot=1.6;
if (AccountBalance()>=4500) lot=1.8;
if (AccountBalance()>=5000) lot=2.0;
if (AccountBalance()>=5500) lot=2.2;
if (AccountBalance()>=6000) lot=2.4;
if (AccountBalance()>=7000) lot=2.8;
if (AccountBalance()>=8000) lot=3.2;
if (AccountBalance()>=9000) lot=3.6;
if (AccountBalance()>=10000) lot=4.0;
if (AccountBalance()>=15000) lot=6.0;
if (AccountBalance()>=20000) lot=8.0;
if (AccountBalance()>=30000) lot=12;
if (AccountBalance()>=40000) lot=16;
if (AccountBalance()>=50000) lot=20;
if (AccountBalance()>=60000) lot=24;
if (AccountBalance()>=70000) lot=28;
if (AccountBalance()>=80000) lot=32;
if (AccountBalance()>=90000) lot=36;
if (AccountBalance()>=100000) lot=40;
if (AccountBalance()>=200000) lot=80;
}
int globPos()
// the function calculates big lot size
{
int v1=GlobalVariableGet("globalPosic");
GlobalVariableSet("globalPosic",v1+1);
return(0);
}
int OpenLong(double volume=0.1)
// the function opens a long position with lot size=volume
{
int slippage=10;
string comment="20/200 expert v2 (Long)";
color arrow_color=Red;
int magic=0;
if (GlobalVariableGet("globalBalans")>AccountBalance()) volume=lot*BigLotSize;
// if (GlobalVariableGet("globalBalans")>AccountBalance()) if (AutoLot) LotSize();
ticket=OrderSend(Symbol(),OP_BUY,volume,Ask,slippage,Ask-StopLoss_L*Point,
Ask+TakeProfit_L*Point,comment,magic,0,arrow_color);
GlobalVariableSet("globalBalans",AccountBalance());
globPos();
// if (GlobalVariableGet("globalPosic")>25)
// {
GlobalVariableSet("globalPosic",0);
if (AutoLot) LotSize();
// }
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
return(0);
}
else
{
Print("OpenLong(),OrderSelect() - returned an error : ",GetLastError());
return(-1);
}
}
else
{
Print("Error opening Buy order : ",GetLastError());
return(-1);
}
}
int OpenShort(double volume=0.1)
// The function opens a short position with lot size=volume
{
int slippage=10;
string comment="20/200 expert v2 (Short)";
color arrow_color=Red;
int magic=0;
if (GlobalVariableGet("globalBalans")>AccountBalance()) volume=lot*BigLotSize;
ticket=OrderSend(Symbol(),OP_SELL,volume,Bid,slippage,Bid+StopLoss_S*Point,
Bid-TakeProfit_S*Point,comment,magic,0,arrow_color);
GlobalVariableSet("globalBalans",AccountBalance());
globPos();
// if (GlobalVariableGet("globalPosic")>25)
// {
GlobalVariableSet("globalPosic",0);
if (AutoLot) LotSize();
// }
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
return(0);
}
else
{
Print("OpenShort(),OrderSelect() - returned an error : ",GetLastError());
return(-1);
}
}
else
{
Print("Error opening Sell order : ",GetLastError());
return(-1);
}
}
int init()
{
// control of a variable before using
if (AutoLot) LotSize();
if(!GlobalVariableCheck("globalBalans"))
GlobalVariableSet("globalBalans",AccountBalance());
if(!GlobalVariableCheck("globalPosic"))
GlobalVariableSet("globalPosic",0);
return(0);
}
int deinit()
{
return(0);
}
int start()
{
if((TimeHour(TimeCurrent())>TradeTime)) cantrade=true;
// check if there are open orders ...
total=OrdersTotal();
if(total<Orders)
{
// ... if no open orders, go further
// check if it's time for trade
if((TimeHour(TimeCurrent())==TradeTime)&&(cantrade))
{
// ... if it is
if (((Open[t1]-Open[t2])>delta_S*Point)) //if it is
{
//condition is fulfilled, enter a short position:
// check if there is free money for opening a short position
if(AccountFreeMarginCheck(Symbol(),OP_SELL,lot)<=0 || GetLastError()==134)
{
Print("Not enough money");
return(0);
}
OpenShort(lot);
cantrade=false; //prohibit repeated trade until the next bar
return(0);
}
if (((Open[t2]-Open[t1])>delta_L*Point)) //if the price increased by delta
{
// condition is fulfilled, enter a long position
// check if there is free money
if(AccountFreeMarginCheck(Symbol(),OP_BUY,lot)<=0 || GetLastError()==134)
{
Print("Not enough money");
return(0);
}
OpenLong(lot);
cantrade=false;
return(0);
}
}
}
//Manage open orders
//move TrailingStop if profit>TS
if(OrderType()==OP_SELL)
{
if(OrderOpenPrice()-Ask>TrailingStop*Point && OrderStopLoss()>Ask+TrailingStop*Point)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TrailingStop*Point,0,0, Red);
}
}
// block of a trade validity time checking, if MaxOpenTime=0, do not check.
if(MaxOpenTime>0)
{
for(cnt=0;cnt<total;cnt++)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
tmp = (TimeCurrent()-OrderOpenTime())/3600.0;
if (((NormalizeDouble(tmp,8)-MaxOpenTime)>=0))
{
RefreshRates();
if (OrderType()==OP_BUY)
closeprice=Bid;
else
closeprice=Ask;
if (OrderClose(OrderTicket(),OrderLots(),closeprice,10,Green))
{
Print("Forced closing of the trade - ",OrderTicket());
OrderPrint();
}
else
Print("OrderClose() in block of a trade validity time checking returned an error - ",GetLastError());
}
}
else
Print("OrderSelect() in block of a trade validity time checking returned an error - ",GetLastError());
}
}
return(0);
} | 0 | 0.574422 | 1 | 0.574422 | game-dev | MEDIA | 0.308649 | game-dev | 0.818397 | 1 | 0.818397 |
JamesTKhan/Mundus | 3,413 | editor/src/main/com/mbrlabs/mundus/editor/core/io/JsonIOManager.java | package com.mbrlabs.mundus.editor.core.io;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import com.esotericsoftware.kryo.io.Input;
import com.mbrlabs.mundus.editor.core.kryo.DescriptorConverter;
import com.mbrlabs.mundus.editor.core.kryo.descriptors.ProjectDescriptor;
import com.mbrlabs.mundus.editor.core.project.ProjectContext;
import com.mbrlabs.mundus.editor.core.project.ProjectManager;
import com.mbrlabs.mundus.editor.core.registry.ProjectRef;
import com.mbrlabs.mundus.editor.core.registry.Registry;
import com.mbrlabs.mundus.editor.utils.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Writer;
/**
* Manages loading and saving of registry and project data in JSON Format.
*
* @author JamesTKhan
* @version August 03, 2023
*/
public class JsonIOManager implements IOManager {
private final Json json;
public JsonIOManager() {
json = new Json(JsonWriter.OutputType.json);
}
@Override
public Registry loadRegistry() {
FileHandle fileHandle = getHomeDataFile();
if (!fileHandle.exists()) {
Log.info(getClass().getSimpleName(), "No registry file found. Creating new one.");
return new Registry();
}
try {
return json.fromJson(Registry.class, fileHandle);
} catch (GdxRuntimeException e) {
Log.warn(getClass().getSimpleName(), "Could not load registry file. Creating new one.");
return new Registry();
}
}
@Override
public void saveRegistry(Registry registry) {
FileHandle fileHandle = getHomeDataFile();
Writer writer = fileHandle.writer(false);
json.setWriter(writer);
String jsonString = json.prettyPrint(registry);
fileHandle.writeString(jsonString, false);
}
@Override
public void saveProjectContext(ProjectContext context) {
FileHandle fileHandle = new FileHandle(context.path + "/" +
context.name + "." + ProjectManager.PROJECT_EXTENSION);
Writer writer = fileHandle.writer(false);
json.setWriter(writer);
ProjectDescriptor descriptor = DescriptorConverter.convert(context);
String jsonString = json.prettyPrint(descriptor);
fileHandle.writeString(jsonString, false);
}
@Override
public ProjectContext loadProjectContext(ProjectRef ref) throws FileNotFoundException {
// find .pro file
FileHandle projectFile = null;
for (FileHandle f : Gdx.files.absolute(ref.getPath()).list()) {
if (f.extension().equals(ProjectManager.PROJECT_EXTENSION)) {
projectFile = f;
break;
}
}
if (projectFile != null) {
Input input = new Input(new FileInputStream(projectFile.path()));
ProjectDescriptor projectDescriptor = json.fromJson(ProjectDescriptor.class, input);
ProjectContext context = DescriptorConverter.convert(projectDescriptor);
context.activeSceneName = projectDescriptor.getCurrentSceneName();
return context;
}
return null;
}
private FileHandle getHomeDataFile() {
return new FileHandle(Registry.HOME_DATA_FILE);
}
}
| 0 | 0.980392 | 1 | 0.980392 | game-dev | MEDIA | 0.30961 | game-dev | 0.9412 | 1 | 0.9412 |
Artemis-RGB/Artemis | 1,437 | src/Artemis.Core/VisualScripting/Internal/EventConditionValueChangedStartNode.cs | using System;
namespace Artemis.Core.Internal;
internal class EventConditionValueChangedStartNode : DefaultNode
{
internal static readonly Guid NodeId = new("F9A270DB-A231-4800-BAB3-DC1F96856756");
private object? _newValue;
private object? _oldValue;
public EventConditionValueChangedStartNode() : base(NodeId, "Changed values", "Contains the old and new values of the property chat was changed.")
{
NewValue = CreateOutputPin(typeof(object), "New value");
OldValue = CreateOutputPin(typeof(object), "Old value");
}
public OutputPin NewValue { get; }
public OutputPin OldValue { get; }
public void UpdateOutputPins(DataModelPath dataModelPath)
{
Type? type = dataModelPath.GetPropertyType();
if (type == null)
type = typeof(object);
else if (Numeric.IsTypeCompatible(type))
type = typeof(Numeric);
if (NewValue.Type != type)
NewValue.ChangeType(type);
if (OldValue.Type != type)
OldValue.ChangeType(type);
}
public void UpdateValues(object? newValue, object? oldValue)
{
_newValue = NewValue.IsNumeric ? new Numeric(newValue) : newValue;
_oldValue = OldValue.IsNumeric ? new Numeric(oldValue) : oldValue;
}
/// <inheritdoc />
public override void Evaluate()
{
NewValue.Value = _newValue;
OldValue.Value = _oldValue;
}
} | 0 | 0.631187 | 1 | 0.631187 | game-dev | MEDIA | 0.856245 | game-dev | 0.865717 | 1 | 0.865717 |
copycats-plus/copycats | 8,299 | common/src/main/java/com/copycatsplus/copycats/content/copycat/flat_pane/CopycatFlatPaneBlock.java | package com.copycatsplus.copycats.content.copycat.flat_pane;
import com.copycatsplus.copycats.CCBlocks;
import com.copycatsplus.copycats.CCShapes;
import com.copycatsplus.copycats.foundation.copycat.CCWaterloggedCopycatBlock;
import com.copycatsplus.copycats.foundation.copycat.ICopycatBlock;
import com.copycatsplus.copycats.foundation.copycat.ICustomCTBlocking;
import com.copycatsplus.copycats.foundation.copycat.IStateType;
import com.copycatsplus.copycats.utility.InteractionUtils;
import com.simibubi.create.content.contraptions.StructureTransform;
import net.createmod.catnip.placement.IPlacementHelper;
import net.createmod.catnip.placement.PlacementHelpers;
import net.createmod.catnip.placement.PlacementOffset;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
import net.minecraft.core.Vec3i;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.IronBarsBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.pathfinder.PathComputationType;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
@SuppressWarnings("deprecation")
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class CopycatFlatPaneBlock extends CCWaterloggedCopycatBlock implements IStateType, ICustomCTBlocking {
public static final EnumProperty<Axis> AXIS = BlockStateProperties.AXIS;
private static final int placementHelperId = PlacementHelpers.register(new PlacementHelper());
public CopycatFlatPaneBlock(Properties pProperties) {
super(pProperties);
registerDefaultState(defaultBlockState().setValue(AXIS, Axis.Y));
}
@Override
public ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) {
return InteractionUtils.sequentialItem(
() -> InteractionUtils.usePlacementHelper(placementHelperId, stack, state, level, pos, player, hand, hitResult),
() -> super.useItemOn(stack, state, level, pos, player, hand, hitResult)
);
}
@Override
public boolean isPathfindable(@NotNull BlockState pState, @NotNull PathComputationType pType) {
return switch (pType) {
case LAND -> pState.getValue(AXIS).isHorizontal();
default -> false;
};
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
BlockState stateForPlacement = super.getStateForPlacement(context);
if (stateForPlacement == null) return null;
Axis axis = context.getNearestLookingDirection().getAxis();
return stateForPlacement.setValue(AXIS, axis);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {
super.createBlockStateDefinition(pBuilder.add(AXIS));
}
@SuppressWarnings("deprecation")
@Override
public @NotNull VoxelShape getShape(BlockState pState, @NotNull BlockGetter pLevel, @NotNull BlockPos pPos, @NotNull CollisionContext pContext) {
return CCShapes.HORIZONTAL_PANE.get(pState.getValue(AXIS)).toShape();
}
@Override
public BlockState transform(BlockState state, StructureTransform transform) {
if (transform.rotationAxis != null) {
state = state.setValue(AXIS, transform.rotateAxis(state.getValue(AXIS)));
}
return state;
}
@Override
public boolean isIgnoredConnectivitySide(BlockAndTintGetter reader, BlockState fromState, Direction face, BlockPos fromPos, @Nullable BlockPos toPos, @Nullable BlockState toState) {
if (toPos == null)
return true;
toState = reader.getBlockState(toPos);
Vec3i diff = toPos.subtract(fromPos);
if (diff.equals(Vec3i.ZERO))
return false;
Direction facing = Direction.fromDelta(diff.getX(), diff.getY(), diff.getZ());
if (toState.getBlock() instanceof IronBarsBlock) {
if (facing == null)
return true;
return face.getAxis().isVertical() || fromState.getValue(AXIS) == facing.getAxis();
} else if (toState.is(this)) {
if (facing == null)
return true;
return toState.getValue(AXIS) != fromState.getValue(AXIS) || fromState.getValue(AXIS) == facing.getAxis();
}
return true;
}
@Override
public boolean canConnectTexturesToward(BlockAndTintGetter reader, BlockPos fromPos, BlockPos toPos, BlockState fromState) {
BlockState toState = reader.getBlockState(toPos);
Vec3i diff = toPos.subtract(fromPos);
if (diff.equals(Vec3i.ZERO))
return true;
Direction facing = Direction.fromDelta(diff.getX(), diff.getY(), diff.getZ());
if (toState.getBlock() instanceof IronBarsBlock) {
if (facing == null)
return false;
return fromState.getValue(AXIS) != facing.getAxis();
} else if (toState.is(this)) {
if (facing == null)
return false;
return toState.getValue(AXIS) == fromState.getValue(AXIS) && fromState.getValue(AXIS) != facing.getAxis();
}
return false;
}
@Override
public Optional<Boolean> blockCTTowards(BlockAndTintGetter reader, BlockState state, BlockPos pos, BlockPos ctPos, BlockPos connectingPos, Direction face) {
return Optional.of(false);
}
@Override
public Optional<Boolean> isCTBlocked(BlockAndTintGetter reader, BlockState state, BlockPos pos, BlockPos connectingPos, BlockPos blockingPos, Direction face) {
return Optional.of(false);
}
public boolean supportsExternalFaceHiding(BlockState state) {
return true;
}
public boolean hidesNeighborFace(BlockGetter level,
BlockPos pos,
BlockState state,
BlockState neighborState,
Direction dir) {
return ICopycatBlock.hidesNeighborFace(level, pos, state, neighborState, dir);
}
@MethodsReturnNonnullByDefault
private static class PlacementHelper implements IPlacementHelper {
@Override
public Predicate<ItemStack> getItemPredicate() {
return CCBlocks.COPYCAT_FLAT_PANE::isIn;
}
@Override
public Predicate<BlockState> getStatePredicate() {
return CCBlocks.COPYCAT_FLAT_PANE::has;
}
@Override
public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos,
BlockHitResult ray) {
List<Direction> directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(),
state.getValue(AXIS),
dir -> world.getBlockState(pos.relative(dir)).canBeReplaced());
if (directions.isEmpty())
return PlacementOffset.fail();
else {
return PlacementOffset.success(pos.relative(directions.get(0)), s -> s.setValue(AXIS, state.getValue(AXIS)));
}
}
}
}
| 0 | 0.915158 | 1 | 0.915158 | game-dev | MEDIA | 0.98974 | game-dev | 0.951343 | 1 | 0.951343 |
davidly/dos_compilers | 6,367 | RHA (Minisystems) ALGOL v55/TTT.ALG | BEGIN
COMMENT scoreWin 6 ;
COMMENT scoreTie 5 ;
COMMENT scoreLose 4 ;
COMMENT scoreMax 9 ;
COMMENT scoreMin 2 ;
COMMENT scoreInvalid 0 ;
COMMENT pieceX 1 ;
COMMENT pieceY 2 ;
COMMENT pieceBlank 0 ;
INTEGER movecount;
INTEGER ARRAY board[0:8];
INTEGER PROCEDURE winner;
BEGIN
INTEGER t, p;
p := 0;
t := board[ 0 ];
IF 0 # t THEN BEGIN
IF ( ( ( t = board[1] ) AND ( t = board[2] ) ) OR
( ( t = board[3] ) AND ( t = board[6] ) ) ) THEN
p := t;
END;
IF 0 = p THEN BEGIN
t := board[1];
IF ( 0 # t ) AND ( t = board[4] ) AND ( t = board[7] ) THEN
p := t
ELSE BEGIN
t := board[2];
IF ( 0 # t ) AND ( t = board[5] ) AND ( t = board[8] ) THEN
p := t
ELSE BEGIN
t := board[3];
IF ( 0 # t ) AND ( t = board[4] ) AND ( t = board[5] ) THEN
p := t
ELSE BEGIN
t := board[6];
IF ( 0 # t ) AND ( t = board[7] ) AND ( t = board[8] ) THEN
p := t
ELSE BEGIN
t := board[4];
IF ( 0 # t ) THEN BEGIN
IF ( ( ( t = board[0] ) AND ( t = board[8] ) ) OR
( ( t = board[2] ) AND ( t = board[6] ) ) ) THEN
p := t;
END;
END;
END;
END;
END;
END;
winner := p;
END winner;
INTEGER PROCEDURE winner2( move );
VALUE move;
INTEGER move;
BEGIN
INTEGER x;
x := board[ move ];
CASE move OF
0: BEGIN
IF NOT ( ( ( x = board[1] ) AND ( x = board[2] ) ) OR
( ( x = board[3] ) AND ( x = board[6] ) ) OR
( ( x = board[4] ) AND ( x = board[8] ) ) )
THEN x := 0;
END;
1: BEGIN
IF NOT ( ( ( x = board[0] ) AND ( x = board[2] ) ) OR
( ( x = board[4] ) AND ( x = board[7] ) ) )
THEN x := 0;
END;
2: BEGIN
x := board[ 2 ];
IF NOT ( ( ( x = board[0] ) AND ( x = board[1] ) ) OR
( ( x = board[5] ) AND ( x = board[8] ) ) OR
( ( x = board[4] ) AND ( x = board[6] ) ) )
THEN x := 0;
END;
3: BEGIN
x := board[ 3 ];
IF NOT ( ( ( x = board[4] ) AND ( x = board[5] ) ) OR
( ( x = board[0] ) AND ( x = board[6] ) ) )
THEN x := 0;
END;
4: BEGIN
x := board[ 4 ];
IF NOT ( ( ( x = board[0] ) AND ( x = board[8] ) ) OR
( ( x = board[2] ) AND ( x = board[6] ) ) OR
( ( x = board[1] ) AND ( x = board[7] ) ) OR
( ( x = board[3] ) AND ( x = board[5] ) ) )
THEN x := 0;
END;
5: BEGIN
x := board[ 5 ];
IF NOT ( ( ( x = board[3] ) AND ( x = board[4] ) ) OR
( ( x = board[2] ) AND ( x = board[8] ) ) )
THEN x := 0;
END;
6: BEGIN
x := board[ 6 ];
IF NOT ( ( ( x = board[7] ) AND ( x = board[8] ) ) OR
( ( x = board[0] ) AND ( x = board[3] ) ) OR
( ( x = board[4] ) AND ( x = board[2] ) ) )
THEN x := 0;
END;
7: BEGIN
x := board[ 7 ];
IF NOT ( ( ( x = board[6] ) AND ( x = board[8] ) ) OR
( ( x = board[1] ) AND ( x = board[4] ) ) )
THEN x := 0;
END;
8: BEGIN
x := board[ 8 ];
IF NOT ( ( ( x = board[6] ) AND ( x = board[7] ) ) OR
( ( x = board[2] ) AND ( x = board[5] ) ) OR
( ( x = board[0] ) AND ( x = board[4] ) ) )
THEN x := 0;
END
ELSE text( 1, "unexpected move" );
winner2 := x;
END winner2;
INTEGER PROCEDURE minmax( alpha, beta, depth, move );
VALUE alpha, beta, depth, move;
INTEGER alpha, beta, depth, move;
BEGIN
INTEGER value, p, score, pm;
value := 0;
movecount := movecount + 1;
IF depth >= 4 THEN BEGIN
p := winner2( move );
IF p # 0 THEN BEGIN
IF p = 1 THEN value := 6
ELSE value := 4;
END
ELSE BEGIN
IF depth = 8 THEN value := 5;
END;
END;
IF value = 0 THEN BEGIN
IF 1 = ( depth MOD 2 ) THEN BEGIN
value := 2;
pm := 1;
END
ELSE BEGIN
value := 9;
pm := 2;
END;
p := 0;
WHILE p <= 8 DO BEGIN
IF board[ p ] = 0 THEN BEGIN
board[ p ] := pm;
score := minmax( alpha, beta, depth + 1, p );
board[ p ] := 0;
IF pm = 1 THEN BEGIN
IF score > value THEN BEGIN
value := score;
IF ( ( value = 6 ) OR ( value >= beta ) ) THEN
p := 10
ELSE BEGIN
IF ( value > alpha ) THEN alpha := value;
END;
END;
END
ELSE BEGIN
IF score < value THEN BEGIN
value := score;
IF ( value = 4 ) OR ( value <= alpha ) THEN
p := 10
ELSE BEGIN
IF ( value < beta ) THEN beta := value;
END;
END;
END;
END;
p := p + 1;
END;
END;
minmax := value;
END minmax;
PROCEDURE findsolution( move );
VALUE move;
INTEGER move;
BEGIN
INTEGER score;
board[ move ] := 1;
score := minmax( 2, 9, 0, move );
board[ move ] := 0;
END findsolution;
PROCEDURE main;
BEGIN
INTEGER i;
FOR i:=0 STEP 1 UNTIL 8 DO BEGIN
board[ i ] := 0;
END;
FOR i:=0 STEP 1 UNTIL 9 DO BEGIN
movecount := 0;
findsolution( 0 );
findsolution( 1 );
findsolution( 4 );
END;
text( 1, "moves: " );
write( 1, movecount );
text( 1, "*N" );
ioc(22);
END main;
main;
END
FINISH
| 0 | 0.589352 | 1 | 0.589352 | game-dev | MEDIA | 0.654505 | game-dev | 0.723302 | 1 | 0.723302 |
PentestSS13/Pentest | 1,713 | code/datums/quixotejump.dm | /datum/action/innate/quixotejump
name = "Dash"
desc = "Activate the quixote hardsuit's dash mechanism, allowing the user to dash over 4-tile gaps."
icon_icon = 'icons/mob/actions/actions_items.dmi'
button_icon_state = "jetboot"
var/charges = 3
var/max_charges = 3
var/charge_rate = 60 //3 seconds
var/datum/weakref/holder_ref
var/dash_sound = 'sound/magic/blink.ogg'
var/beam_effect = "blur"
/datum/action/innate/quixotejump/Grant(mob/user)
. = ..()
holder_ref = WEAKREF(user)
/datum/action/innate/quixotejump/IsAvailable()
if(charges > 0)
return TRUE
else
return FALSE
/datum/action/innate/quixotejump/proc/charge()
var/mob/living/carbon/human/holder = holder_ref.resolve()
if(isnull(holder))
return
charges = clamp(charges + 1, 0, max_charges)
holder.update_action_buttons_icon()
to_chat(holder, span_notice("Quixote dash mechanisms now have [charges]/[max_charges] charges."))
/datum/action/innate/quixotejump/Activate()
var/mob/living/carbon/human/holder = holder_ref.resolve()
if(isnull(holder))
return
if(!charges)
to_chat(holder, span_warning("Quixote dash mechanisms are still recharging. Please standby."))
return
var/newx = holder.x
var/newy = holder.y
switch(holder.dir)
if(NORTH) newy += 4
if(EAST) newx += 4
if(SOUTH) newy -= 4
if(WEST) newx -= 4
else CRASH("Invalid direction!")
var/turf/T = locate(newx, newy, holder.z)
holder.throw_at(T, 5, 3, spin = FALSE)
holder.visible_message(span_warning("[holder] suddenly dashes forward!"), span_notice("The Quixote dash mechanisms propel you forward!"))
playsound(T, dash_sound, 25, TRUE)
charges--
holder.update_action_buttons_icon()
addtimer(CALLBACK(src, PROC_REF(charge)), charge_rate)
| 0 | 0.92529 | 1 | 0.92529 | game-dev | MEDIA | 0.892897 | game-dev | 0.973027 | 1 | 0.973027 |
ProjectIgnis/CardScripts | 2,993 | official/c97007933.lua | --HSR魔剣ダーマ
--Hi-Speedroid Kendama
local s,id=GetID()
function s.initial_effect(c)
--synchro summon
Synchro.AddProcedure(c,nil,1,1,Synchro.NonTuner(nil),1,99)
c:EnableReviveLimit()
--pierce
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,0))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,id)
e2:SetCost(s.damcost)
e2:SetTarget(s.damtg)
e2:SetOperation(s.damop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,{id,1})
e3:SetCondition(s.spcon)
e3:SetCost(s.spcost)
e3:SetTarget(s.sptg)
e3:SetOperation(s.spop)
c:RegisterEffect(e3)
end
function s.cfilter(c)
return c:IsRace(RACE_MACHINE) and c:IsAbleToRemoveAsCost() and aux.SpElimFilter(c,true)
end
function s.damcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_MZONE|LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function s.damop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)==0
end
function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_NORMALSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetReset(RESET_PHASE|PHASE_END)
e1:SetTargetRange(1,0)
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_CANNOT_MSET)
Duel.RegisterEffect(e2,tp)
local e3=Effect.CreateEffect(e:GetHandler())
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e3:SetDescription(aux.Stringid(id,2))
e3:SetReset(RESET_PHASE|PHASE_END)
e3:SetTargetRange(1,0)
Duel.RegisterEffect(e3,tp)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end | 0 | 0.835766 | 1 | 0.835766 | game-dev | MEDIA | 0.994135 | game-dev | 0.865997 | 1 | 0.865997 |
dnnsoftware/Dnn.Platform | 8,963 | Dnn.AdminExperience/Library/Dnn.PersonaBar.Library/Prompt/ConsoleCommandBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.PersonaBar.Library.Prompt
{
using System;
using System.Collections;
using System.ComponentModel;
using Dnn.PersonaBar.Library.Prompt.Models;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Internal.SourceGenerators;
using DotNetNuke.Services.Localization;
/// <summary>A Prompt console command.</summary>
[DnnDeprecated(9, 7, 0, "Moved to DotNetNuke.Prompt in the core library project")]
public abstract partial class ConsoleCommandBase : IConsoleCommand
{
/// <inheritdoc/>
public abstract string LocalResourceFile { get; }
/// <summary>Gets resource key for the result html.</summary>
public virtual string ResultHtml => this.LocalizeString($"Prompt_{this.GetType().Name}_ResultHtml");
/// <inheritdoc/>
public string ValidationMessage { get; private set; }
protected PortalSettings PortalSettings { get; private set; }
protected UserInfo User { get; private set; }
protected int PortalId { get; private set; }
protected int TabId { get; private set; }
protected string[] Args { get; private set; }
protected Hashtable Flags { get; private set; }
/// <summary>Get the flag value.</summary>
/// <typeparam name="T">Type of the output expected.</typeparam>
/// <param name="flag">Flag name to look.</param>
/// <param name="fieldName">Filed name to show in message.</param>
/// <param name="defaultVal">Default value of the flag, if any.</param>
/// <param name="required">Is this a required flag or not.</param>
/// <param name="checkmain">Try to find the flag value in first args or not.</param>
/// <param name="checkpositive">This would be applicable only if the output is of type int or double and value should be positive.</param>
/// <returns>The flag value or <paramref name="defaultVal"/>.</returns>
public virtual T GetFlagValue<T>(string flag, string fieldName, T defaultVal, bool required = false, bool checkmain = false, bool checkpositive = false)
{
const string resourceFile = "~/DesktopModules/admin/Dnn.PersonaBar/App_LocalResources/SharedResources.resx";
dynamic value = null;
try
{
if (this.HasFlag(flag))
{
if (this.IsBoolean<T>())
{
value = this.Flag<bool>(flag, true);
}
else
{
value = this.Flag<T>(flag, defaultVal);
}
}
else
{
if (checkmain && this.Args.Length >= 2 && !this.IsFlag(this.Args[1]))
{
var tc = TypeDescriptor.GetConverter(typeof(T));
value = tc.ConvertFrom(this.Args[1]);
}
else if (!required)
{
value = defaultVal;
}
else
{
this.ValidationMessage += Localization.GetString(
checkmain ? "Promp_MainFlagIsRequired" : "Prompt_FlagIsRequired",
resourceFile)?.Replace("[0]", fieldName).Replace("[1]", flag);
}
}
}
catch (Exception)
{
this.ValidationMessage +=
Localization.GetString("Prompt_InvalidType", resourceFile)?
.Replace("[0]", fieldName)
.Replace("[1]", GetTypeName(typeof(T)));
}
if (checkpositive &&
(typeof(T) == typeof(int) || typeof(T) == typeof(long) || typeof(T) == typeof(int?) ||
typeof(T) == typeof(long?)) && value != null && Convert.ToInt32(value) <= 0)
{
this.ValidationMessage += Localization.GetString("Promp_PositiveValueRequired", resourceFile)?.Replace("[0]", fieldName);
}
return value ?? defaultVal;
}
public virtual void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId)
{
}
/// <inheritdoc/>
public void Initialize(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId)
{
this.Args = args;
this.PortalSettings = portalSettings;
this.User = userInfo;
this.PortalId = portalSettings.PortalId;
this.TabId = activeTabId;
this.ValidationMessage = string.Empty;
this.ParseFlags();
this.Init(args, portalSettings, userInfo, activeTabId);
}
/// <inheritdoc/>
public abstract ConsoleResultModel Run();
/// <inheritdoc/>
public virtual bool IsValid()
{
return string.IsNullOrEmpty(this.ValidationMessage);
}
protected bool HasFlag(string flagName)
{
flagName = NormalizeFlagName(flagName);
return this.Flags.ContainsKey(flagName);
}
protected bool IsFlag(object input)
{
var inputVal = Convert.ToString(input);
return !string.IsNullOrEmpty(inputVal) && inputVal.StartsWith("--");
}
protected string LocalizeString(string key)
{
var localizedText = Localization.GetString(key, this.LocalResourceFile);
return string.IsNullOrEmpty(localizedText) ? key : localizedText;
}
protected void AddMessage(string message)
{
this.ValidationMessage += message;
}
private static string GetTypeName(Type type)
{
if (type.FullName.ToLowerInvariant().Contains("int"))
{
return "Integer";
}
if (type.FullName.ToLowerInvariant().Contains("double"))
{
return "Double";
}
if (type.FullName.ToLowerInvariant().Contains("bool"))
{
return "Boolean";
}
if (type.FullName.ToLowerInvariant().Contains("datetime"))
{
return "DateTime";
}
return string.Empty;
}
private static string NormalizeFlagName(string flagName)
{
if (flagName == null)
{
return string.Empty;
}
if (flagName.StartsWith("--"))
{
flagName = flagName.Substring(2);
}
return flagName.ToLower().Trim();
}
private void ParseFlags()
{
this.Flags = new Hashtable();
// loop through arguments, skipping the first one (the command)
for (var i = 1; i <= this.Args.Length - 1; i++)
{
if (!this.Args[i].StartsWith("--"))
{
continue;
}
// found a flag
var flagName = NormalizeFlagName(this.Args[i]);
var flagValue = string.Empty;
if (i < this.Args.Length - 1)
{
if (!string.IsNullOrEmpty(this.Args[i + 1]))
{
if (this.Args[i + 1].StartsWith("--"))
{
// next value is another flag, so this flag has no value
flagValue = string.Empty;
}
else
{
flagValue = this.Args[i + 1];
}
}
else
{
flagValue = string.Empty;
}
}
this.Flags.Add(flagName.ToLower(), flagValue);
}
}
private object Flag<T>(string flagName, T defValue)
{
flagName = NormalizeFlagName(flagName);
if (!this.Flags.ContainsKey(flagName))
{
return defValue;
}
var retVal = this.Flags[flagName];
if (retVal == null || (string)retVal == string.Empty)
{
return defValue;
}
var tc = TypeDescriptor.GetConverter(typeof(T));
return tc.ConvertFrom(retVal);
}
private bool IsBoolean<T>()
{
return typeof(T) == typeof(bool?);
}
}
}
| 0 | 0.93178 | 1 | 0.93178 | game-dev | MEDIA | 0.439559 | game-dev | 0.938923 | 1 | 0.938923 |
Kooboo/Json | 40,126 | Kooboo.Json/Formatter/Serializer/Default/SpecialType.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Text;
namespace Kooboo.Json.Serializer
{
internal partial class SpecialTypeNormal : DefaultJsonFormatter
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(DateTime value, JsonSerializerHandler handler)
{
if (handler.Option.DatetimeFormat == DatetimeFormatEnum.ISO8601)
{
// "yyyy-mm-ddThh:mm:ss.fffffffZ"
// 0123456789ABCDEFGHIJKL
//
// Yes, DateTime.Max is in fact guaranteed to have a 4 digit year (and no more)
// f of 7 digits allows for 1 Tick level resolution
char[] buffer = new char[36];
buffer[0] = '"';
// Year
uint val = (uint)value.Year;
var digits = DigitPairs[(byte)(val % 100)];
buffer[4] = digits.Second;
buffer[3] = digits.First;
digits = DigitPairs[(byte)(val / 100)];
buffer[2] = digits.Second;
buffer[1] = digits.First;
// delimiter
buffer[5] = '-';
// Month
digits = DigitPairs[value.Month];
buffer[7] = digits.Second;
buffer[6] = digits.First;
// Delimiter
buffer[8] = '-';
// Day
digits = DigitPairs[value.Day];
buffer[10] = digits.Second;
buffer[9] = digits.First;
// Delimiter
buffer[11] = 'T';
digits = DigitPairs[value.Hour];
buffer[13] = digits.Second;
buffer[12] = digits.First;
// Delimiter
buffer[14] = ':';
digits = DigitPairs[value.Minute];
buffer[16] = digits.Second;
buffer[15] = digits.First;
// Delimiter
buffer[17] = ':';
digits = DigitPairs[value.Second];
buffer[19] = digits.Second;
buffer[18] = digits.First;
int fracEnd;
var remainingTicks = (value - new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second)).Ticks;
if (remainingTicks > 0)
{
buffer[20] = '.';
var fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[27] = digits.Second;
buffer[26] = digits.First;
fracEnd = 28;
}
else
{
fracEnd = 26;
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[25] = digits.Second;
buffer[24] = digits.First;
}
else
{
if (fracEnd == 26)
{
fracEnd = 24;
}
else
{
buffer[25] = '0';
buffer[24] = '0';
}
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[23] = digits.Second;
buffer[22] = digits.First;
}
else
{
if (fracEnd == 24)
{
fracEnd = 22;
}
else
{
buffer[23] = '0';
buffer[22] = '0';
}
}
fracPart = remainingTicks;
buffer[21] = (char)('0' + fracPart);
}
else
{
fracEnd = 20;
}
buffer[fracEnd] = 'Z';
buffer[fracEnd + 1] = '"';
handler.WriteChars(buffer, 0, fracEnd + 2);
}
else if (handler.Option.DatetimeFormat == DatetimeFormatEnum.RFC1123)
{
// ddd, dd MMM yyyy HH:mm:ss GMT'"
handler.WriteChar('"');
// compiles as a switch
switch (value.DayOfWeek)
{
case DayOfWeek.Sunday: handler.WriteString("Sun, "); break;
case DayOfWeek.Monday: handler.WriteString("Mon, "); break;
case DayOfWeek.Tuesday: handler.WriteString("Tue, "); break;
case DayOfWeek.Wednesday: handler.WriteString("Wed, "); break;
case DayOfWeek.Thursday: handler.WriteString("Thu, "); break;
case DayOfWeek.Friday: handler.WriteString("Fri, "); break;
case DayOfWeek.Saturday: handler.WriteString("Sat, "); break;
}
{
var day = DigitPairs[value.Day];
handler.WriteChar(day.First);
handler.WriteChar(day.Second);
handler.WriteChar(' ');
}
// compiles as a switch
switch (value.Month)
{
case 1: handler.WriteString("Jan "); break;
case 2: handler.WriteString("Feb "); break;
case 3: handler.WriteString("Mar "); break;
case 4: handler.WriteString("Apr "); break;
case 5: handler.WriteString("May "); break;
case 6: handler.WriteString("Jun "); break;
case 7: handler.WriteString("Jul "); break;
case 8: handler.WriteString("Aug "); break;
case 9: handler.WriteString("Sep "); break;
case 10: handler.WriteString("Oct "); break;
case 11: handler.WriteString("Nov "); break;
case 12: handler.WriteString("Dec "); break;
}
{
var year = value.Year;
var firstHalfYear = DigitPairs[year / 100];
handler.WriteChar(firstHalfYear.First);
handler.WriteChar(firstHalfYear.Second);
var secondHalfYear = DigitPairs[year % 100];
handler.WriteChar(secondHalfYear.First);
handler.WriteChar(secondHalfYear.Second);
handler.WriteChar(' ');
}
{
var hour = DigitPairs[value.Hour];
handler.WriteChar(hour.First);
handler.WriteChar(hour.Second);
handler.WriteChar(':');
}
{
var minute = DigitPairs[value.Minute];
handler.WriteChar(minute.First);
handler.WriteChar(minute.Second);
handler.WriteChar(':');
}
{
var second = DigitPairs[value.Second];
handler.WriteChar(second.First);
handler.WriteChar(second.Second);
}
handler.WriteString(" GMT\"");
}
else if (handler.Option.DatetimeFormat == DatetimeFormatEnum.Microsoft)
{
/*
"\/Date(628318530718)\/"
*/
handler.WriteString("\"\\/Date(");
handler.WriteLong((value.Ticks - 621355968000000000L) / 10000L);
handler.WriteString(")\\/\"");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(TimeSpan value, JsonSerializerHandler handler)
{
if (handler.Option.TimespanFormat == TimespanFormatEnum.ISO8601)
{
// can't negate this, have to handle it manually
if (value.Ticks == long.MinValue)
{
handler.WriteString("\"-P10675199DT2H48M5.4775808S\"");
return;
}
char[] buffer = new char[36];
handler.WriteChar('"');
if (value.Ticks < 0)
{
handler.WriteChar('-');
value = value.Negate();
}
handler.WriteChar('P');
var days = value.Days;
var hours = value.Hours;
var minutes = value.Minutes;
var seconds = value.Seconds;
// days
if (days > 0)
{
_CustomWriteIntUnrolledSigned(handler, days, buffer);
handler.WriteChar('D');
}
// time separator
handler.WriteChar('T');
// hours
if (hours > 0)
{
_CustomWriteIntUnrolledSigned(handler, hours, buffer);
handler.WriteChar('H');
}
// minutes
if (minutes > 0)
{
_CustomWriteIntUnrolledSigned(handler, minutes, buffer);
handler.WriteChar('M');
}
// seconds
_CustomWriteIntUnrolledSigned(handler, seconds, buffer);
// fractional part
{
var endCount = 0;
var remainingTicks = (value - new TimeSpan(days, hours, minutes, seconds, 0)).Ticks;
if (remainingTicks > 0)
{
int fracEnd;
buffer[0] = '.';
var fracPart = remainingTicks % 100;
remainingTicks /= 100;
TwoDigits digits;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[7] = digits.Second;
buffer[6] = digits.First;
fracEnd = 8;
}
else
{
fracEnd = 6;
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[5] = digits.Second;
buffer[4] = digits.First;
}
else
{
if (fracEnd == 6)
{
fracEnd = 4;
}
else
{
buffer[5] = '0';
buffer[4] = '0';
}
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[3] = digits.Second;
buffer[2] = digits.First;
}
else
{
if (fracEnd == 4)
{
fracEnd = 2;
}
else
{
buffer[3] = '0';
buffer[2] = '0';
}
}
fracPart = remainingTicks;
buffer[1] = (char)('0' + fracPart);
endCount = fracEnd;
}
handler.WriteChars(buffer, 0, endCount);
}
handler.WriteString("S\"");
}
else
{
if (value.Ticks == long.MinValue)
{
handler.WriteString("\"-10675199.02:48:05.4775808\"");
return;
}
char[] buffer = new char[36];
handler.WriteChar('"');
if (value.Ticks < 0)
{
handler.WriteChar('-');
value = value.Negate();
}
var days = value.Days;
var hours = value.Hours;
var minutes = value.Minutes;
var secs = value.Seconds;
TwoDigits digits;
// days
{
if (days != 0)
{
PrimitiveNormal.WriteValue(days, handler);
handler.WriteChar('.');
}
}
// hours
{
digits = DigitPairs[hours];
buffer[0] = digits.First;
buffer[1] = digits.Second;
}
buffer[2] = ':';
// minutes
{
digits = DigitPairs[minutes];
buffer[3] = digits.First;
buffer[4] = digits.Second;
}
buffer[5] = ':';
// seconds
{
digits = DigitPairs[secs];
buffer[6] = digits.First;
buffer[7] = digits.Second;
}
int endCount = 8;
// factional part
{
var remainingTicks = (value - new TimeSpan(value.Days, value.Hours, value.Minutes, value.Seconds, 0)).Ticks;
if (remainingTicks > 0)
{
int fracEnd;
buffer[8] = '.';
var fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[15] = digits.Second;
buffer[14] = digits.First;
fracEnd = 16;
}
else
{
fracEnd = 14;
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[13] = digits.Second;
buffer[12] = digits.First;
}
else
{
if (fracEnd == 14)
{
fracEnd = 12;
}
else
{
buffer[13] = '0';
buffer[12] = '0';
}
}
fracPart = remainingTicks % 100;
remainingTicks /= 100;
if (fracPart > 0)
{
digits = DigitPairs[fracPart];
buffer[11] = digits.Second;
buffer[10] = digits.First;
}
else
{
if (fracEnd == 12)
{
fracEnd = 10;
}
else
{
buffer[11] = '0';
buffer[10] = '0';
}
}
fracPart = remainingTicks;
buffer[9] = (char)('0' + fracPart);
endCount = fracEnd;
}
}
handler.WriteChars(buffer, 0, endCount);
handler.WriteChar('"');
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(Uri value, JsonSerializerHandler handler)
{
if (value == null)
handler.WriteString("null");
else
PrimitiveNormal.WriteValue(value.OriginalString, handler);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(byte[] value, JsonSerializerHandler handler)
{
if (value == null)
handler.WriteString("null");
else
{
if (handler.Option.IsByteArrayFormatBase64)
{
handler.WriteString("\"");
handler.WriteString(Convert.ToBase64String(value));
handler.WriteString("\"");
}
else
{
handler.WriteString("[");
bool isFirst = true;
foreach (var obj in value)
{
if (isFirst)
isFirst = false;
else
handler.WriteString(",");
PrimitiveNormal.WriteValue(obj, handler);
}
handler.WriteString("]");
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(Guid value, JsonSerializerHandler handler)
{
handler.WriteString("\"");
char[] buffer = new char[36];
// 1314FAD4-7505-439D-ABD2-DBD89242928C
// 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
// 8 4 4 4 12,36 char,64byte
// guid -> int short short 8byte => 8byte 4byte 4byte 8byte
// Guid is guaranteed to be a 36 character string
// get all the dashes in place
buffer[8] = '-';
buffer[13] = '-';
buffer[18] = '-';
buffer[23] = '-';
// Bytes are in a different order than you might expect
// For: 35 91 8b c9 - 19 6d - 40 ea - 97 79 - 88 9d 79 b7 53 f0
// Get: C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0
// Ix: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
// And we have to account for dashes
//
// So the map is like so:
// bytes[0] -> chars[3] -> buffer[ 6, 7]
// bytes[1] -> chars[2] -> buffer[ 4, 5]
// bytes[2] -> chars[1] -> buffer[ 2, 3]
// bytes[3] -> chars[0] -> buffer[ 0, 1]
// bytes[4] -> chars[5] -> buffer[11,12]
// bytes[5] -> chars[4] -> buffer[ 9,10]
// bytes[6] -> chars[7] -> buffer[16,17]
// bytes[7] -> chars[6] -> buffer[14,15]
// bytes[8] -> chars[8] -> buffer[19,20]
// bytes[9] -> chars[9] -> buffer[21,22]
// bytes[10] -> chars[10] -> buffer[24,25]
// bytes[11] -> chars[11] -> buffer[26,27]
// bytes[12] -> chars[12] -> buffer[28,29]
// bytes[13] -> chars[13] -> buffer[30,31]
// bytes[14] -> chars[14] -> buffer[32,33]
// bytes[15] -> chars[15] -> buffer[34,35]
var visibleMembers = new GuidStruct(value);
// bytes[0]
var b = visibleMembers.B00 * 2;
buffer[6] = WriteGuidLookup[b];
buffer[7] = WriteGuidLookup[b + 1];
// bytes[1]
b = visibleMembers.B01 * 2;
buffer[4] = WriteGuidLookup[b];
buffer[5] = WriteGuidLookup[b + 1];
// bytes[2]
b = visibleMembers.B02 * 2;
buffer[2] = WriteGuidLookup[b];
buffer[3] = WriteGuidLookup[b + 1];
// bytes[3]
b = visibleMembers.B03 * 2;
buffer[0] = WriteGuidLookup[b];
buffer[1] = WriteGuidLookup[b + 1];
// bytes[4]
b = visibleMembers.B04 * 2;
buffer[11] = WriteGuidLookup[b];
buffer[12] = WriteGuidLookup[b + 1];
// bytes[5]
b = visibleMembers.B05 * 2;
buffer[9] = WriteGuidLookup[b];
buffer[10] = WriteGuidLookup[b + 1];
// bytes[6]
b = visibleMembers.B06 * 2;
buffer[16] = WriteGuidLookup[b];
buffer[17] = WriteGuidLookup[b + 1];
// bytes[7]
b = visibleMembers.B07 * 2;
buffer[14] = WriteGuidLookup[b];
buffer[15] = WriteGuidLookup[b + 1];
// bytes[8]
b = visibleMembers.B08 * 2;
buffer[19] = WriteGuidLookup[b];
buffer[20] = WriteGuidLookup[b + 1];
// bytes[9]
b = visibleMembers.B09 * 2;
buffer[21] = WriteGuidLookup[b];
buffer[22] = WriteGuidLookup[b + 1];
// bytes[10]
b = visibleMembers.B10 * 2;
buffer[24] = WriteGuidLookup[b];
buffer[25] = WriteGuidLookup[b + 1];
// bytes[11]
b = visibleMembers.B11 * 2;
buffer[26] = WriteGuidLookup[b];
buffer[27] = WriteGuidLookup[b + 1];
// bytes[12]
b = visibleMembers.B12 * 2;
buffer[28] = WriteGuidLookup[b];
buffer[29] = WriteGuidLookup[b + 1];
// bytes[13]
b = visibleMembers.B13 * 2;
buffer[30] = WriteGuidLookup[b];
buffer[31] = WriteGuidLookup[b + 1];
// bytes[14]
b = visibleMembers.B14 * 2;
buffer[32] = WriteGuidLookup[b];
buffer[33] = WriteGuidLookup[b + 1];
// bytes[15]
b = visibleMembers.B15 * 2;
buffer[34] = WriteGuidLookup[b];
buffer[35] = WriteGuidLookup[b + 1];
handler.WriteChars(buffer, 0, 36);
handler.WriteString("\"");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(ExpandoObject value, JsonSerializerHandler handler)
{
if (value == null)
{
handler.WriteString("null");
return;
}
if (handler.Option.ReferenceLoopHandling != JsonReferenceHandlingEnum.None)
{
if (handler.SerializeStacks.Contains(value))
{
if (handler.Option.ReferenceLoopHandling == JsonReferenceHandlingEnum.Null)
handler.WriteString("null");
else if (handler.Option.ReferenceLoopHandling == JsonReferenceHandlingEnum.Empty)
handler.WriteString("{}");
else if (handler.Option.ReferenceLoopHandling == JsonReferenceHandlingEnum.Remove)
RemoveWriterHelper.RemoveDictionaryKey(handler);
return;
}
handler.SerializeStacks.Push(value);
}
IDictionary<string, object> keyValuePairs = value;
handler.WriteString("{");
bool isFirst = true;
foreach (var item in value)
{
if (isFirst)
isFirst = false;
else
handler.WriteString(",");
PrimitiveNormal.WriteValue(item.Key, handler);
handler.WriteString(":");
var val = item.Value;
PrimitiveNormal.WriteValue(val, handler);
}
handler.WriteString("}");
if (handler.Option.ReferenceLoopHandling != JsonReferenceHandlingEnum.None)
handler.SerializeStacks.Pop();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(NameValueCollection value, JsonSerializerHandler handler)
{
if (value == null)
{
handler.WriteString("null");
return;
}
handler.WriteString("{");
bool isFirst = true;
foreach (string item in value)
{
if (isFirst)
isFirst = false;
else
handler.WriteString(",");
var name = item;
PrimitiveNormal.WriteValue(name, handler);
handler.WriteString(":");
var val = value[name];
PrimitiveNormal.WriteValue(val, handler);
}
handler.WriteString("}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(StringDictionary value, JsonSerializerHandler handler)
{
if (value == null)
{
handler.WriteString("null");
return;
}
handler.WriteString("{");
bool isFirst = true;
foreach (DictionaryEntry item in value)
{
if (isFirst)
isFirst = false;
else
handler.WriteString(",");
var name = item.Key;
PrimitiveNormal.WriteValue(item.Key, handler);
handler.WriteString(":");
var val = item.Value;
PrimitiveNormal.WriteValue(val, handler);
}
handler.WriteString("}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(DataTable value, JsonSerializerHandler handler)
{
if (value == null)
{
handler.WriteString("null");
return;
}
handler.WriteString("[");
bool isFirst = true;
foreach (DataRow row in value.Rows)
{
if (isFirst)
isFirst = false;
else
handler.WriteString(",");
handler.WriteString("{");
bool isFirst2 = true;
foreach (DataColumn column in row.Table.Columns)
{
if (isFirst2)
isFirst2 = false;
else
handler.WriteString(",");
object columnValue = row[column];
handler.WriteString("\"");
handler.WriteString(column.ColumnName);//没有检查
handler.WriteString("\":");
PrimitiveNormal.WriteValue(columnValue, handler);
}
handler.WriteString("}");
}
handler.WriteString("]");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(DBNull value, JsonSerializerHandler handler)
{
handler.WriteString("null");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[FuncLable(FuncType.SameType)]
internal static void WriteValue(StringBuilder value, JsonSerializerHandler handler)
{
if (value == null)
handler.WriteString("null");
else
{
handler.WriteString("\"");
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
if (c == '\\')//\u005c //%x5c a\\b => a\u005cb
{
handler.WriteString(@"\\");
continue;
}
if (c == '"')//\u0022 //%x22
{
handler.WriteString("\\\"");
continue;
}
//如果是jsonp格式,多了 u2028 u2029的转换
switch (c)
{
//%x00-x19
case '\u0000': handler.WriteString(@"\u0000"); continue;
case '\u0001': handler.WriteString(@"\u0001"); continue;
case '\u0002': handler.WriteString(@"\u0002"); continue;
case '\u0003': handler.WriteString(@"\u0003"); continue;
case '\u0004': handler.WriteString(@"\u0004"); continue;
case '\u0005': handler.WriteString(@"\u0005"); continue;
case '\u0006': handler.WriteString(@"\u0006"); continue;
case '\u0007': handler.WriteString(@"\u0007"); continue;
case '\u0008': handler.WriteString(@"\b"); continue;
case '\u0009': handler.WriteString(@"\t"); continue;
case '\u000A': handler.WriteString(@"\n"); continue;
case '\u000B': handler.WriteString(@"\u000b"); continue;
case '\u000C': handler.WriteString(@"\f"); continue;
case '\u000D': handler.WriteString(@"\r"); continue;
case '\u000E': handler.WriteString(@"\u000e"); continue;
case '\u000F': handler.WriteString(@"\u000f"); continue;
case '\u0010': handler.WriteString(@"\u0010"); continue;
case '\u0011': handler.WriteString(@"\u0011"); continue;
case '\u0012': handler.WriteString(@"\u0012"); continue;
case '\u0013': handler.WriteString(@"\u0013"); continue;
case '\u0014': handler.WriteString(@"\u0014"); continue;
case '\u0015': handler.WriteString(@"\u0015"); continue;
case '\u0016': handler.WriteString(@"\u0016"); continue;
case '\u0017': handler.WriteString(@"\u0017"); continue;
case '\u0018': handler.WriteString(@"\u0018"); continue;
case '\u0019': handler.WriteString(@"\u0019"); continue;
case '\u001A': handler.WriteString(@"\u001a"); continue;
case '\u001B': handler.WriteString(@"\u001b"); continue;
case '\u001C': handler.WriteString(@"\u001c"); continue;
case '\u001D': handler.WriteString(@"\u001d"); continue;
case '\u001E': handler.WriteString(@"\u001e"); continue;
case '\u001F': handler.WriteString(@"\u001f"); continue;
default: handler.WriteChar(c); continue;
}
}
handler.WriteString("\"");
}
}
internal struct TwoDigits
{
public readonly char First;
public readonly char Second;
public TwoDigits(char first, char second)
{
First = first;
Second = second;
}
}
internal static readonly TwoDigits[] DigitPairs =
CreateArray(100, i => new TwoDigits((char)('0' + (i / 10)), (char)+('0' + (i % 10))));
internal static readonly char[] DigitTriplets =
CreateArray(3 * 1000, i =>
{
var ibase = i / 3;
switch (i % 3)
{
case 0:
return (char)('0' + ibase / 100 % 10);
case 1:
return (char)('0' + ibase / 10 % 10);
case 2:
return (char)('0' + ibase % 10);
default:
throw new InvalidOperationException("Unexpectedly reached default case in switch block.");
}
});
internal static T[] CreateArray<T>(int count, Func<int, T> generator)
{
var arr = new T[count];
for (var i = 0; i < arr.Length; i++)
{
arr[i] = generator(i);
}
return arr;
}
}
internal partial class SpecialTypeNormal
{
static readonly char[] WriteGuidLookup = new char[] { '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '0', 'a', '0', 'b', '0', 'c', '0', 'd', '0', 'e', '0', 'f', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '1', 'a', '1', 'b', '1', 'c', '1', 'd', '1', 'e', '1', 'f', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '2', 'a', '2', 'b', '2', 'c', '2', 'd', '2', 'e', '2', 'f', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '3', 'a', '3', 'b', '3', 'c', '3', 'd', '3', 'e', '3', 'f', '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', '4', 'a', '4', 'b', '4', 'c', '4', 'd', '4', 'e', '4', 'f', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', '5', 'a', '5', 'b', '5', 'c', '5', 'd', '5', 'e', '5', 'f', '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', '6', 'a', '6', 'b', '6', 'c', '6', 'd', '6', 'e', '6', 'f', '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', '7', 'a', '7', 'b', '7', 'c', '7', 'd', '7', 'e', '7', 'f', '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '8', 'a', '8', 'b', '8', 'c', '8', 'd', '8', 'e', '8', 'f', '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9', '9', 'a', '9', 'b', '9', 'c', '9', 'd', '9', 'e', '9', 'f', 'a', '0', 'a', '1', 'a', '2', 'a', '3', 'a', '4', 'a', '5', 'a', '6', 'a', '7', 'a', '8', 'a', '9', 'a', 'a', 'a', 'b', 'a', 'c', 'a', 'd', 'a', 'e', 'a', 'f', 'b', '0', 'b', '1', 'b', '2', 'b', '3', 'b', '4', 'b', '5', 'b', '6', 'b', '7', 'b', '8', 'b', '9', 'b', 'a', 'b', 'b', 'b', 'c', 'b', 'd', 'b', 'e', 'b', 'f', 'c', '0', 'c', '1', 'c', '2', 'c', '3', 'c', '4', 'c', '5', 'c', '6', 'c', '7', 'c', '8', 'c', '9', 'c', 'a', 'c', 'b', 'c', 'c', 'c', 'd', 'c', 'e', 'c', 'f', 'd', '0', 'd', '1', 'd', '2', 'd', '3', 'd', '4', 'd', '5', 'd', '6', 'd', '7', 'd', '8', 'd', '9', 'd', 'a', 'd', 'b', 'd', 'c', 'd', 'd', 'd', 'e', 'd', 'f', 'e', '0', 'e', '1', 'e', '2', 'e', '3', 'e', '4', 'e', '5', 'e', '6', 'e', '7', 'e', '8', 'e', '9', 'e', 'a', 'e', 'b', 'e', 'c', 'e', 'd', 'e', 'e', 'e', 'f', 'f', '0', 'f', '1', 'f', '2', 'f', '3', 'f', '4', 'f', '5', 'f', '6', 'f', '7', 'f', '8', 'f', '9', 'f', 'a', 'f', 'b', 'f', 'c', 'f', 'd', 'f', 'e', 'f', 'f' };
static void _CustomWriteIntUnrolledSigned(JsonSerializerHandler handler, int num, char[] buffer)
{
if (num == int.MinValue)
{
handler.WriteString("-2147483648");
return;
}
int numLen;
int number;
if (num < 0)
{
handler.WriteChar('-');
number = -num;
}
else
{
number = num;
}
if (number < 1000)
{
if (number >= 100)
{
handler.WriteChars(DigitTriplets, number * 3, 3);
}
else
{
if (number >= 10)
{
handler.WriteChars(DigitTriplets, number * 3 + 1, 2);
}
else
{
handler.WriteChars(DigitTriplets, number * 3 + 2, 1);
}
}
return;
}
var d012 = number % 1000 * 3;
int d543;
if (number < 1000000)
{
d543 = (number / 1000) * 3;
if (number >= 100000)
{
numLen = 6;
goto digit5;
}
else
{
if (number >= 10000)
{
numLen = 5;
goto digit4;
}
else
{
numLen = 4;
goto digit3;
}
}
}
d543 = (number / 1000) % 1000 * 3;
int d876;
if (number < 1000000000)
{
d876 = (number / 1000000) * 3;
if (number >= 100000000)
{
numLen = 9;
goto digit8;
}
else
{
if (number >= 10000000)
{
numLen = 8;
goto digit7;
}
else
{
numLen = 7;
goto digit6;
}
}
}
d876 = (number / 1000000) % 1000 * 3;
numLen = 10;
// uint is between 0 & 4,294,967,295 (in practice we only get to int.MaxValue, but that's the same # of digits)
// so 1 to 10 digits
// [01,]000,000-[99,]000,000
var d9 = number / 1000000000;
buffer[0] = (char)('0' + d9);
digit8:
buffer[1] = DigitTriplets[d876];
digit7:
buffer[2] = DigitTriplets[d876 + 1];
digit6:
buffer[3] = DigitTriplets[d876 + 2];
digit5:
buffer[4] = DigitTriplets[d543];
digit4:
buffer[5] = DigitTriplets[d543 + 1];
digit3:
buffer[6] = DigitTriplets[d543 + 2];
buffer[7] = DigitTriplets[d012];
buffer[8] = DigitTriplets[d012 + 1];
buffer[9] = DigitTriplets[d012 + 2];
handler.WriteChars(buffer, 10 - numLen, numLen);
}
}
}
| 0 | 0.74491 | 1 | 0.74491 | game-dev | MEDIA | 0.239396 | game-dev | 0.951489 | 1 | 0.951489 |
Dimbreath/AzurLaneData | 22,705 | zh-TW/view/main/navalacademyscene.lua | slot0 = class("NavalAcademyScene", import("..base.BaseUI"))
slot0.STATE_ACADEMY = "STATE_ACADEMY"
slot0.STATE_COURSE = "STATE_COURSE"
slot0.STATE_RESOURCE = "STATE_RESOURCE"
slot0.STATE_MERCHANT = "STATE_MERCHANT"
slot0.COURSE_COUNT = 5
slot0.ICON_COUNT = 3
slot0.MAX_SLOT = 3
slot1 = 5
slot0.WARP_TO_TACTIC = "WARP_TO_TACTIC"
function slot0.getUIName(slot0)
return "NavalAcademyUI"
end
function slot0.init(slot0)
slot0.sakura = slot0:findTF("effect")
slot0._map = slot0:findTF("academyMap/map")
slot0.wave = slot0._map:Find("effect_wave")
slot0._classBtn = slot0._map:Find("classRoom")
setActive(slot0._classBtn, not LOCK_CLASSROOM)
slot0._fountain = slot0._map:Find("fountain")
slot0._commanderBtn = slot0._map:Find("commander")
slot0._merchant = slot0._map:Find("merchant")
slot0._tacticRoom = slot0._map:Find("tacticRoom")
slot0._shipTpl = slot0._map:Find("ship")
slot0._blurLayer = slot0:findTF("blur_container")
slot0._topPanel = slot0._blurLayer:Find("adapt/top")
slot0._backBtn = slot0._topPanel:Find("title/back")
slot0._shop = slot0._map:Find("shop")
slot0._getGold = slot0._shop:Find("popup_contain/popup")
slot0._canteen = slot0._map:Find("canteen")
slot0._getOil = slot0._canteen:Find("popup_contain/popup")
slot0._resourceLayer = slot0:findTF("blur_container/resource_panel")
slot0._merchantTip = slot0:findTF("merchant/tip", slot0._map)
slot0._tacticTips = slot0:findTF("tip", slot0._tacticRoom)
slot0._fountainReminder = slot0:findTF("tip", slot0._fountain)
slot0._currentCourseID = slot0.contextData.number
slot0._startCourseFlag = slot0.contextData.startCourseFlag
slot0.contextData.number = nil
slot0.contextData.selectedShips = nil
slot0.contextData.startCourseFlag = nil
slot0.warp = slot0.contextData.warp
slot0.contextData.warp = nil
slot0._panelTimer = {}
slot0._buildingTimers = {}
slot0._mapTimers = {}
slot0.academyStudents = {}
slot0.academyGraphPath = GraphPath.New(AcademyGraph)
slot0._playerResOb = slot0:findTF("blur_container/adapt/top/playerRes")
slot0._resPanel = PlayerResource.New()
tf(slot0._resPanel._go):SetParent(tf(slot0._playerResOb), false)
slot0:uiStartAnimating()
end
function slot0.uiStartAnimating(slot0)
setAnchoredPosition(slot0._topPanel, {
y = 84
})
shiftPanel(slot0._topPanel, nil, 0, 0.3, 0, true, true)
end
function slot0.uiExitAnimating(slot0)
shiftPanel(slot0._topPanel, nil, slot0._topPanel.rect.height, 0.3, 0, true, true)
end
function slot0.didEnter(slot0)
setText(slot0._resourceLayer:Find("describe/canteen"), i18n("naval_academy_res_desc_cateen"))
setText(slot0._resourceLayer:Find("describe/shop"), i18n("naval_academy_res_desc_shop"))
slot0._currentState = uv0.STATE_ACADEMY
onButton(slot0, slot0._backBtn, function ()
if uv0._currentState == uv1.STATE_ACADEMY then
uv0:uiExitAnimating()
uv0:emit(uv1.ON_BACK, nil, 0.3)
elseif uv0._currentState == uv1.STATE_COURSE then
uv0:CloseCoursePanel()
elseif uv0._currentState == uv1.STATE_RESOURCE then
uv0:CloseResourcePanel()
end
end, SFX_CANCEL)
setText(slot0._classBtn:Find("title/name/Text"), i18n("school_title_dajiangtang"))
setText(slot0._commanderBtn:Find("title/name/Text"), i18n("school_title_zhihuimiao"))
setText(slot0._tacticRoom:Find("title/name/Text"), i18n("school_title_xueyuan"))
setText(slot0._merchant:Find("title/name/Text"), i18n("school_title_shangdian"))
setText(slot0._fountain:Find("title/name/Text"), i18n("school_title_shoucang"))
setText(slot0._shop:Find("title/name/Text"), i18n("school_title_xiaomaibu"))
setText(slot0._canteen:Find("title/name/Text"), i18n("school_title_shitang"))
onButton(slot0, slot0._classBtn, function ()
slot0, slot1 = pg.SystemOpenMgr.GetInstance():isOpenSystem(uv0._player.level, "ClassMediator")
if not slot0 then
pg.TipsMgr.GetInstance():ShowTips(slot1)
return
end
uv0:emit(NavalAcademyMediator.OPEN_CLASS)
end, SFX_PANEL)
onButton(slot0, slot0._canteen, function ()
uv0:OpenResourcePanel(uv0._oilVO)
end, SFX_PANEL)
onButton(slot0, slot0._shop, function ()
uv0:OpenResourcePanel(uv0._goldVO)
end, SFX_PANEL)
onButton(slot0, slot0._getGold, function ()
if uv0._player.goldField <= 0 then
pg.TipsMgr.GetInstance():ShowTips(i18n("battle_levelScene_0Gold"))
else
uv0:emit(NavalAcademyMediator.GET_RES, ResourceField.TYPE_GOLD)
end
end, SFX_PANEL)
onButton(slot0, slot0._getOil, function ()
if uv0._player.oilField <= 0 then
pg.TipsMgr.GetInstance():ShowTips(i18n("battle_levelScene_0Oil"))
else
uv0:emit(NavalAcademyMediator.GET_RES, ResourceField.TYPE_OIL)
end
end, SFX_PANEL)
onButton(slot0, slot0._merchant, function ()
setActive(uv0._merchantTip, false)
uv0:emit(NavalAcademyMediator.GO_SHOP)
end, SFX_PANEL)
onButton(slot0, slot0._tacticRoom, function ()
setActive(uv0._tacticTips, false)
uv0:activeSakura(false)
uv0:emit(NavalAcademyMediator.OPEN_TACTIC, function ()
uv0:activeSakura(true)
end)
end, SFX_PANEL)
onButton(slot0, slot0._commanderBtn, function ()
uv0:emit(NavalAcademyMediator.OPEN_COMMANDER)
end)
onButton(slot0, slot0._fountain, function ()
uv0:activeSakura(false)
uv0:emit(NavalAcademyMediator.OPEN_TROPHY_GALLERY, function ()
uv0:activeSakura(true)
end, SFX_PANEL)
end)
if slot0._currentCourseID ~= nil then
if slot0._startCourseFlag then
pg.TipsMgr.GetInstance():ShowTips(i18n("main_navalAcademyScene_quest_startClass"))
end
triggerToggle(slot0._toggleList[slot0._currentCourseID], true)
slot0.currentCourseID = nil
end
if slot0.warp == uv0.WARP_TO_TACTIC then
slot0:activeSakura(false)
slot0:emit(NavalAcademyMediator.OPEN_TACTIC, function ()
uv0:activeSakura(true)
end)
end
blinkAni(go(slot0:findTF("blur_container/resource_panel/produce/pre_value")), 0.8)
blinkAni(go(slot0:findTF("blur_container/resource_panel/store/pre_value")), 0.8)
slot0:updateStudents()
slot0:updateTrophyReminder()
slot0.bulinTip = AprilFoolBulinSubView.ShowAprilFoolBulin(slot0, 60037)
end
function slot0.SetPlayerInfo(slot0, slot1, slot2, slot3, slot4)
slot0._player = slot1
slot0._oilVO = slot2
slot0._goldVO = slot3
slot0._classVO = slot4
slot0:updateMap()
slot0._resPanel:setResources(slot1)
end
function slot0.SetMerchantInfo(slot0, slot1)
if slot1:isUpdateGoods() then
setActive(slot0._merchantTip, true)
end
end
function slot0.SetTacticInfo(slot0, slot1)
slot0.students = slot1
for slot6, slot7 in pairs(slot1) do
if slot7:getFinishTime() <= pg.TimeMgr.GetInstance():GetServerTime() then
setActive(slot0._tacticTips, true)
break
end
end
end
function slot0.SetCourseInfo(slot0, slot1)
slot0._courseVO = slot1
end
function slot0.SetUnclaimTrophyCount(slot0, slot1)
slot0._unclaimTrophyCount = slot1
end
function slot0.updateMap(slot0)
slot0:updateResourceBuilding(slot0._canteen, slot0._player.oilField, slot0._oilVO)
slot0:updateResourceBuilding(slot0._shop, slot0._player.goldField, slot0._goldVO)
slot0:updateResourceBuilding(slot0._classBtn, nil, slot0._classVO)
end
function slot0.updateResourceBuilding(slot0, slot1, slot2, slot3)
pg.TimeMgr.GetInstance():RemoveTimer(slot0._buildingTimers[slot3])
if slot2 then
SetActive(slot1:Find("popup_contain/popup"), slot2 > 0)
end
SetActive(slot1:Find("tip"), false)
if slot3._type == ResourceField.TYPE_CLASS and slot0._courseVO:inClass() and AcademyCourse.MaxStudyTime <= pg.TimeMgr.GetInstance():GetServerTime() - slot0._courseVO.timestamp then
SetActive(slot1:Find("tip"), true)
end
slot4 = slot1:Find("title/name")
if slot3:GetUpgradeTimeStamp() == 0 then
SetActive(slot4, true)
SetActive(slot1:Find("title/count"), false)
slot4:Find("level"):GetComponent(typeof(Text)).text = "Lv." .. slot3:GetLevel()
if slot3:CanUpgrade(slot0._player.level, slot0._player.gold) then
SetActive(slot1:Find("tip"), true)
end
else
SetActive(slot4, false)
SetActive(slot5, true)
slot6 = slot5:Find("Text"):GetComponent(typeof(Text))
slot0._buildingTimers[slot3] = pg.TimeMgr.GetInstance():AddTimer("timer", 0, 1, function ()
if uv0:GetDuration() and slot0 > 0 then
uv1.text = pg.TimeMgr.GetInstance():DescCDTime(slot0)
else
pg.TimeMgr.GetInstance():RemoveTimer(uv2._buildingTimers[uv0])
uv2:emit(NavalAcademyMediator.UPGRADE_TIMES_UP)
end
end)
end
end
function slot0.OpenResourcePanel(slot0, slot1)
setActive(slot0._topPanel, false)
slot0:openSecondPanel()
slot0._currentState = uv0.STATE_RESOURCE
SetActive(slot0._resourceLayer, true)
onButton(slot0, slot0:findTF("mengban", slot0._resourceLayer), function ()
uv0:CloseResourcePanel()
end)
slot2 = slot1:bindConfigTable()
SetActive(slot0._resourceLayer:Find("icon/" .. slot1:GetKeyWord()), true)
setText(slot0._resourceLayer:Find("icon/" .. slot1:GetKeyWord() .. "/current"), "Lv." .. slot1:GetLevel())
eachChild(slot0._resourceLayer:Find("describe"), function (slot0)
setActive(slot0, false)
end)
SetActive(slot0._resourceLayer:Find("describe/" .. slot1:GetKeyWord()), true)
SetActive(slot0._resourceLayer:Find("produce/label/" .. slot1:GetKeyWord()), true)
slot11 = slot1:GetLevel()
slot12 = slot2.all[#slot2.all]
slot13 = slot2[slot11]
slot14 = slot2[slot12]
if slot11 == slot12 then
SetActive(slot0._resourceLayer:Find("upgrading_block"), false)
slot3:GetComponent("Button").interactable = false
slot0._resourceLayer:Find("upgrade_btn"):Find("cost"):GetComponent("Text").text = "-"
slot0._resourceLayer:Find("upgrade_duration/Text"):GetComponent(typeof(Text)).text = "-"
slot0._resourceLayer:Find("bg/bg/title/lv/current"):GetComponent(typeof(Text)).text = "Lv.Max"
setActive(slot0._resourceLayer:Find("bg/bg/title/lv/next"), false)
slot0:setBar(slot0._resourceLayer:Find("produce"), slot13.production, 0, slot14.production, slot13.hour_time)
slot0:setBar(slot0._resourceLayer:Find("store"), slot13.store, 0, slot14.store)
else
slot15 = slot2[slot11 + 1]
slot0:setBar(slot7, slot13.production, slot15.production - slot13.production, slot14.production, slot13.hour_time)
slot0:setBar(slot8, slot13.store, slot15.store - slot13.store, slot14.store)
slot5.text = slot13.use[2] <= slot0._player.gold and slot13.use[2] or "<color=#FB4A2C>" .. slot13.use[2] .. "</color>"
slot9:GetComponent(typeof(Text)).text = "Lv." .. slot11
slot10:GetComponent(typeof(Text)).text = "> Lv." .. slot11 + 1
if slot1:GetUpgradeTimeStamp() == 0 then
SetActive(slot4, false)
SetActive(slot3, true)
slot6.text = pg.TimeMgr.GetInstance():DescCDTime(slot13.time)
slot3:GetComponent("Button").interactable = true
onButton(slot0, slot3, function ()
uv0:emit(NavalAcademyMediator.UPGRADE_FIELD, uv1)
end, SFX_UI_ACADEMY_LVLUP)
else
SetActive(slot4, true)
SetActive(slot3, false)
slot3:GetComponent("Button").interactable = false
slot0._panelTimer[#slot0._panelTimer + 1] = pg.TimeMgr.GetInstance():AddTimer("timer", 0, 1, function ()
if uv0:GetDuration() and slot0 > 0 then
uv1.text = pg.TimeMgr.GetInstance():DescCDTime(slot0)
else
uv2:emit(NavalAcademyMediator.UPGRADE_TIMES_UP, uv0)
end
end)
end
end
onButton(slot0, findTF(slot0._resourceLayer, "top/btnBack"), function ()
uv0:CloseResourcePanel()
end, SFX_CANCEL)
end
function slot0.setSliderValue(slot0, slot1, slot2)
slot1.value = slot2 == 0 and slot2 or math.max(slot2, 0.08)
end
function slot0.setBar(slot0, slot1, slot2, slot3, slot4, slot5)
slot1:Find("pre_value"):GetComponent(typeof(Image)).fillAmount = (slot2 + slot3) / slot4
slot1:Find("value"):GetComponent(typeof(Image)).fillAmount = slot2 / slot4
if slot5 then
slot1:Find("current"):GetComponent(typeof(Text)).text = slot2 * slot5 .. "/H"
else
slot5 = 1
slot1:Find("current"):GetComponent(typeof(Text)).text = slot2 .. "/" .. slot4
end
if slot3 <= 0 then
SetActive(slot1:Find("advance"), false)
else
SetActive(slot8, true)
slot8:GetComponent(typeof(Text)).text = "[+" .. slot3 * slot5 .. "]"
end
end
function slot0.CloseResourcePanel(slot0)
setActive(slot0._topPanel, true)
SetActive(slot0._resourceLayer, false)
SetActive(slot0._resourceLayer:Find("icon/canteen"), false)
SetActive(slot0._resourceLayer:Find("icon/shop"), false)
SetActive(slot0._resourceLayer:Find("describe/canteen"), false)
SetActive(slot0._resourceLayer:Find("describe/shop"), false)
SetActive(slot0._resourceLayer:Find("produce/label/canteen"), false)
SetActive(slot0._resourceLayer:Find("produce/label/shop"), false)
slot0:closeSecondPanel()
end
function slot0.GetResourceDone(slot0, slot1, slot2)
slot3 = nil
if slot1 == ResourceField.TYPE_GOLD then
slot3 = slot0._shop
elseif slot1 == ResourceField.TYPE_OIL then
slot3 = slot0._canteen
end
SetActive(slot3:Find("popup_contain/popup"), false)
slot4 = slot3:Find("float")
slot6 = slot4:GetComponent(typeof(Image))
SetActive(slot4, true)
slot4:Find("Text"):GetComponent(typeof(Text)).text = "+" .. slot2
rtf(slot4).anchoredPosition = Vector2(slot4.localPosition.x, y)
LeanTween.moveY(rtf(slot4), 100, 4):setOnUpdate(System.Action_float(function (slot0)
slot1 = Color(1, 1, 1, 1.5 - slot0 * 0.05)
uv0.color = slot1
uv1.color = slot1
end)):setOnComplete(System.Action(function ()
SetActive(uv0, false)
uv0.localPosition = uv1
end))
end
function slot0.openSecondPanel(slot0)
slot0.isOpenSecondPanel = true
for slot4, slot5 in ipairs(slot0._panelTimer) do
pg.TimeMgr.GetInstance():RemoveTimer(slot5)
end
slot0._panelTimer = {}
pg.UIMgr.GetInstance():BlurPanel(slot0._blurLayer, false)
end
function slot0.closeSecondPanel(slot0)
slot0.isOpenSecondPanel = nil
slot4 = slot0._tf
pg.UIMgr.GetInstance():UnblurPanel(slot0._blurLayer, slot4)
for slot4, slot5 in ipairs(slot0._panelTimer) do
pg.TimeMgr.GetInstance():RemoveTimer(slot5)
end
slot0._panelTimer = {}
slot0._currentState = uv0.STATE_ACADEMY
end
function slot0.loadCharacter(slot0, slot1, slot2, slot3)
function slot4(slot0)
if uv0 == nil then
PoolMgr.GetInstance():ReturnSpineChar(uv1, slot0)
return
end
tf(slot0):SetParent(uv0, false)
tf(slot0).localScale = Vector3(0.5, 0.5, 1)
pg.ViewUtils.SetLayer(tf(slot0), Layer.UI)
slot0:GetComponent("SpineAnimUI"):SetAction(uv2 or "stand", 0)
uv3.prefabs = uv3.prefabs or {}
table.insert(uv3.prefabs, uv1)
uv3.models = uv3.models or {}
table.insert(uv3.models, slot0)
end
return function (slot0)
PoolMgr.GetInstance():GetSpineChar(uv0, true, function (slot0)
uv0(slot0)
uv1()
end)
end
end
function slot0.SetPainting(slot0, slot1)
setPaintingPrefabAsync(slot0._painting, Ship.getPaintingName(slot1), "info")
onButton(slot0, slot0._painting, function ()
setButtonEnabled(uv0._painting, false)
slot0 = {
"touch",
"touch2"
}
uv0:displayShipWord(uv1, slot0[math.random(#slot0)])
end)
end
function slot0.RetPainting(slot0, slot1)
retPaintingPrefab(slot0._painting, Ship.getPaintingName(slot1))
end
function slot0.displayShipWord(slot0, slot1, slot2)
if not slot0._chatFlag then
slot0._chatFlag = true
if slot0._chatTimer then
slot0._chatTimer:Stop()
slot0._chatTimer = nil
end
slot3, slot4, slot5 = ShipWordHelper.GetWordAndCV(slot1.skinId, slot2)
setText(slot0._chatText, slot5)
if CHAT_POP_STR_LEN_SHORT < #slot0._chatText:GetComponent(typeof(Text)).text then
slot6.alignment = TextAnchor.MiddleLeft
else
slot6.alignment = TextAnchor.MiddleCenter
end
LeanTween.scale(rtf(slot0._chat.gameObject), Vector3.New(1, 1, 1), 0.45):setEase(LeanTweenType.easeOutBack):setOnComplete(System.Action(function ()
LeanTween.scale(rtf(uv0._chat.gameObject), Vector3.New(0, 0, 1), 0.45):setEase(LeanTweenType.easeInBack):setDelay(2.3):setOnComplete(System.Action(function ()
uv0._chatFlag = nil
uv0:startChatTimer(uv1)
setButtonEnabled(uv0._painting, true)
end))
end))
end
end
function slot0.startChatTimer(slot0, slot1)
if slot0._chatFlag then
return
end
if slot0._chatTimer then
slot0._chatTimer:Stop()
slot0._chatTimer = nil
end
slot0._chatTimer = Timer.New(function ()
uv0:displayShipWord(uv1, "main")
uv0._chatTimer = nil
end, 10, 1)
slot0._chatTimer:Start()
end
function slot0.recycleSpineChar(slot0)
if slot0.prefabs and slot0.models then
for slot4, slot5 in ipairs(slot0.prefabs) do
slot7 = slot0.models[slot4]
if slot0.prefabs[slot4] and slot7 then
PoolMgr.GetInstance():ReturnSpineChar(slot6, slot7)
end
end
end
slot0.prefabs = nil
slot0.models = nil
end
function slot0.getStudents(slot0)
slot3 = getProxy(TaskProxy)
_.each(getProxy(ActivityProxy):getActivitiesByType(ActivityConst.ACTIVITY_TYPE_TASK_LIST), function (slot0)
if not slot0:isEnd() then
slot3 = _.flatten(slot0:getConfig("config_data"))
slot4, slot5 = nil
if type(slot0:getConfig("config_client")) == "table" then
for slot9, slot10 in ipairs(slot1) do
uv0[slot10.id] = Ship.New(slot10)
if slot9 == 1 then
uv0[slot10.id].withShipFace = true
slot11 = {
type = slot10.type,
param = slot10.param,
showTips = slot12 and not slot13 or slot13 and slot13:isFinish() and not slot13:isReceive(),
acceptTaskId = slot12,
currentTask = slot13
}
if slot10.type then
-- Nothing
end
slot12, slot13 = getActivityTask(slot0, true)
uv1[slot10.id] = slot11
slot4 = slot11.acceptTaskId
slot5 = slot11.currentTask
end
if slot10.tasks then
uv0[slot10.id].hide = true
for slot16, slot17 in ipairs(slot11) do
if slot17 == (slot5 and table.indexof(slot3, slot5.id) or table.indexof(slot3, slot4)) then
uv0[slot10.id].hide = false
break
end
end
end
end
end
end
end)
return getProxy(NavalAcademyProxy):fillStudens({}), {}
end
function slot0.updateStudents(slot0)
slot1, slot2 = slot0:getStudents()
_.each(_.keys(slot0.academyStudents), function (slot0)
if uv0[slot0] then
uv2.academyStudents[slot0]:updateStudent(slot1, uv1[slot0])
else
slot3:detach()
end
end)
for slot6, slot7 in pairs(slot1) do
if not slot0.academyStudents[slot6] then
slot9 = NavalAcademyStudent.New(cloneTplTo(slot0._shipTpl, slot0._map).gameObject)
slot9:attach()
slot9:setPathFinder(slot0.academyGraphPath)
slot9:setCallBack(function (slot0)
uv0:onStateChange(uv1, slot0)
end, function (slot0, slot1)
slot2, slot3 = uv0:getStudents()
uv0:onTask(uv2, slot3[uv1])
end)
slot9:updateStudent(slot7, slot2[slot6])
slot0.academyStudents[slot6] = slot9
end
end
slot0:sortStudents()
end
function slot0.updateTrophyReminder(slot0)
setActive(slot0._fountainReminder, slot0._unclaimTrophyCount > 0)
end
function slot0.onStateChange(slot0, slot1, slot2)
if slot0.sortTimer then
slot0.sortTimer:Stop()
slot0.sortTimer = nil
end
if slot2 == NavalAcademyStudent.ShipState.Walk then
slot0.sortTimer = Timer.New(function ()
uv0:sortStudents()
end, 0.2, -1)
slot0.sortTimer:Start()
end
end
function slot0.sortStudents(slot0)
slot1 = {
slot0._fountain
}
for slot5, slot6 in pairs(slot0.academyStudents) do
table.insert(slot1, slot6._tf)
end
table.sort(slot1, function (slot0, slot1)
return slot0.anchoredPosition.y < slot1.anchoredPosition.y
end)
for slot6, slot7 in ipairs(slot1) do
slot7:SetSiblingIndex(6)
end
end
function slot0.onTask(slot0, slot1, slot2)
slot4 = getProxy(ActivityProxy)
if _.detect(slot4:getActivitiesByType(ActivityConst.ACTIVITY_TYPE_TASK_LIST), function (slot0)
return slot0:getTaskShip() and slot1.groupId == uv0.groupId
end) and not slot6:isEnd() then
if slot6.id == ActivityConst.JYHZ_ACTIVITY_ID and slot2.acceptTaskId then
slot7 = getProxy(TaskProxy):getAcademyTask(slot1.groupId)
if slot4:getActivityByType(ActivityConst.ACTIVITY_TYPE_ZPROJECT) and _.detect(slot8:getConfig("config_data"), function (slot0)
return _.any(pg.chapter_template[slot0].npc_data, function (slot0)
return pg.npc_squad_template[slot0].task_id == uv0
end)
end) and getProxy(ChapterProxy):getChapterById(slot10).active then
pg.TipsMgr.GetInstance():ShowTips(i18n("task_target_chapter_in_progress"))
return
end
end
if slot2.type then
if slot2.type == 1 then
Application.OpenURL(slot2.param)
elseif slot2.type == 2 then
slot0:emit(NavalAcademyMediator.GO_SCENE, slot2.param)
elseif slot2.type == 3 then
slot0:emit(NavalAcademyMediator.OPEN_ACTIVITY_PANEL, tonumber(slot2.param))
elseif slot2.type == 4 then
slot0:emit(NavalAcademyMediator.OPEN_ACTIVITY_SHOP)
elseif slot2.type == 5 then
slot0:emit(NavalAcademyMediator.OPEN_SCROLL, tonumber(slot2.param))
end
elseif not slot2.currentTask and slot2.acceptTaskId then
if getProxy(PlayerProxy):getRawData().level < pg.task_data_template[slot2.acceptTaskId].level then
pg.TipsMgr.GetInstance():ShowTips(i18n("task_level_notenough", slot9.level))
return
end
slot0:emit(NavalAcademyMediator.ACTIVITY_OP, {
cmd = 1,
activity_id = slot6.id,
arg1 = slot2.acceptTaskId
})
elseif slot2.currentTask then
if not slot2.currentTask:isFinish() and slot2.currentTask:getConfig("sub_type") == 29 then
slot0:emit(NavalAcademyMediator.TASK_GO, {
taskVO = slot2.currentTask
})
elseif not slot2.currentTask:isReceive() then
slot0:emit(NavalAcademyMediator.GO_TASK_SCENE, {
page = "activity"
})
end
else
pg.TipsMgr.GetInstance():ShowTips(i18n("main_navalAcademyScene_work_done"))
end
end
end
function slot0.clearStudents(slot0)
if slot0.sortTimer then
slot0.sortTimer:Stop()
slot0.sortTimer = nil
end
for slot4, slot5 in pairs(slot0.academyStudents) do
slot5:detach()
Destroy(slot5._go)
end
slot0.academyStudents = {}
end
function slot0.onBackPressed(slot0)
triggerButton(slot0._backBtn)
end
function slot0.willExit(slot0)
if slot0.bulinTip then
slot0.bulinTip:Destroy()
slot0.bulinTip = nil
end
slot4 = slot0._tf
pg.UIMgr.GetInstance():UnblurPanel(slot0._blurLayer, slot4)
for slot4, slot5 in ipairs(slot0._panelTimer) do
pg.TimeMgr.GetInstance():RemoveTimer(slot5)
end
for slot4, slot5 in pairs(slot0._buildingTimers) do
pg.TimeMgr.GetInstance():RemoveTimer(slot5)
end
if slot0._chatTimer then
slot0._chatTimer:Stop()
slot0._chatTimer = nil
end
if not IsNil(slot0._resourceLayer) then
setActive(slot0._resourceLayer, false)
end
if slot0._resPanel then
slot0._resPanel:exit()
slot0._resPanel = nil
end
if slot0.tweens then
cancelTweens(slot0.tweens)
end
slot0:clearStudents()
end
function slot0.activeSakura(slot0, slot1)
if slot0.sakura then
setActive(slot0.sakura, slot1)
end
if slot0.wave then
setActive(slot0.wave, slot1)
end
end
return slot0
| 0 | 0.630817 | 1 | 0.630817 | game-dev | MEDIA | 0.950673 | game-dev | 0.838438 | 1 | 0.838438 |
gta-chaos-mod/ChaosModV | 1,761 | ChaosMod/Effects/db/Player/PlayerDrunk.cpp | #include <stdafx.h>
#include "Effects/Register/RegisterEffect.h"
static void OnStop()
{
Ped playerPed = PLAYER_PED_ID();
SET_PED_IS_DRUNK(playerPed, false);
RESET_PED_MOVEMENT_CLIPSET(playerPed, .0f);
REMOVE_CLIP_SET("MOVE_M@DRUNK@VERYDRUNK");
STOP_GAMEPLAY_CAM_SHAKING(true);
_0x487A82C650EB7799(.0f);
_0x0225778816FDC28C(.0f);
}
static void OnTick()
{
if (!IS_GAMEPLAY_CAM_SHAKING())
SHAKE_GAMEPLAY_CAM("DRUNK_SHAKE", 2.f);
Ped playerPed = PLAYER_PED_ID();
SET_PED_IS_DRUNK(playerPed, true);
REQUEST_CLIP_SET("MOVE_M@DRUNK@VERYDRUNK");
SET_PED_MOVEMENT_CLIPSET(playerPed, "MOVE_M@DRUNK@VERYDRUNK", 1.f);
SET_AUDIO_SPECIAL_EFFECT_MODE(2);
// No idea what these do, but game scripts also call these so just blindly follow
_0x487A82C650EB7799(1.f);
_0x0225778816FDC28C(1.f);
// Random right / left steering
if (IS_PED_IN_ANY_VEHICLE(playerPed, false))
{
Vehicle playerVeh = GET_VEHICLE_PED_IS_IN(playerPed, false);
if (GET_PED_IN_VEHICLE_SEAT(playerVeh, -1, 0) != playerPed)
return;
static float timeUntilSteer = 0.f;
static bool enableDrunkSteering = false;
static float steering;
if (enableDrunkSteering)
SET_VEHICLE_STEER_BIAS(playerVeh, steering);
if ((timeUntilSteer -= GET_FRAME_TIME()) < 0.f)
{
if (enableDrunkSteering)
{
// Give player back control
timeUntilSteer = g_RandomNoDeterm.GetRandomFloat(0.f, 3.f);
}
else
{
// Take control from player
steering = GET_RANDOM_FLOAT_IN_RANGE(-.5f, .5f);
timeUntilSteer = g_RandomNoDeterm.GetRandomFloat(0.f, .2f);
}
enableDrunkSteering = !enableDrunkSteering;
}
}
}
// clang-format off
REGISTER_EFFECT(nullptr, OnStop, OnTick,
{
.Name = "Drunk",
.Id = "player_drunk",
.IsTimed = true
}
); | 0 | 0.814888 | 1 | 0.814888 | game-dev | MEDIA | 0.93877 | game-dev | 0.89692 | 1 | 0.89692 |
katalash/DSMapStudio | 25,615 | StudioCore/MsbEditor/SceneTree.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
using Veldrid;
using System.Windows.Forms;
namespace StudioCore.MsbEditor
{
public struct DragDropPayload
{
public Entity Entity;
}
public struct DragDropPayloadReference
{
public int Index;
}
public interface SceneTreeEventHandler
{
public void OnEntityContextMenu(Entity ent);
}
public class SceneTree : IActionEventHandler
{
private Universe _universe;
private ActionManager _editorActionManager;
private Gui.Viewport _viewport;
private AssetLocator _assetLocator;
private Selection _selection;
private string _id;
private SceneTreeEventHandler _handler;
private string _chaliceMapID = "m29_";
private bool _chaliceLoadError = false;
private bool _GCNeedsCollection = false;
private Dictionary<string, Dictionary<MapEntity.MapEntityType, Dictionary<Type, List<MapEntity>>>> _cachedTypeView = null;
private bool _initiatedDragDrop = false;
private bool _pendingDragDrop = false;
private Dictionary<int, DragDropPayload> _dragDropPayloads = new Dictionary<int, DragDropPayload>();
private int _dragDropPayloadCounter = 0;
private List<Entity> _dragDropSources = new List<Entity>();
private List<int> _dragDropDests = new List<int>();
private List<Entity> _dragDropDestObjects = new List<Entity>();
// Keep track of open tree nodes for selection management purposes
private HashSet<Entity> _treeOpenEntities = new HashSet<Entity>();
private Entity _pendingClick = null;
private bool _setNextFocus = false;
public enum ViewMode
{
Hierarchy,
Flat,
ObjectType,
}
private string[] _viewModeStrings =
{
"Hierarchy View",
"Flat View",
"Type View",
};
private ViewMode _viewMode = ViewMode.Flat;
public enum Configuration
{
MapEditor,
ModelEditor
}
private Configuration _configuration;
public SceneTree(Configuration configuration, SceneTreeEventHandler handler, string id, Universe universe, Selection sel, ActionManager aman, Gui.Viewport vp, AssetLocator al)
{
_handler = handler;
_id = id;
_universe = universe;
_selection = sel;
_editorActionManager = aman;
_viewport = vp;
_assetLocator = al;
_configuration = configuration;
if (_configuration == Configuration.ModelEditor)
{
_viewMode = ViewMode.Hierarchy;
}
}
private void RebuildTypeViewCache(Map map)
{
if (_cachedTypeView == null)
{
_cachedTypeView = new Dictionary<string, Dictionary<MapEntity.MapEntityType, Dictionary<Type, List<MapEntity>>>>();
}
var mapcache = new Dictionary<MapEntity.MapEntityType, Dictionary<Type, List<MapEntity>>>();
mapcache.Add(MapEntity.MapEntityType.Part, new Dictionary<Type, List<MapEntity>>());
mapcache.Add(MapEntity.MapEntityType.Region, new Dictionary<Type, List<MapEntity>>());
mapcache.Add(MapEntity.MapEntityType.Event, new Dictionary<Type, List<MapEntity>>());
if (_assetLocator.Type == GameType.DarkSoulsIISOTFS)
{
mapcache.Add(MapEntity.MapEntityType.DS2Event, new Dictionary<Type, List<MapEntity>>());
mapcache.Add(MapEntity.MapEntityType.DS2EventLocation, new Dictionary<Type, List<MapEntity>>());
mapcache.Add(MapEntity.MapEntityType.DS2Generator, new Dictionary<Type, List<MapEntity>>());
mapcache.Add(MapEntity.MapEntityType.DS2GeneratorRegist, new Dictionary<Type, List<MapEntity>>());
}
foreach (var obj in map.Objects)
{
if (obj is MapEntity e && mapcache.ContainsKey(e.Type))
{
var typ = e.WrappedObject.GetType();
if (!mapcache[e.Type].ContainsKey(typ))
{
mapcache[e.Type].Add(typ, new List<MapEntity>());
}
mapcache[e.Type][typ].Add(e);
}
}
if (!_cachedTypeView.ContainsKey(map.Name))
{
_cachedTypeView.Add(map.Name, mapcache);
}
else
{
_cachedTypeView[map.Name] = mapcache;
}
}
private void ChaliceDungeonImportButton()
{
ImGui.Selectable($@" {ForkAwesome.PlusCircle} Load Chalice Dungeon...", false);
if (ImGui.BeginPopupContextItem("chalice", 0))
{
ImGui.AlignTextToFramePadding();
ImGui.Text("Chalice ID (m29_xx_xx_xx): ");
ImGui.SameLine();
var pname = _chaliceMapID;
ImGui.SetNextItemWidth(100);
if (_chaliceLoadError)
{
ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.8f, 0.2f, 0.2f, 1.0f));
}
if (ImGui.InputText("##chalicename", ref pname, 12))
{
_chaliceMapID = pname;
}
if (_chaliceLoadError)
{
ImGui.PopStyleColor();
}
ImGui.SameLine();
if (ImGui.Button("Load"))
{
if (!_universe.LoadMap(_chaliceMapID))
{
_chaliceLoadError = true;
}
else
{
ImGui.CloseCurrentPopup();
_chaliceLoadError = false;
_chaliceMapID = "m29_";
}
}
ImGui.EndPopup();
}
}
unsafe private void MapObjectSelectable(Entity e, bool visicon, bool hierarchial=false)
{
// Main selectable
if (e is MapEntity me)
{
ImGui.PushID(me.Type.ToString() + e.Name);
}
else
{
ImGui.PushID(e.Name);
}
bool doSelect = false;
if (_setNextFocus)
{
ImGui.SetItemDefaultFocus();
_setNextFocus = false;
doSelect = true;
}
bool nodeopen = false;
string padding = hierarchial ? " " : " ";
if (hierarchial && e.Children.Count > 0)
{
var treeflags = ImGuiTreeNodeFlags.OpenOnArrow | ImGuiTreeNodeFlags.SpanAvailWidth;
if ( _selection.GetSelection().Contains(e))
{
treeflags |= ImGuiTreeNodeFlags.Selected;
}
nodeopen = ImGui.TreeNodeEx(e.PrettyName, treeflags);
if (ImGui.IsItemHovered() && ImGui.IsMouseDoubleClicked(0))
{
if (e.RenderSceneMesh != null)
{
_viewport.FrameBox(e.RenderSceneMesh.GetBounds());
}
}
}
else
{
if (ImGui.Selectable(padding + e.PrettyName, _selection.GetSelection().Contains(e), ImGuiSelectableFlags.AllowDoubleClick | ImGuiSelectableFlags.AllowItemOverlap))
{
// If double clicked frame the selection in the viewport
if (ImGui.IsMouseDoubleClicked(0))
{
if (e.RenderSceneMesh != null)
{
_viewport.FrameBox(e.RenderSceneMesh.GetBounds());
}
}
}
}
if (ImGui.IsItemClicked(0))
{
_pendingClick = e;
}
if (_pendingClick == e && ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
if (ImGui.IsItemHovered())
{
doSelect = true;
}
_pendingClick = null;
}
if (ImGui.IsItemFocused() && !_selection.IsSelected(e))
{
doSelect = true;
}
if (hierarchial && doSelect)
{
if ((nodeopen && !_treeOpenEntities.Contains(e)) ||
(!nodeopen && _treeOpenEntities.Contains(e)))
{
doSelect = false;
}
if (nodeopen && !_treeOpenEntities.Contains(e))
{
_treeOpenEntities.Add(e);
}
else if (!nodeopen && _treeOpenEntities.Contains(e))
{
_treeOpenEntities.Remove(e);
}
}
if (ImGui.BeginPopupContextItem())
{
_handler.OnEntityContextMenu(e);
ImGui.EndPopup();
}
if (ImGui.BeginDragDropSource())
{
ImGui.Text(e.PrettyName);
// Kinda meme
DragDropPayload p = new DragDropPayload();
p.Entity = e;
_dragDropPayloads.Add(_dragDropPayloadCounter, p);
DragDropPayloadReference r = new DragDropPayloadReference();
r.Index = _dragDropPayloadCounter;
_dragDropPayloadCounter++;
GCHandle handle = GCHandle.Alloc(r, GCHandleType.Pinned);
ImGui.SetDragDropPayload("entity", handle.AddrOfPinnedObject(), (uint)sizeof(DragDropPayloadReference));
ImGui.EndDragDropSource();
handle.Free();
_initiatedDragDrop = true;
}
if (hierarchial && ImGui.BeginDragDropTarget())
{
var payload = ImGui.AcceptDragDropPayload("entity");
if (payload.NativePtr != null)
{
DragDropPayloadReference* h = (DragDropPayloadReference*)payload.Data;
var pload = _dragDropPayloads[h->Index];
_dragDropPayloads.Remove(h->Index);
_dragDropSources.Add(pload.Entity);
_dragDropDestObjects.Add(e);
_dragDropDests.Add(e.Children.Count);
}
ImGui.EndDragDropTarget();
}
// Visibility icon
if (visicon)
{
ImGui.SetItemAllowOverlap();
bool visible = e.EditorVisible;
ImGui.SameLine(ImGui.GetWindowContentRegionWidth() - 18.0f);
ImGui.PushStyleColor(ImGuiCol.Text, visible ? new Vector4(1.0f, 1.0f, 1.0f, 1.0f)
: new Vector4(0.6f, 0.6f, 0.6f, 1.0f));
ImGui.TextWrapped(visible ? ForkAwesome.Eye : ForkAwesome.EyeSlash);
ImGui.PopStyleColor();
if (ImGui.IsItemClicked(0))
{
e.EditorVisible = !e.EditorVisible;
doSelect = false;
}
}
// If the visibility icon wasn't clicked actually perform the selection
if (doSelect)
{
if (InputTracker.GetKey(Key.ControlLeft) || InputTracker.GetKey(Key.ControlRight))
{
_selection.AddSelection(e);
}
else
{
_selection.ClearSelection();
_selection.AddSelection(e);
}
}
ImGui.PopID();
// Invisible item to be a drag drop target between nodes
if (_pendingDragDrop)
{
if (e is MapEntity me2)
{
ImGui.SetItemAllowOverlap();
ImGui.InvisibleButton(me2.Type.ToString() + e.Name, new Vector2(-1, 3.0f));
}
else
{
ImGui.SetItemAllowOverlap();
ImGui.InvisibleButton(e.Name, new Vector2(-1, 3.0f));
}
if (ImGui.IsItemFocused())
{
_setNextFocus = true;
}
if (ImGui.BeginDragDropTarget())
{
var payload = ImGui.AcceptDragDropPayload("entity");
if (payload.NativePtr != null)
{
DragDropPayloadReference* h = (DragDropPayloadReference*)payload.Data;
var pload = _dragDropPayloads[h->Index];
_dragDropPayloads.Remove(h->Index);
if (hierarchial)
{
_dragDropSources.Add(pload.Entity);
_dragDropDestObjects.Add(e.Parent);
_dragDropDests.Add(e.Parent.ChildIndex(e) + 1);
}
else
{
_dragDropSources.Add(pload.Entity);
_dragDropDests.Add(pload.Entity.Container.Objects.IndexOf(e) + 1);
}
}
ImGui.EndDragDropTarget();
}
}
// If there's children then draw them
if (nodeopen)
{
HierarchyView(e);
ImGui.TreePop();
}
}
private void HierarchyView(Entity entity)
{
foreach (var obj in entity.Children)
{
if (obj is Entity e)
{
MapObjectSelectable(e, true, true);
}
}
}
private void FlatView(Map map)
{
foreach (var obj in map.Objects)
{
if (obj is MapEntity e)
{
MapObjectSelectable(e, true);
}
}
}
private void TypeView(Map map)
{
if (_cachedTypeView == null || !_cachedTypeView.ContainsKey(map.Name))
{
RebuildTypeViewCache(map);
}
foreach (var cats in _cachedTypeView[map.Name].OrderBy(q => q.Key.ToString()))
{
if (cats.Value.Count > 0)
{
if (ImGui.TreeNodeEx(cats.Key.ToString(), ImGuiTreeNodeFlags.OpenOnArrow))
{
foreach (var typ in cats.Value.OrderBy(q => q.Key.Name))
{
if (typ.Value.Count > 0)
{
// Regions don't have multiple types in games before DS3
if (cats.Key == MapEntity.MapEntityType.Region &&
_assetLocator.Type != GameType.DarkSoulsIII && _assetLocator.Type != GameType.Sekiro)
{
foreach (var obj in typ.Value)
{
MapObjectSelectable(obj, true);
}
}
else if (ImGui.TreeNodeEx(typ.Key.Name, ImGuiTreeNodeFlags.OpenOnArrow))
{
foreach (var obj in typ.Value)
{
MapObjectSelectable(obj, true);
}
ImGui.TreePop();
}
}
else
{
ImGui.Text($@" {typ.Key.ToString()}");
}
}
ImGui.TreePop();
}
}
else
{
ImGui.Text($@" {cats.Key.ToString()}");
}
}
}
public void OnGui()
{
ImGui.PushStyleColor(ImGuiCol.ChildBg, new Vector4(0.145f, 0.145f, 0.149f, 1.0f));
if (_configuration == Configuration.MapEditor)
{
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0.0f, 0.0f));
}
else
{
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0.0f, 2.0f));
}
string titleString = _configuration == Configuration.MapEditor ? $@"Map Object List##{_id}" : $@"Model Hierarchy##{_id}";
if (ImGui.Begin(titleString))
{
if (_initiatedDragDrop)
{
_initiatedDragDrop = false;
_pendingDragDrop = true;
}
if (_pendingDragDrop && ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
_pendingDragDrop = false;
}
ImGui.PopStyleVar();
ImGui.SetNextItemWidth(-1);
if (_configuration == Configuration.MapEditor)
{
int mode = (int)_viewMode;
if (ImGui.Combo("##typecombo", ref mode, _viewModeStrings, _viewModeStrings.Length))
{
_viewMode = (ViewMode)mode;
}
}
ImGui.BeginChild("listtree");
Map pendingUnload = null;
foreach (var lm in _universe.LoadedObjectContainers.OrderBy((k) => k.Key))
{
var map = lm.Value;
var mapid = lm.Key;
var treeflags = ImGuiTreeNodeFlags.OpenOnArrow | ImGuiTreeNodeFlags.SpanAvailWidth;
if (map != null && _selection.GetSelection().Contains(map.RootObject))
{
treeflags |= ImGuiTreeNodeFlags.Selected;
}
bool nodeopen = false;
string unsaved = (map != null && map.HasUnsavedChanges) ? "*" : "";
if (map != null)
{
nodeopen = ImGui.TreeNodeEx($@"{ForkAwesome.Cube} {mapid}", treeflags, $@"{ForkAwesome.Cube} {mapid}{unsaved}");
}
else
{
ImGui.Selectable($@" {ForkAwesome.Cube} {mapid}", false);
}
// Right click context menu
if (ImGui.BeginPopupContextItem($@"mapcontext_{mapid}"))
{
if (map == null)
{
if (ImGui.Selectable("Load Map"))
{
_universe.LoadMap(mapid);
}
}
else if (map is Map m)
{
if (ImGui.Selectable("Save Map"))
{
try
{
_universe.SaveMap(m);
}
catch (SavingFailedException e)
{
System.Windows.Forms.MessageBox.Show(e.Wrapped.Message, e.Message,
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.None);
}
}
if (ImGui.Selectable("Unload Map"))
{
_selection.ClearSelection();
_editorActionManager.Clear();
pendingUnload = m;
}
}
ImGui.EndPopup();
}
if (ImGui.IsItemClicked() && map != null)
{
_pendingClick = map.RootObject;
}
if (map != null && _pendingClick == map.RootObject && ImGui.IsMouseReleased(ImGuiMouseButton.Left))
{
if (ImGui.IsItemHovered())
{
// Only select if a node is not currently being opened/closed
if ((nodeopen && _treeOpenEntities.Contains(map.RootObject)) ||
(!nodeopen && !_treeOpenEntities.Contains(map.RootObject)))
{
if (InputTracker.GetKey(Key.ShiftLeft) || InputTracker.GetKey(Key.ShiftRight))
{
_selection.AddSelection(map.RootObject);
}
else
{
_selection.ClearSelection();
_selection.AddSelection(map.RootObject);
}
}
// Update the open/closed state
if (nodeopen && !_treeOpenEntities.Contains(map.RootObject))
{
_treeOpenEntities.Add(map.RootObject);
}
else if (!nodeopen && _treeOpenEntities.Contains(map.RootObject))
{
_treeOpenEntities.Remove(map.RootObject);
}
}
_pendingClick = null;
}
if (nodeopen)
{
if (_pendingDragDrop)
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(8.0f, 0.0f));
}
else
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(8.0f, 3.0f));
}
if (_viewMode == ViewMode.Hierarchy)
{
HierarchyView(map.RootObject);
}
else if (_viewMode == ViewMode.Flat)
{
FlatView((Map)map);
}
else if (_viewMode == ViewMode.ObjectType)
{
TypeView((Map)map);
}
ImGui.PopStyleVar();
ImGui.TreePop();
}
}
if (_assetLocator.Type == GameType.Bloodborne && _configuration == Configuration.MapEditor)
{
ChaliceDungeonImportButton();
}
ImGui.EndChild();
if (_dragDropSources.Count > 0)
{
if (_dragDropDestObjects.Count > 0)
{
var action = new ChangeEntityHierarchyAction(_universe, _dragDropSources, _dragDropDestObjects, _dragDropDests, false);
_editorActionManager.ExecuteAction(action);
_dragDropSources.Clear();
_dragDropDests.Clear();
_dragDropDestObjects.Clear();
}
else
{
var action = new ReorderContainerObjectsAction(_universe, _dragDropSources, _dragDropDests, false);
_editorActionManager.ExecuteAction(action);
_dragDropSources.Clear();
_dragDropDests.Clear();
}
}
if (pendingUnload != null)
{
_universe.UnloadMap(pendingUnload);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
_GCNeedsCollection = true;
Resource.ResourceManager.UnloadUnusedResources();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
else
{
ImGui.PopStyleVar();
}
ImGui.End();
ImGui.PopStyleColor();
}
public void OnActionEvent(ActionEvent evt)
{
if (evt.HasFlag(ActionEvent.ObjectAddedRemoved))
{
_cachedTypeView = null;
}
}
}
}
| 0 | 0.972681 | 1 | 0.972681 | game-dev | MEDIA | 0.586694 | game-dev,desktop-app | 0.975345 | 1 | 0.975345 |
sghiassy/Code-Reading-Book | 11,519 | argouml/org/argouml/uml/ui/foundation/core/PropPanelGeneralization.java | // Copyright (c) 1996-99 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import org.argouml.uml.ui.*;
import ru.novosoft.uml.foundation.core.*;
import ru.novosoft.uml.foundation.data_types.*;
import ru.novosoft.uml.model_management.*;
import ru.novosoft.uml.foundation.extension_mechanisms.*;
import ru.novosoft.uml.behavior.use_cases.*;
import ru.novosoft.uml.behavior.common_behavior.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class PropPanelGeneralization extends PropPanelModelElement {
private PropPanelButton _newButton;
public PropPanelGeneralization() {
super("Generalization",_generalizationIcon,2);
Class mclass = MGeneralization.class;
Class[] namesToWatch = {MStereotype.class,MNamespace.class,MClassifier.class };
setNameEventListening(namesToWatch);
addCaption("Name:",1,0,0);
addField(nameField,1,0,0);
addCaption("Stereotype:",2,0,0);
addField(new UMLComboBoxNavigator(this,"NavStereo",stereotypeBox),2,0,0);
addCaption("Discriminator:",3,0,0);
addField(new UMLTextField(this,new UMLTextProperty(mclass,"discriminator","getDiscriminator","setDiscriminator")),3,0,0);
addCaption("Namespace:",4,0,1);
addField(namespaceScroll,4,0,0);
addCaption("Parent:",0,1,0);
UMLModelElementListModel parentModel = new UMLReflectionListModel(this,"parent",true,"getParentElement",null,null,null);
parentModel.setUpperBound(1);
addLinkField(new JScrollPane(new UMLList(parentModel,true),JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),0,1,0);
addCaption("Child:",1,1,0);
UMLModelElementListModel childModel = new UMLReflectionListModel(this,"child",true,"getChild",null,null,null);
childModel.setUpperBound(1);
addLinkField(new JScrollPane(new UMLList(childModel,true),JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),1,1,0);
addCaption("Powertype:",2,1,1);
UMLComboBoxModel powerModel = new UMLComboBoxModel(this,"isAcceptiblePowertype",
"powertype","getPowertype","setPowertype",false,MClassifier.class,true);
addField(new UMLComboBoxNavigator(this,"NavClass",new UMLComboBox(powerModel)),2,1,0);
new PropPanelButton(this,buttonPanel,_navUpIcon,localize("Go up"),"navigateUp",null);
new PropPanelButton(this,buttonPanel,_navBackIcon,localize("Go back"),"navigateBackAction","isNavigateBackEnabled");
new PropPanelButton(this,buttonPanel,_navForwardIcon,localize("Go forward"),"navigateForwardAction","isNavigateForwardEnabled");
new PropPanelButton(this,buttonPanel,_deleteIcon,localize("Delete generalization"),"removeElement",null);
}
private void updateButton() {
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralization gen = (MGeneralization) target;
MGeneralizableElement parent = gen.getParent();
MGeneralizableElement child = gen.getChild();
//
// if one and only one of child and parent are set
//
if(parent != null ^ child != null) {
if(parent == null) parent = child;
if(parent instanceof MClass) {
_newButton.setIcon(_classIcon);
_newButton.setToolTipText("Add new class");
}
else {
if(parent instanceof MInterface) {
_newButton.setIcon(_interfaceIcon);
_newButton.setToolTipText("Add new interface");
}
else {
if(parent instanceof MPackage) {
_newButton.setIcon(_packageIcon);
_newButton.setToolTipText("Add new package");
}
}
}
_newButton.setEnabled(true);
}
else {
_newButton.setEnabled(false);
}
}
}
public MGeneralizableElement getParentElement() {
MGeneralizableElement parent = null;
Object target = getTarget();
if(target instanceof MGeneralization) {
parent = ((MGeneralization) target).getParent();
}
return parent;
}
public void setParentElement(MGeneralizableElement parent) {
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralization gen = (MGeneralization) target;
MGeneralizableElement child = gen.getChild();
MGeneralizableElement oldParent = gen.getParent();
//
// can't do immediate circular generalization
//
if(parent != child && parent != oldParent) {
gen.setParent(parent);
}
else {
//
// force a refresh of the panel
// refresh();
}
}
}
public MGeneralizableElement getChild() {
MGeneralizableElement child = null;
Object target = getTarget();
if(target instanceof MGeneralization) {
child = ((MGeneralization) target).getChild();
}
return child;
}
public void setChild(MGeneralizableElement child) {
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralization gen = (MGeneralization) target;
MGeneralizableElement parent = gen.getParent();
MGeneralizableElement oldChild = gen.getChild();
if(child != parent && child != oldChild) {
gen.setChild(child);
}
else {
// refresh();
}
}
}
public MClassifier getPowertype() {
MClassifier ptype = null;
Object target = getTarget();
if(target instanceof MGeneralization) {
ptype = ((MGeneralization) target).getPowertype();
}
return ptype;
}
public void setPowertype(MClassifier ptype) {
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralization gen = (MGeneralization) target;
MClassifier oldPtype = gen.getPowertype();
if(ptype != oldPtype) {
gen.setPowertype(ptype);
}
}
}
public void newModelElement() {
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralization gen = (MGeneralization) target;
MGeneralizableElement parent = gen.getParent();
MGeneralizableElement child = gen.getChild();
if(parent != null ^ child != null) {
MGeneralizableElement known = parent;
if(known == null) known = child;
MNamespace ns = known.getNamespace();
if(ns != null) {
try {
MGeneralizableElement newElement = (MGeneralizableElement)
known.getClass().getConstructor(new Class[] {}).newInstance(new Object[] {});
ns.addOwnedElement(newElement);
if(parent == null) {
gen.setParent(newElement);
}
else {
gen.setChild(newElement);
}
_newButton.setEnabled(false);
navigateTo(newElement);
}
catch(Exception e) {
System.out.println(e.toString() + " in PropPanelGeneralization.newElement");
}
}
}
}
}
public void navigateUp() {
Object target = getTarget();
if(target instanceof MModelElement) {
MNamespace ns = ((MModelElement) target).getNamespace();
if(ns != null) {
navigateTo(ns);
}
}
}
private boolean isAcceptible(MGeneralizableElement fixed,
MModelElement candidate) {
boolean isCompatible = true;
Class[] keys = { MClass.class, MDataType.class,
MInterface.class, MActor.class, MSignal.class };
int i;
for(i = 0; i < keys.length; i++) {
if(keys[i].isInstance(fixed)) {
isCompatible = keys[i].isInstance(candidate);
break;
}
}
return isCompatible;
}
public boolean isAcceptibleParent(MModelElement element) {
boolean isAcceptible = false;
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralizableElement child = ((MGeneralization) target).getChild();
if(child == null) {
isAcceptible = element instanceof MGeneralizableElement;
}
else {
isAcceptible = isAcceptible(child,element);
}
}
return isAcceptible;
}
public boolean isAcceptibleChild(MModelElement element) {
boolean isAcceptible = false;
System.out.println("PropPanelGeneralization: testing isAcceptibleChild");
Object target = getTarget();
if(target instanceof MGeneralization) {
MGeneralizableElement parent = ((MGeneralization) target).getParent();
if(parent == null) {
isAcceptible = element instanceof MGeneralizableElement;
}
else {
isAcceptible = isAcceptible(parent,element);
}
}
System.out.println("isAcceptible: "+isAcceptible);
return isAcceptible;
}
public boolean isAcceptiblePowertype(MModelElement element) {
return element instanceof MClassifier;
}
protected boolean isAcceptibleBaseMetaClass(String baseClass) {
return baseClass.equals("Generalization");
}
} /* end class PropPanelGeneralization */
| 0 | 0.898401 | 1 | 0.898401 | game-dev | MEDIA | 0.621655 | game-dev | 0.96583 | 1 | 0.96583 |
RSDKModding/Sonic-Mania-Decompilation | 2,082 | SonicMania/Objects/Global/Animals.h | #ifndef OBJ_ANIMALS_H
#define OBJ_ANIMALS_H
#include "Game.h"
typedef enum {
ANIMAL_FLICKY,
ANIMAL_RICKY,
ANIMAL_POCKY,
ANIMAL_PECKY,
ANIMAL_PICKY,
ANIMAL_CUCKY,
ANIMAL_ROCKY,
ANIMAL_BECKY,
ANIMAL_LOCKY,
ANIMAL_TOCKY,
ANIMAL_WOCKY,
ANIMAL_MICKY,
} AnimalTypes;
typedef enum {
ANIMAL_BEHAVE_FREE,
ANIMAL_BEHAVE_FOLLOW,
ANIMAL_BEHAVE_FIXED,
} AnimalBehaviours;
// Object Class
struct ObjectAnimals {
RSDK_OBJECT
TABLE(int32 hitboxes[12], { 0x70000, 0x70000, 0xC0000, 0xA0000, 0x80000, 0x80000, 0x80000, 0x80000, 0x70000, 0x50000, 0x70000, 0x60000 });
TABLE(int32 gravityStrength[12], { 0x1800, 0x3800, 0x3800, 0x3800, 0x3800, 0x3800, 0x3800, 0x3800, 0x1800, 0x3800, 0x3800, 0x3800 });
TABLE(int32 yVelocity[12],
{ -0x40000, -0x38000, -0x40000, -0x30000, -0x30000, -0x30000, -0x18000, -0x30000, -0x30000, -0x20000, -0x30000, -0x38000 });
TABLE(int32 xVelocity[12],
{ -0x30000, -0x28000, -0x20000, -0x18000, -0x1C000, -0x20000, -0x14000, -0x20000, -0x28000, -0x14000, -0x2C000, -0x20000 });
uint16 aniFrames;
int32 animalTypes[2];
bool32 hasPlatform;
bool32 hasBridge;
};
// Entity Class
struct EntityAnimals {
RSDK_ENTITY
StateMachine(state);
int32 timer;
AnimalTypes type;
AnimalBehaviours behaviour;
Animator animator;
Hitbox hitboxAnimal;
};
// Object Struct
extern ObjectAnimals *Animals;
// Standard Entity Events
void Animals_Update(void);
void Animals_LateUpdate(void);
void Animals_StaticUpdate(void);
void Animals_Draw(void);
void Animals_Create(void *data);
void Animals_StageLoad(void);
#if GAME_INCLUDE_EDITOR
void Animals_EditorDraw(void);
void Animals_EditorLoad(void);
#endif
void Animals_Serialize(void);
// Extra Entity Functions
void Animals_CheckDirection(void);
bool32 Animals_CheckPlatformCollision(void *platform);
bool32 Animals_CheckGroundCollision(void);
void Animals_State_Fall(void);
void Animals_State_Bounce(void);
void Animals_State_Fly(void);
void Animals_State_Placed(void);
#endif //! OBJ_ANIMALS_H
| 0 | 0.839297 | 1 | 0.839297 | game-dev | MEDIA | 0.954986 | game-dev | 0.557595 | 1 | 0.557595 |
Samuels-Development/sd_lib | 4,092 | modules/Target/client.lua | --- @class SD.Target
SD.Target = {}
--- Initialize the target system by checking available resources and setting the target module.
local Initialize = function()
local resources = {"qb-target", "qtarget", "ox_target"} -- List of potential target resources.
for _, resource in ipairs(resources) do
if GetResourceState(resource) == 'started' then
if resource == 'ox_target' then
target = 'qtarget'
else
target = resource
end
break -- Break the loop once the first active target resource is found.
end
end
-- Optionally handle the case where none of the resources are started.
if not target then
error("No target resource found or started.")
return false -- Indicate unsuccessful initialization.
end
return true -- Indicate successful initialization.
end
Initialize() -- Initialize the target system
--- Add a box zone.
---@param identifier string The identifier for the zone.
---@param coords table Coordinates where the zone is centered.
---@param width number The width of the box zone.
---@param length number The length of the box zone.
---@param data table Additional data such as heading, options, and distance.
---@param debugPoly boolean Whether to debug the polygon.
---@return handler The handle to the created zone.
SD.Target.AddBoxZone = function(identifier, coords, width, length, data, debugPoly)
local handler = exports[target]:AddBoxZone(identifier, coords, width, length, {
name = identifier,
heading = data.heading,
debugPoly = debugPoly,
minZ = coords.z - 1.2,
maxZ = coords.z + 1.2,
}, {
options = data.options,
distance = data.distance,
})
return handler
end
--- Add a circle zone.
---@param identifier string The identifier for the zone.
---@param coords table Coordinates where the zone is centered.
---@param radius number The radius of the circle zone.
---@param data table Additional data such as options and distance.
---@param debugPoly boolean Whether to debug the polygon.
---@return handler The handle to the created zone.
SD.Target.AddCircleZone = function(identifier, coords, radius, data, debugPoly)
local handler = exports[target]:AddCircleZone(identifier, coords, radius, {
name = identifier,
useZ = true,
debugPoly = debugPoly,
}, {
options = data.options,
distance = data.distance,
})
return handler
end
--- Add a target entity.
---@param entityId number The entity ID to target.
---@param data table Additional data such as options and distance.
SD.Target.AddTargetEntity = function(entityId, data)
exports[target]:AddTargetEntity(entityId, {
options = data.options,
distance = data.distance,
})
end
--- Add a target model.
---@param models table|array Models to target.
---@param data table Additional data such as options and distance.
SD.Target.AddTargetModel = function(models, data)
exports[target]:AddTargetModel(models, {
options = data.options,
distance = data.distance,
})
end
--- Remove a target entity.
---@param entity number The entity to remove from targeting.
SD.Target.RemoveTargetEntity = function(entity)
exports[target]:RemoveTargetEntity(entity)
end
--- Remove a zone.
---@param identifier string The identifier for the zone to remove.
SD.Target.RemoveZone = function(identifier)
exports[target]:RemoveZone(identifier)
end
--- Add a global ped target.
---@param identifier string The identifier for the global ped.
---@param data table Additional data such as options and distance.
SD.Target.AddGlobalPed = function(identifier, data)
exports[target]:AddGlobalPed({
name = identifier,
options = data.options,
distance = data.distance,
})
end
--- Remove a global ped target.
---@param identifier string The identifier for the global ped to remove.
SD.Target.RemoveGlobalPed = function(identifier)
exports[target]:RemoveGlobalPed(identifier)
end
return SD.Target | 0 | 0.762416 | 1 | 0.762416 | game-dev | MEDIA | 0.626579 | game-dev | 0.863065 | 1 | 0.863065 |
chai3d/chai3d | 4,980 | modules/Bullet/externals/bullet/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_DEFAULT_COLLISION_CONFIGURATION
#define BT_DEFAULT_COLLISION_CONFIGURATION
#include "btCollisionConfiguration.h"
class btVoronoiSimplexSolver;
class btConvexPenetrationDepthSolver;
struct btDefaultCollisionConstructionInfo
{
btPoolAllocator* m_persistentManifoldPool;
btPoolAllocator* m_collisionAlgorithmPool;
int m_defaultMaxPersistentManifoldPoolSize;
int m_defaultMaxCollisionAlgorithmPoolSize;
int m_customCollisionAlgorithmMaxElementSize;
int m_useEpaPenetrationAlgorithm;
btDefaultCollisionConstructionInfo()
:m_persistentManifoldPool(0),
m_collisionAlgorithmPool(0),
m_defaultMaxPersistentManifoldPoolSize(4096),
m_defaultMaxCollisionAlgorithmPoolSize(4096),
m_customCollisionAlgorithmMaxElementSize(0),
m_useEpaPenetrationAlgorithm(true)
{
}
};
///btCollisionConfiguration allows to configure Bullet collision detection
///stack allocator, pool memory allocators
///@todo: describe the meaning
class btDefaultCollisionConfiguration : public btCollisionConfiguration
{
protected:
int m_persistentManifoldPoolSize;
btPoolAllocator* m_persistentManifoldPool;
bool m_ownsPersistentManifoldPool;
btPoolAllocator* m_collisionAlgorithmPool;
bool m_ownsCollisionAlgorithmPool;
//default simplex/penetration depth solvers
btVoronoiSimplexSolver* m_simplexSolver;
btConvexPenetrationDepthSolver* m_pdSolver;
//default CreationFunctions, filling the m_doubleDispatch table
btCollisionAlgorithmCreateFunc* m_convexConvexCreateFunc;
btCollisionAlgorithmCreateFunc* m_convexConcaveCreateFunc;
btCollisionAlgorithmCreateFunc* m_swappedConvexConcaveCreateFunc;
btCollisionAlgorithmCreateFunc* m_compoundCreateFunc;
btCollisionAlgorithmCreateFunc* m_compoundCompoundCreateFunc;
btCollisionAlgorithmCreateFunc* m_swappedCompoundCreateFunc;
btCollisionAlgorithmCreateFunc* m_emptyCreateFunc;
btCollisionAlgorithmCreateFunc* m_sphereSphereCF;
btCollisionAlgorithmCreateFunc* m_sphereBoxCF;
btCollisionAlgorithmCreateFunc* m_boxSphereCF;
btCollisionAlgorithmCreateFunc* m_boxBoxCF;
btCollisionAlgorithmCreateFunc* m_sphereTriangleCF;
btCollisionAlgorithmCreateFunc* m_triangleSphereCF;
btCollisionAlgorithmCreateFunc* m_planeConvexCF;
btCollisionAlgorithmCreateFunc* m_convexPlaneCF;
public:
btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo = btDefaultCollisionConstructionInfo());
virtual ~btDefaultCollisionConfiguration();
///memory pools
virtual btPoolAllocator* getPersistentManifoldPool()
{
return m_persistentManifoldPool;
}
virtual btPoolAllocator* getCollisionAlgorithmPool()
{
return m_collisionAlgorithmPool;
}
virtual btVoronoiSimplexSolver* getSimplexSolver()
{
return m_simplexSolver;
}
virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1);
///Use this method to allow to generate multiple contact points between at once, between two objects using the generic convex-convex algorithm.
///By default, this feature is disabled for best performance.
///@param numPerturbationIterations controls the number of collision queries. Set it to zero to disable the feature.
///@param minimumPointsPerturbationThreshold is the minimum number of points in the contact cache, above which the feature is disabled
///3 is a good value for both params, if you want to enable the feature. This is because the default contact cache contains a maximum of 4 points, and one collision query at the unperturbed orientation is performed first.
///See Bullet/Demos/CollisionDemo for an example how this feature gathers multiple points.
///@todo we could add a per-object setting of those parameters, for level-of-detail collision detection.
void setConvexConvexMultipointIterations(int numPerturbationIterations=3, int minimumPointsPerturbationThreshold = 3);
void setPlaneConvexMultipointIterations(int numPerturbationIterations=3, int minimumPointsPerturbationThreshold = 3);
};
#endif //BT_DEFAULT_COLLISION_CONFIGURATION
| 0 | 0.677925 | 1 | 0.677925 | game-dev | MEDIA | 0.988813 | game-dev | 0.64761 | 1 | 0.64761 |
mastercomfig/tf2-patches-old | 13,940 | src/hammer/prefab3d.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "stdafx.h"
#include <sys\types.h>
#include <sys\stat.h>
#include "ChunkFile.h"
#include "Prefab3D.h"
#include "Options.h"
#include "History.h"
#include "MapGroup.h"
#include "MapWorld.h"
#include "GlobalFunctions.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefab3D::CPrefab3D()
{
m_pWorld = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefab3D::~CPrefab3D()
{
FreeData();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPrefab3D::FreeData()
{
delete m_pWorld;
m_pWorld = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CMapClass *CPrefab3D::Create(void)
{
if (!IsLoaded() && (Load() == -1))
{
return(NULL);
}
CMapClass *pCopy;
CMapClass *pOriginal;
//
// Check for just one object - if only one, don't group it.
//
if (m_pWorld->GetChildCount() == 1)
{
pOriginal = m_pWorld->GetChildren()->Element(0);
pCopy = pOriginal->Copy(false);
}
else
{
// Original object is world
pOriginal = m_pWorld;
// New object is a new group
pCopy = (CMapClass *)new CMapGroup;
}
//
// Copy children from original (if any).
//
pCopy->CopyChildrenFrom(pOriginal, false);
// HACK: must calculate bounds here due to a hack in CMapClass::CopyChildrenFrom
pCopy->CalcBounds();
return(pCopy);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : point - Where to center the prefab.
// Output : CMapClass
//-----------------------------------------------------------------------------
CMapClass *CPrefab3D::CreateAtPoint(const Vector &point)
{
//
// Create the prefab object. It will either be a single object
// or a group containing the prefab objects.
//
CMapClass *pObject = Create();
if (pObject != NULL)
{
//
// Move the prefab center to match the given point.
//
Vector move = point;
Vector center;
pObject->GetBoundsCenter(center);
for (int i = 0; i < 3; i++)
{
move[i] -= center[i];
}
BOOL bOldLock = Options.SetLockingTextures(TRUE);
pObject->TransMove(move);
Options.SetLockingTextures(bOldLock);
}
return(pObject);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
CMapClass *CPrefab3D::CreateAtPointAroundOrigin( Vector const &point )
{
//
// Create the prefab object. It will either be a single object
// or a group containing the prefab objects.
//
CMapClass *pObject = Create();
if( !pObject )
return NULL;
Vector move = point;
BOOL bOldLock = Options.SetLockingTextures( TRUE );
pObject->TransMove( move );
Options.SetLockingTextures( bOldLock );
return ( pObject );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pBox -
// Output :
//-----------------------------------------------------------------------------
CMapClass *CPrefab3D::CreateInBox(BoundBox *pBox)
{
//
// Create the prefab object. It will either be a single object
// or a group containing the prefab objects.
//
CMapClass *pObject = Create();
if (pObject != NULL)
{
//
// Scale the prefab to match the box bounds.
//
Vector NewSize;
pBox->GetBoundsSize(NewSize);
Vector CurSize;
pObject->GetBoundsSize(CurSize);
Vector scale;
for (int i = 0; i < 3; i++)
{
scale[i] = NewSize[i] / CurSize[i];
}
Vector zero(0, 0, 0);
pObject->TransScale(zero, scale);
//
// Move the prefab center to match the box center.
//
Vector move;
pBox->GetBoundsCenter(move);
Vector center;
pObject->GetBoundsCenter(center);
for (int i = 0; i < 3; i++)
{
move[i] -= center[i];
}
BOOL bOldLock = Options.SetLockingTextures(TRUE);
pObject->TransMove(move);
Options.SetLockingTextures(bOldLock);
}
return(pObject);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPrefab3D::CenterOnZero()
{
Vector ptCenter;
m_pWorld->GetBoundsCenter(ptCenter);
ptCenter[0] = -ptCenter[0];
ptCenter[1] = -ptCenter[1];
ptCenter[2] = -ptCenter[2];
BOOL bOldLock = Options.SetLockingTextures(TRUE);
m_pWorld->TransMove(ptCenter);
Options.SetLockingTextures(bOldLock);
}
//-----------------------------------------------------------------------------
// Purpose: Returns true if the prefab data has been loaded from disk, false if not.
//-----------------------------------------------------------------------------
bool CPrefab3D::IsLoaded(void)
{
return (m_pWorld != NULL);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefabRMF::CPrefabRMF()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefabRMF::~CPrefabRMF()
{
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : file -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::DoLoad(std::fstream& file, DWORD dwFlags)
{
int iRvl;
GetHistory()->Pause();
AddMRU(this);
if(m_pWorld)
delete m_pWorld;
m_pWorld = new CMapWorld( NULL );
// read data
if(dwFlags & lsMAP)
iRvl = m_pWorld->SerializeMAP(file, FALSE);
else
iRvl = m_pWorld->SerializeRMF(file, FALSE);
// error?
if(iRvl == -1)
{
GetHistory()->Resume();
return iRvl;
}
m_pWorld->CalcBounds(TRUE);
GetHistory()->Resume();
return 1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : file -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::DoSave(std::fstream& file, DWORD dwFlags)
{
// save world
if(dwFlags & lsMAP)
return m_pWorld->SerializeMAP(file, TRUE);
return m_pWorld->SerializeRMF(file, TRUE);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::Load(DWORD dwFlags)
{
//
// Get parent library's file handle.
//
CPrefabLibraryRMF *pLibrary = dynamic_cast <CPrefabLibraryRMF *>(CPrefabLibrary::FindID(dwLibID));
if (!pLibrary)
{
return -1;
}
std::fstream &file = pLibrary->m_file;
file.seekg(dwFileOffset);
return(DoLoad(file, dwFlags));
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszFilename -
// bLoadNow -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::Init(LPCTSTR pszFilename, BOOL bLoadNow, DWORD dwFlags)
{
std::fstream file(pszFilename, std::ios::in | std::ios::binary);
// ensure we're named
memset(szName, 0, sizeof szName);
strncpy(szName, pszFilename, sizeof szName - 1);
return Init(file, bLoadNow, dwFlags);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : file -
// bLoadNow -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::Init(std::fstream &file, BOOL bLoadNow, DWORD dwFlags)
{
int iRvl = 1; // start off ok
if(bLoadNow)
{
// do load now
iRvl = DoLoad(file, dwFlags);
}
if(!szName[0])
{
// ensure we're named
strcpy(szName, "Prefab");
}
return iRvl;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszFilename -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::Save(LPCTSTR pszFilename, DWORD dwFlags)
{
std::fstream file(pszFilename, std::ios::out | std::ios::binary);
return Save(file, dwFlags);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : file -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabRMF::Save(std::fstream& file, DWORD dwFlags)
{
if (!IsLoaded() && (Load() == -1))
{
AfxMessageBox("Couldn't Load prefab to Save it.");
return -1;
}
return DoSave(file, dwFlags);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefabVMF::CPrefabVMF()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPrefabVMF::~CPrefabVMF()
{
}
//-----------------------------------------------------------------------------
// Purpose: Returns true if the prefab data has been loaded from disk, false if not.
//-----------------------------------------------------------------------------
bool CPrefabVMF::IsLoaded(void)
{
if (m_pWorld == NULL)
{
return false;
}
//
// We have loaded this prefab at least once this session. Check the file date/time
// against our cached date/time to see if we need to reload it.
//
struct _stat info;
if (_stat(m_szFilename, &info) == 0)
{
if (info.st_mtime > m_nFileTime)
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabVMF::Load(DWORD dwFlags)
{
//
// Create a new world to hold the loaded objects.
//
if (m_pWorld != NULL)
{
delete m_pWorld;
}
m_pWorld = new CMapWorld( NULL );
//
// Open the file.
//
CChunkFile File;
ChunkFileResult_t eResult = File.Open(m_szFilename, ChunkFile_Read);
//
// Read the file.
//
if (eResult == ChunkFile_Ok)
{
//
// Set up handlers for the subchunks that we are interested in.
//
CChunkHandlerMap Handlers;
Handlers.AddHandler("world", (ChunkHandler_t)CPrefabVMF::LoadWorldCallback, this);
Handlers.AddHandler("entity", (ChunkHandler_t)CPrefabVMF::LoadEntityCallback, this);
// dvs: Handlers.SetErrorHandler((ChunkErrorHandler_t)CPrefabVMF::HandleLoadError, this);
File.PushHandlers(&Handlers);
//CMapDoc::SetLoadingMapDoc( this ); dvs: fix - without this, no displacements in prefabs
//
// Read the sub-chunks. We ignore keys in the root of the file, so we don't pass a
// key value callback to ReadChunk.
//
while (eResult == ChunkFile_Ok)
{
eResult = File.ReadChunk();
}
if (eResult == ChunkFile_EOF)
{
eResult = ChunkFile_Ok;
}
//CMapDoc::SetLoadingMapDoc( NULL );
File.PopHandlers();
}
if (eResult == ChunkFile_Ok)
{
m_pWorld->PostloadWorld();
m_pWorld->CalcBounds();
File.Close();
//
// Store the file modification time to use as a cache check.
//
struct _stat info;
if (_stat(m_szFilename, &info) == 0)
{
m_nFileTime = info.st_mtime;
}
}
else
{
//GetMainWnd()->MessageBox(File.GetErrorText(eResult), "Error loading prefab", MB_OK | MB_ICONEXCLAMATION);
}
return(eResult == ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pFile -
// pData -
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CPrefabVMF::LoadEntityCallback(CChunkFile *pFile, CPrefabVMF *pPrefab)
{
CMapEntity *pEntity = new CMapEntity;
ChunkFileResult_t eResult = pEntity->LoadVMF(pFile);
if (eResult == ChunkFile_Ok)
{
CMapWorld *pWorld = pPrefab->GetWorld();
pWorld->AddChild(pEntity);
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pFile -
// pData -
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CPrefabVMF::LoadWorldCallback(CChunkFile *pFile, CPrefabVMF *pPrefab)
{
CMapWorld *pWorld = pPrefab->GetWorld();
ChunkFileResult_t eResult = pWorld->LoadVMF(pFile);
return(eResult);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszFilename -
// dwFlags -
// Output : int
//-----------------------------------------------------------------------------
int CPrefabVMF::Save(LPCTSTR pszFilename, DWORD dwFlags)
{
return 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPrefabVMF::SetFilename(const char *szFilename)
{
//
// Extract the file name without the path or extension as the prefab name.
//
_splitpath(szFilename, NULL, NULL, szName, NULL);
strcpy(m_szFilename, szFilename);
}
| 0 | 0.884043 | 1 | 0.884043 | game-dev | MEDIA | 0.547912 | game-dev | 0.819012 | 1 | 0.819012 |
DanceManiac/Advanced-X-Ray-Public | 4,763 | SourcesAXR/xrGameCS/group_hierarchy_holder.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : group_hierarchy_holder.cpp
// Created : 12.11.2001
// Modified : 03.09.2004
// Author : Dmitriy Iassenev, Oles Shishkovtsov, Aleksandr Maksimchuk
// Description : Group hierarchy holder
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "group_hierarchy_holder.h"
#include "squad_hierarchy_holder.h"
#include "entity.h"
#include "agent_manager.h"
#include "agent_member_manager.h"
#include "agent_memory_manager.h"
#include "ai/stalker/ai_stalker.h"
#include "memory_manager.h"
#include "visual_memory_manager.h"
#include "sound_memory_manager.h"
#include "hit_memory_manager.h"
CGroupHierarchyHolder::~CGroupHierarchyHolder ()
{
VERIFY (m_members.empty());
VERIFY (!m_visible_objects);
VERIFY (!m_sound_objects);
VERIFY (!m_hit_objects);
VERIFY (!m_agent_manager);
}
#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
void CGroupHierarchyHolder::update_leader ()
{
m_leader = 0;
MEMBER_REGISTRY::iterator I = m_members.begin();
MEMBER_REGISTRY::iterator E = m_members.end();
for ( ; I != E; ++I)
if ((*I)->g_Alive()) {
m_leader = *I;
break;
}
}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER
void CGroupHierarchyHolder::register_in_group (CEntity *member)
{
VERIFY (member);
MEMBER_REGISTRY::iterator I = std::find(m_members.begin(),m_members.end(),member);
VERIFY3 (I == m_members.end(),"Specified group member has already been found",*member->cName());
if (m_members.empty()) {
m_visible_objects = xr_new<VISIBLE_OBJECTS>();
m_sound_objects = xr_new<SOUND_OBJECTS>();
m_hit_objects = xr_new<HIT_OBJECTS>();
// m_visible_objects->reserve (128);
// m_sound_objects->reserve (128);
// m_hit_objects->reserve (128);
}
m_members.push_back (member);
}
void CGroupHierarchyHolder::register_in_squad (CEntity *member)
{
#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
if (!leader() && member->g_Alive()) {
m_leader = member;
if (!squad().leader())
squad().leader (member);
}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER
}
void CGroupHierarchyHolder::register_in_agent_manager (CEntity *member)
{
if (!get_agent_manager() && smart_cast<CAI_Stalker*>(member)) {
m_agent_manager = xr_new<CAgentManager>();
agent_manager().memory().set_squad_objects (&visible_objects());
agent_manager().memory().set_squad_objects (&sound_objects());
agent_manager().memory().set_squad_objects (&hit_objects());
}
if (get_agent_manager())
agent_manager().member().add (member);
}
void CGroupHierarchyHolder::register_in_group_senses (CEntity *member)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(member);
if (monster) {
monster->memory().visual().set_squad_objects(&visible_objects());
monster->memory().sound().set_squad_objects (&sound_objects());
monster->memory().hit().set_squad_objects (&hit_objects());
}
}
void CGroupHierarchyHolder::unregister_in_group (CEntity *member)
{
VERIFY (member);
MEMBER_REGISTRY::iterator I = std::find(m_members.begin(),m_members.end(),member);
VERIFY3 (I != m_members.end(),"Specified group member cannot be found",*member->cName());
m_members.erase (I);
}
void CGroupHierarchyHolder::unregister_in_squad (CEntity *member)
{
#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
if (leader() && (leader()->ID() == member->ID())) {
update_leader ();
if (squad().leader()->ID() == member->ID())
if (leader())
squad().leader (leader());
else
squad().update_leader ();
}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER
}
void CGroupHierarchyHolder::unregister_in_agent_manager (CEntity *member)
{
if (get_agent_manager()) {
agent_manager().member().remove (member);
if (agent_manager().member().members().empty())
xr_delete (m_agent_manager);
}
if (m_members.empty()) {
xr_delete (m_visible_objects);
xr_delete (m_sound_objects);
xr_delete (m_hit_objects);
}
}
void CGroupHierarchyHolder::unregister_in_group_senses (CEntity *member)
{
CCustomMonster *monster = smart_cast<CCustomMonster*>(member);
if (monster) {
monster->memory().visual().set_squad_objects(0);
monster->memory().sound().set_squad_objects (0);
monster->memory().hit().set_squad_objects (0);
}
}
void CGroupHierarchyHolder::register_member (CEntity *member)
{
register_in_group (member);
register_in_squad (member);
register_in_agent_manager (member);
register_in_group_senses (member);
}
void CGroupHierarchyHolder::unregister_member (CEntity *member)
{
unregister_in_group (member);
unregister_in_squad (member);
unregister_in_agent_manager (member);
unregister_in_group_senses (member);
}
| 0 | 0.924424 | 1 | 0.924424 | game-dev | MEDIA | 0.890899 | game-dev | 0.867343 | 1 | 0.867343 |
wormtql/genshin_artifact | 5,394 | mona_core/src/buffs/buffs/character/xianyun.rs | use crate::attribute::{Attribute, AttributeName};
use crate::buffs::{Buff, BuffConfig};
use crate::buffs::buff::BuffMeta;
use crate::buffs::buff_meta::{BuffFrom, BuffGenre, BuffImage, BuffMetaData};
use crate::buffs::buff_name::BuffName;
use crate::character::CharacterName;
use crate::common::i18n::locale;
use crate::common::item_config_type::{ItemConfig, ItemConfigType};
use crate::enemies::Enemy;
pub struct BuffXianyunTalent1 {
pub stack: f64,
}
impl<A: Attribute> Buff<A> for BuffXianyunTalent1 {
fn change_attribute(&self, attribute: &mut A) {
let bonus = if self.stack < 1e-6 {
0.0
} else if self.stack >= 1e-6 && self.stack < 1.0 {
self.stack * 0.04
} else {
0.02 + self.stack * 0.02
};
attribute.set_value_by(AttributeName::CriticalBase, "BUFF: 闲云天赋1「霜翎高逐祥风势」", bonus);
}
}
impl BuffMeta for BuffXianyunTalent1 {
#[cfg(not(target_family = "wasm"))]
const META_DATA: BuffMetaData = BuffMetaData {
name: BuffName::XianyunTalent1,
name_locale: locale!(
zh_cn: "闲云-「霜翎高逐祥风势」",
en: "Xianun-「Galefeather Pursuit」"
),
image: BuffImage::Avatar(CharacterName::Xianyun),
genre: BuffGenre::Character,
description: Some(locale!(
zh_cn: "朝起鹤云的闲云冲击波每命中一个敌人,都将为队伍中附近的所有角色产生一层持续20秒,至多叠加4层的「风翎」效果,使角色的下落攻击的暴击率提升4%/6%/8%/10%。每次命中敌人产生的「风翎」的持续时间独立计算。",
en: "Each opponent hit by Driftcloud Waves from White Clouds at Dawn will grant all nearby party members 1 stack of Storm Pinion for 20s. Max 4 stacks. These will cause the characters' Plunging Attack CRIT Rate to increase by 4%/6%/8%/10% respectively. Each Storm Pinion created by hitting an opponent has an independent duration."
)),
from: BuffFrom::Character(CharacterName::Xianyun)
};
#[cfg(not(target_family = "wasm"))]
const CONFIG: Option<&'static [ItemConfig]> = Some(&[
ItemConfig {
name: "stack",
title: locale!(
zh_cn: "层数",
en: "Stack"
),
config: ItemConfigType::Float { min: 0.0, max: 4.0, default: 4.0 }
}
]);
fn create<A: Attribute>(b: &BuffConfig) -> Box<dyn Buff<A>> {
let stack = match *b {
BuffConfig::XianyunTalent1 { stack } => stack,
_ => 0.0
};
Box::new(BuffXianyunTalent1 {
stack
})
}
}
pub struct BuffXianyunTalent2 {
pub rate: f64,
pub c2: bool,
pub atk: f64,
}
impl<A: Attribute> Buff<A> for BuffXianyunTalent2 {
fn change_attribute(&self, attribute: &mut A) {
let factor = if self.c2 { 2.0 } else { 1.0 };
let dmg = (9000.0_f64 * factor).min(self.atk * 2.0 * factor);
attribute.set_value_by(AttributeName::ExtraDmgPlungingAttackLowHigh, "闲云天赋2「细想应是洞中仙」", dmg);
}
}
impl BuffMeta for BuffXianyunTalent2 {
#[cfg(not(target_family = "wasm"))]
const META_DATA: BuffMetaData = BuffMetaData {
name: BuffName::XianyunTalent2,
name_locale: locale!(
zh_cn: "闲云-「细想应是洞中仙」",
en: "Xianyun-「Consider, the Adeptus in Her Realm」"
),
image: BuffImage::Avatar(CharacterName::Xianyun),
genre: BuffGenre::Character,
description: Some(locale!(
zh_cn: "暮集竹星的竹星拥有仙力助推时,附近的当前场上角色的下落攻击坠地冲击造成的伤害提升,提升值相当于闲云的攻击力的200%。通过这种方式,至多使附近的当前场上角色的下落攻击坠地冲击伤害提升9000。<br>C2:固有天赋「细想应是洞中仙」的效果获得提升:暮集竹星的竹星拥有仙力助推时,附近的当前场上角色的下落攻击坠地冲击造成的伤害提升,提升值相当于闲云的攻击力的400%。通过这种方式,至多使附近的当前场上角色的下落攻击坠地冲击伤害提升18000。",
en: "When the Starwicker created by Stars Gather at Dusk has Adeptal Assistance stacks, nearby active characters' Plunging Attack shockwave DMG will be increased by 200% of Xianyun's ATK. The maximum DMG increase that can be achieved this way is 9,000.<br>C2: the effects of the Passive Talent \"Consider, the Adeptus in Her Realm\" will be enhanced: When the Starwicker created by Stars Gather at Dusk has Adeptal Assistance stacks, nearby active characters' Plunging Attack shockwave DMG will be increased by 400% of Xianyun's ATK. The maximum DMG increase that can be achieved this way is 18,000."
)),
from: BuffFrom::Character(CharacterName::Xianyun)
};
#[cfg(not(target_family = "wasm"))]
const CONFIG: Option<&'static [ItemConfig]> = Some(&[
ItemConfig {
name: "rate",
title: locale!(
zh_cn: "应用比例",
en: "Ratio"
),
config: ItemConfigType::Float { min: 0.0, max: 1.0, default: 1.0 }
},
ItemConfig {
name: "c2",
title: locale!(
zh_cn: "命座2「鹤唳远人间」",
en: "C2"
),
config: ItemConfigType::Bool { default: false }
},
ItemConfig {
name: "atk",
title: locale!(
zh_cn: "闲云的攻击力",
en: "ATK of Xianyun"
),
config: ItemConfigType::Float { min: 0.0, max: 10000.0, default: 2000.0 }
}
]);
fn create<A: Attribute>(b: &BuffConfig) -> Box<dyn Buff<A>> {
let (rate, c2, atk) = match *b {
BuffConfig::XianyunTalent2 { rate, c2, atk } => (rate, c2, atk),
_ => (0.0, false, 0.0)
};
Box::new(BuffXianyunTalent2 {
rate, c2, atk
})
}
}
| 0 | 0.882362 | 1 | 0.882362 | game-dev | MEDIA | 0.861383 | game-dev | 0.834142 | 1 | 0.834142 |
ProjectIgnis/CardScripts | 1,400 | rush/c160017018.lua | --サイバースパイス・ナツメグ
--Cybersepice Nutmeg
--Scripted by YoshiDuels
local s,id=GetID()
function s.initial_effect(c)
--Summon with 1 tribute
local e1=aux.AddNormalSummonProcedure(c,true,true,1,1,SUMMON_TYPE_TRIBUTE,aux.Stringid(id,0),s.otfilter)
--Gain LP
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DECKDES|CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetTarget(s.target)
e2:SetOperation(s.operation)
c:RegisterEffect(e2)
end
function s.otfilter(c)
return c:IsRace(RACE_CYBERSE)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDiscardDeck(tp,1) and Duel.IsPlayerCanDiscardDeck(1-tp,1) end
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
--Effect
Duel.DiscardDeck(tp,1,REASON_EFFECT)
local g=Duel.GetOperatedGroup()
Duel.DiscardDeck(1-tp,1,REASON_EFFECT)
local g2=Duel.GetOperatedGroup()
g:Merge(g2)
local tdg=g:Filter(Card.IsAbleToDeck,nil)
if #tdg>0 and Duel.SelectYesNo(tp,aux.Stringid(id,2)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local sg=tdg:Select(tp,1,1,nil)
Duel.HintSelection(sg)
local opt=Duel.SelectOption(tp,aux.Stringid(id,3),aux.Stringid(id,4))
if opt==0 then
Duel.SendtoDeck(sg,nil,SEQ_DECKTOP,REASON_EFFECT)
elseif opt==1 then
Duel.SendtoDeck(sg,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
end
end
end
| 0 | 0.808945 | 1 | 0.808945 | game-dev | MEDIA | 0.924444 | game-dev | 0.954766 | 1 | 0.954766 |
septag/rizz | 16,762 | examples/12-boids/boids.c | #include "rizz/config.h"
#include "rizz/utility.h"
#include "sx/allocator.h"
#include "sx/io.h"
#include "sx/linear-buffer.h"
#include "sx/math-vec.h"
#include "sx/os.h"
#include "sx/rng.h"
#include "sx/string.h"
#include "rizz/3dtools.h"
#include "rizz/imgui-extra.h"
#include "rizz/imgui.h"
#include "rizz/rizz.h"
#include <alloca.h>
#include "../common.h"
RIZZ_STATE static rizz_api_core* the_core;
RIZZ_STATE static rizz_api_gfx* the_gfx;
RIZZ_STATE static rizz_api_app* the_app;
RIZZ_STATE static rizz_api_imgui* the_imgui;
RIZZ_STATE static rizz_api_asset* the_asset;
RIZZ_STATE static rizz_api_camera* the_camera;
RIZZ_STATE static rizz_api_vfs* the_vfs;
RIZZ_STATE static rizz_api_3d* the_3d;
RIZZ_STATE static rizz_api_imgui_extra* the_imguix;
RIZZ_STATE static rizz_api_utility* the_utility;
#ifndef EXAMPLES_ROOT
# define EXAMPLES_ROOT ""
#endif
#define NUM_BOIDS 2048
#define MAX_NEIGHBORS 64
#define INIT_SPEED 2.0f
#define MIN_SPEED 2.0f
#define MAX_SPEED 5.0f
#define NEIGHBOR_DIST 1.0f
#define NEIGHBOR_FOV 90.0f
#define SEPERATION_WEIGHT 8.0f
#define WALL_SIZE 5.0f
#define WALL_DIST 2.0f
#define WALL_WEIGHT 1.0f
#define OBSTACLE_WEIGHT 16.0f
#define ALIGNMENT_WEIGHT 2.0f
#define COHESION_WEIGHT 3.0f
typedef struct {
int count;
int indices[MAX_NEIGHBORS];
} neighbors_t;
bool add_neighbor(neighbors_t* neighbors, int ni)
{
if (neighbors->count == MAX_NEIGHBORS)
return false;
neighbors->indices[neighbors->count++] = ni;
return true;
}
void clear_neighbors(neighbors_t* neighbors)
{
neighbors->count = 0;
}
typedef struct {
int count;
neighbors_t* neighbors;
sx_vec3* pos;
sx_vec3* vel;
sx_vec3* acl;
sx_color* col;
} boid_t;
typedef struct {
rizz_gfx_stage stage;
rizz_camera_fps cam;
sx_vec3 obstacle_origin;
float obstacle_radius;
boid_t* boids;
bool use_jobs;
} boid_simulation_t;
RIZZ_STATE static boid_simulation_t g_simulation;
static inline sx_vec3 calc_wall_acl(float dist, sx_vec3 dir)
{
if (dist < WALL_DIST) {
float f = dist / WALL_DIST;
return sx_vec3_mulf(dir, WALL_WEIGHT / sx_abs(f));
}
return SX_VEC3_ZERO;
}
void update_boid(int bi, float dt)
{
// neighbors
{
sx_vec3 bpos = g_simulation.boids->pos[bi];
for (int i = 0; i < g_simulation.boids->count; i++) {
if (i == bi)
continue;
sx_vec3 npos = g_simulation.boids->pos[i];
sx_vec3 nvel = g_simulation.boids->vel[i];
sx_vec3 to = sx_vec3_sub(bpos, npos);
float len = sx_vec3_len(to);
if (len < NEIGHBOR_DIST) {
sx_vec3 fwd = sx_vec3_norm(nvel);
sx_vec3 dir = sx_vec3_norm(to);
if (sx_vec3_dot(fwd, dir) > 0) {
if (!add_neighbor(&g_simulation.boids->neighbors[bi], i))
break;
}
}
}
}
// walls
{
float scale = WALL_SIZE;
sx_vec3 bpos = g_simulation.boids->pos[bi];
sx_vec3 xp = calc_wall_acl(-scale - bpos.x, sx_vec3f(1, 0, 0));
sx_vec3 yp = calc_wall_acl(-scale - bpos.y, sx_vec3f(0, 1, 0));
sx_vec3 zp = calc_wall_acl(-scale - bpos.z, sx_vec3f(0, 0, 1));
sx_vec3 xn = calc_wall_acl(+scale - bpos.x, sx_vec3f(-1, 0, 0));
sx_vec3 yn = calc_wall_acl(+scale - bpos.y, sx_vec3f(0, -1, 0));
sx_vec3 zn = calc_wall_acl(+scale - bpos.z, sx_vec3f(0, 0, -1));
sx_vec3 r = SX_VEC3_ZERO;
r = sx_vec3_add(r, xp);
r = sx_vec3_add(r, yp);
r = sx_vec3_add(r, zp);
r = sx_vec3_add(r, xn);
r = sx_vec3_add(r, yn);
r = sx_vec3_add(r, zn);
g_simulation.boids->acl[bi] = sx_vec3_add(g_simulation.boids->acl[bi], r);
}
// avoid obstacle
{
sx_vec3 bpos = g_simulation.boids->pos[bi];
float dist;
sx_vec3 dir = sx_vec3_norm_len(sx_vec3_sub(bpos, g_simulation.obstacle_origin), &dist);
if (dist < g_simulation.obstacle_radius)
{
g_simulation.boids->acl[bi] = sx_vec3_add(g_simulation.boids->acl[bi], sx_vec3_mulf(dir, OBSTACLE_WEIGHT));
}
}
// seperation
{
neighbors_t* neighbors = &g_simulation.boids->neighbors[bi];
if (neighbors->count == 0)
return;
sx_vec3 force = SX_VEC3_ZERO;
sx_vec3 bpos = g_simulation.boids->pos[bi];
for (int i = 0; i < neighbors->count; i++) {
sx_vec3 npos = g_simulation.boids->pos[neighbors->indices[i]];
force = sx_vec3_add(force, sx_vec3_norm(sx_vec3_sub(bpos, npos)));
}
force.x /= (float)neighbors->count;
force.y /= (float)neighbors->count;
force.z /= (float)neighbors->count;
force = sx_vec3_mulf(force, SEPERATION_WEIGHT);
g_simulation.boids->acl[bi] = sx_vec3_add(g_simulation.boids->acl[bi], force);
}
// alignment
{
neighbors_t* neighbors = &g_simulation.boids->neighbors[bi];
if (neighbors->count == 0)
return;
sx_vec3 average = SX_VEC3_ZERO;
for (int i = 0; i < neighbors->count; i++) {
sx_vec3 nvel = g_simulation.boids->vel[neighbors->indices[i]];
average = sx_vec3_add(average, nvel);
}
average.x /= (float)neighbors->count;
average.y /= (float)neighbors->count;
average.z /= (float)neighbors->count;
sx_vec3 r = sx_vec3_sub(average, g_simulation.boids->vel[bi]);
r = sx_vec3_mulf(r, ALIGNMENT_WEIGHT);
g_simulation.boids->acl[bi] = sx_vec3_add(g_simulation.boids->acl[bi], r);
}
// cohesion
{
neighbors_t* neighbors = &g_simulation.boids->neighbors[bi];
if (neighbors->count == 0)
return;
sx_vec3 average = SX_VEC3_ZERO;
for (int i = 0; i < neighbors->count; i++) {
sx_vec3 npos = g_simulation.boids->pos[neighbors->indices[i]];
average = sx_vec3_add(average, npos);
}
average.x /= (float)neighbors->count;
average.y /= (float)neighbors->count;
average.z /= (float)neighbors->count;
sx_vec3 r = sx_vec3_sub(average, g_simulation.boids->pos[bi]);
r = sx_vec3_mulf(r, COHESION_WEIGHT);
g_simulation.boids->acl[bi] = sx_vec3_add(g_simulation.boids->acl[bi], r);
}
// apply move
{
sx_vec3 pos = g_simulation.boids->pos[bi];
sx_vec3 vel = g_simulation.boids->vel[bi];
sx_vec3 acl = g_simulation.boids->acl[bi];
vel = sx_vec3_add(vel, sx_vec3_mulf(acl, dt));
float speed = sx_vec3_len(vel);
sx_vec3 dir = sx_vec3_norm(vel);
vel = sx_vec3_mulf(dir, sx_clamp(speed, MIN_SPEED, MAX_SPEED));
pos = sx_vec3_add(pos, sx_vec3_mulf(vel, dt));
acl = SX_VEC3_ZERO;
g_simulation.boids->pos[bi] = pos;
g_simulation.boids->vel[bi] = vel;
g_simulation.boids->acl[bi] = acl;
}
}
static bool init()
{
#if SX_PLATFORM_ANDROID || SX_PLATFORM_IOS
the_vfs->mount_mobile_assets("/assets");
#else
// mount `/asset` directory
char asset_dir[RIZZ_MAX_PATH];
sx_os_path_join(asset_dir, sizeof(asset_dir), EXAMPLES_ROOT, "assets"); // "/examples/assets"
the_vfs->mount(asset_dir, "/assets", true);
#endif
// register main graphics stage.
// at least one stage should be registered if you want to draw anything
g_simulation.stage = the_gfx->stage_register("main", (rizz_gfx_stage){ .id = 0 });
sx_assert(g_simulation.stage.id);
// camera
// projection: setup for perspective
// view: Z-UP Y-Forward (like blender)
sx_vec2 screen_size;
the_app->window_size(&screen_size);
const float view_width = screen_size.x;
const float view_height = screen_size.y;
the_camera->fps_init(&g_simulation.cam, 60.0f, sx_rectwh(0, 0, view_width, view_height), 0.1f, 500.0f);
the_camera->fps_lookat(&g_simulation.cam, sx_vec3f(5, 15, 5), SX_VEC3_ZERO, SX_VEC3_UNITZ);
// init boids
{
const int boid_count = NUM_BOIDS;
sx_linear_buffer lb;
sx_linear_buffer_init(&lb, boid_t, 0);
sx_linear_buffer_addtype(&lb, boid_t, neighbors_t, neighbors, boid_count, 0);
sx_linear_buffer_addtype(&lb, boid_t, sx_vec3, pos, boid_count, 0);
sx_linear_buffer_addtype(&lb, boid_t, sx_vec3, vel, boid_count, 0);
sx_linear_buffer_addtype(&lb, boid_t, sx_vec3, acl, boid_count, 0);
sx_linear_buffer_addtype(&lb, boid_t, sx_color, col, boid_count, 0);
boid_t* buf = sx_linear_buffer_calloc(&lb, the_core->heap_alloc());
buf->count = boid_count;
g_simulation.boids = buf;
sx_rng rng;
sx_rng_seed(&rng, 123);
for (int i = 0; i < boid_count; i++) {
sx_vec3 pos = sx_vec3f(sx_rng_genf(&rng), sx_rng_genf(&rng), sx_rng_genf(&rng));
pos.x = (pos.x * 2 - 1);
pos.y = (pos.y * 2 - 1);
pos.z = (pos.z * 2 - 1);
pos = sx_vec3_mulf(sx_vec3_norm(pos), sx_rng_genf(&rng));
sx_color col =
sx_color4f(sx_rng_genf(&rng), sx_rng_genf(&rng), sx_rng_genf(&rng), 1.0f);
g_simulation.boids->pos[i] = pos;
g_simulation.boids->col[i] = col;
sx_vec3 vel = sx_vec3f(sx_rng_genf(&rng), sx_rng_genf(&rng), sx_rng_genf(&rng));
vel.x = (vel.x * 2 - 1);
vel.y = (vel.y * 2 - 1);
vel.z = (vel.z * 2 - 1);
vel = sx_vec3_norm(vel);
g_simulation.boids->vel[i] = sx_vec3_mulf(vel, INIT_SPEED);
}
}
the_3d->debug.set_max_instances(NUM_BOIDS + 16);
g_simulation.obstacle_radius = 3.0f;
return true;
}
static void shutdown(void)
{
sx_free(the_core->heap_alloc(), g_simulation.boids);
}
static void update_job_cb(int start, int end, int thrd_index, void* user)
{
float dt = the_core->delta_time();
for (int i = start; i < end; i++) {
update_boid(i, dt);
}
}
static void update(float dt)
{
float move_speed = 3.0f;
if (the_app->key_pressed(RIZZ_APP_KEYCODE_LEFT_SHIFT) ||
the_app->key_pressed(RIZZ_APP_KEYCODE_RIGHT_SHIFT))
move_speed = 10.0f;
// update keyboard movement: WASD first-person
if (the_app->key_pressed(RIZZ_APP_KEYCODE_A) || the_app->key_pressed(RIZZ_APP_KEYCODE_LEFT)) {
the_camera->fps_strafe(&g_simulation.cam, -move_speed * dt);
}
if (the_app->key_pressed(RIZZ_APP_KEYCODE_D) || the_app->key_pressed(RIZZ_APP_KEYCODE_RIGHT)) {
the_camera->fps_strafe(&g_simulation.cam, move_speed * dt);
}
if (the_app->key_pressed(RIZZ_APP_KEYCODE_W) || the_app->key_pressed(RIZZ_APP_KEYCODE_UP)) {
the_camera->fps_forward(&g_simulation.cam, move_speed * dt);
}
if (the_app->key_pressed(RIZZ_APP_KEYCODE_S) || the_app->key_pressed(RIZZ_APP_KEYCODE_DOWN)) {
the_camera->fps_forward(&g_simulation.cam, -move_speed * dt);
}
if (the_imgui->Begin("Boids", NULL, 0)) {
the_imgui->Checkbox("Use JobSystem", &g_simulation.use_jobs);
if (the_imgui->Button("Memory Snapshot", SX_VEC2_ZERO)) {
the_core->trace_alloc_capture_frame();
}
}
the_imgui->End();
static float time = 0.0f;
time += dt;
g_simulation.obstacle_origin.x = sx_sin(time) * 1.5f;
g_simulation.obstacle_origin.y = sx_cos(time) * 1.5f;
g_simulation.obstacle_origin.z = sx_sin(time * 0.25f) * 1.5f;
// simulate boids
if (g_simulation.use_jobs) {
sx_job_t job =
the_core->job_dispatch(NUM_BOIDS, update_job_cb, NULL, SX_JOB_PRIORITY_HIGH, 0);
the_core->job_wait_and_del(job);
} else {
for (int i = 0; i < g_simulation.boids->count; i++) {
update_boid(i, dt);
}
}
show_debugmenu(the_imgui, the_core);
}
static void render(void)
{
sg_pass_action pass_action = {
.colors[0] = { SG_ACTION_CLEAR, { 0.0f, 0.0f, 0.0f, 0.0f } },
.depth = { SG_ACTION_CLEAR, 1.0f },
};
the_gfx->staged.begin(g_simulation.stage);
the_gfx->staged.begin_default_pass(&pass_action, the_app->width(), the_app->height());
sx_mat4 proj, view;
the_camera->perspective_mat(&g_simulation.cam.cam, &proj);
the_camera->view_mat(&g_simulation.cam.cam, &view);
sx_mat4 viewproj = sx_mat4_mul(&proj, &view);
const sx_alloc* talloc = the_core->tmp_alloc_push();
sx_scope(the_core->tmp_alloc_pop())
{
const int count = g_simulation.boids->count;
sx_box* boxes = sx_malloc(talloc, sizeof(sx_box) * count);
for (int i = 0; i < count; i++) {
sx_vec3 nvel = g_simulation.boids->vel[i];
sx_vec3 zz = sx_vec3_norm(nvel);
sx_vec3 xx = sx_vec3_norm(sx_vec3_cross(zz, SX_VEC3_UNITY));
sx_vec3 yy = sx_vec3_cross(xx, zz);
sx_mat3 m = sx_mat3v(xx, sx_vec3_mulf(yy, -1.0f), zz);
boxes[i].tx = sx_tx3d_set(g_simulation.boids->pos[i], m);
boxes[i].e = sx_vec3f(.05f, .05f, .2f);
}
the_3d->debug.draw_boxes(boxes, NUM_BOIDS, &viewproj, RIZZ_3D_DEBUG_MAPTYPE_WHITE, g_simulation.boids->col);
the_3d->debug.draw_sphere(g_simulation.obstacle_origin, g_simulation.obstacle_radius,
&viewproj, RIZZ_3D_DEBUG_MAPTYPE_WHITE, sx_color4f(1.0f, 0.0f, 0.0f, 0.5f));
}
sx_box wall_box;
wall_box.e = sx_vec3f(WALL_SIZE, WALL_SIZE, WALL_SIZE);
wall_box.tx = sx_tx3d_ident();
the_3d->debug.draw_box(&wall_box, &viewproj, RIZZ_3D_DEBUG_MAPTYPE_WHITE, sx_color4f(0.0f, 0.5f, 1.0f, 0.3f));
the_gfx->staged.end_pass();
the_gfx->staged.end();
}
rizz_plugin_decl_event_handler(boids, e)
{
static bool mouse_down = false;
float dt = (float)sx_tm_sec(the_core->delta_tick());
const float rotate_speed = 5.0f;
static sx_vec2 last_mouse;
switch (e->type) {
case RIZZ_APP_EVENTTYPE_SUSPENDED:
break;
case RIZZ_APP_EVENTTYPE_RESTORED:
break;
case RIZZ_APP_EVENTTYPE_MOUSE_DOWN:
if (!mouse_down) {
the_app->mouse_capture();
}
mouse_down = true;
last_mouse = sx_vec2f(e->mouse_x, e->mouse_y);
break;
case RIZZ_APP_EVENTTYPE_MOUSE_UP:
if (mouse_down) {
the_app->mouse_release();
}
case RIZZ_APP_EVENTTYPE_MOUSE_LEAVE:
mouse_down = false;
break;
case RIZZ_APP_EVENTTYPE_MOUSE_MOVE:
if (mouse_down) {
float dx = sx_torad(e->mouse_x - last_mouse.x) * rotate_speed * dt;
float dy = sx_torad(e->mouse_y - last_mouse.y) * rotate_speed * dt;
last_mouse = sx_vec2f(e->mouse_x, e->mouse_y);
if (!the_imguix->gizmo.is_using() && !the_imguix->is_capturing_mouse()) {
the_camera->fps_pitch(&g_simulation.cam, dy);
the_camera->fps_yaw(&g_simulation.cam, dx);
}
}
break;
default:
break;
}
}
rizz_plugin_decl_main(boids, plugin, e)
{
switch (e) {
case RIZZ_PLUGIN_EVENT_STEP:
update(the_core->delta_time());
render();
break;
case RIZZ_PLUGIN_EVENT_INIT:
// runs only once for application. Retreive needed APIs
the_core = (rizz_api_core*)plugin->api->get_api(RIZZ_API_CORE, 0);
the_gfx = (rizz_api_gfx*)plugin->api->get_api(RIZZ_API_GFX, 0);
the_app = (rizz_api_app*)plugin->api->get_api(RIZZ_API_APP, 0);
the_vfs = (rizz_api_vfs*)plugin->api->get_api(RIZZ_API_VFS, 0);
the_asset = (rizz_api_asset*)plugin->api->get_api(RIZZ_API_ASSET, 0);
the_camera = (rizz_api_camera*)plugin->api->get_api(RIZZ_API_CAMERA, 0);
the_imgui = (rizz_api_imgui*)plugin->api->get_api_byname("imgui", 0);
the_imguix = (rizz_api_imgui_extra*)plugin->api->get_api_byname("imgui_extra", 0);
the_3d = (rizz_api_3d*)plugin->api->get_api_byname("3dtools", 0);
the_utility = (rizz_api_utility*)plugin->api->get_api_byname("utility", 0);
init();
break;
case RIZZ_PLUGIN_EVENT_LOAD:
break;
case RIZZ_PLUGIN_EVENT_UNLOAD:
break;
case RIZZ_PLUGIN_EVENT_SHUTDOWN:
shutdown();
break;
}
return 0;
}
rizz_game_decl_config(conf)
{
conf->app_name = "";
conf->app_version = 1000;
conf->app_title = "boids";
conf->app_flags |= RIZZ_APP_FLAG_HIGHDPI;
conf->log_level = RIZZ_LOG_LEVEL_DEBUG;
conf->window_width = EXAMPLES_DEFAULT_WIDTH;
conf->window_height = EXAMPLES_DEFAULT_HEIGHT;
conf->multisample_count = 4;
conf->swap_interval = RIZZ_APP_SWAP_INTERVAL_NOSYNC;
conf->plugins[0] = "imgui";
conf->plugins[1] = "3dtools";
conf->plugins[2] = "utility";
} | 0 | 0.828213 | 1 | 0.828213 | game-dev | MEDIA | 0.316391 | game-dev | 0.994149 | 1 | 0.994149 |
ApproxEng/approxeng.input | 2,273 | src/python/approxeng/input/sf30pro.py | from approxeng.input import Controller, Button, CentredAxis, TriggerAxis, BinaryAxis
__all__ = ['SF30Pro']
class SF30Pro(Controller):
"""
Driver for the 8BitDo SF30 Pro, courtesy of Tom Brougthon (tabroughton on github)
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new SF30 Pro driver
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
"""
super(SF30Pro, self).__init__(
controls=[
TriggerAxis("Right Trigger", 0, 255, 9, sname='rt'),
TriggerAxis("Left Trigger", 0, 255, 10, sname='lt'),
CentredAxis("Right Vertical", 255, 0, 5, sname='ry'),
CentredAxis("Left Horizontal", 0, 255, 0, sname='lx'),
CentredAxis("Left Vertical", 255, 0, 1, sname='ly'),
CentredAxis("Right Horizontal", 0, 255, 2, sname='rx'),
BinaryAxis("D-pad Horizontal", 16, b1name='dleft', b2name='dright'),
BinaryAxis("D-pad Vertical", 17, b1name='ddown', b2name='dup'),
Button("B", 304, sname='circle'),
Button("A", 305, sname='cross'),
Button("Mode", 306, sname='home'),
Button("X", 307, sname='triangle'),
Button("Y", 308, sname='square'),
Button("L1", 310, sname='l1'),
Button("R1", 311, sname='r1'),
Button("L2", 312, sname='l2'),
Button("R2", 313, sname='r2'),
Button("Select", 314, sname='select'),
Button("Start", 315, sname='start'),
Button("Left Stick", 317, sname='ls'),
Button("Right Stick", 318, sname='rs')
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x2dc8, 0x6100)]
def __repr__(self):
return '8Bitdo SF30 Pro'
| 0 | 0.746789 | 1 | 0.746789 | game-dev | MEDIA | 0.486247 | game-dev,desktop-app | 0.67787 | 1 | 0.67787 |
jtfmumm/novitiate | 1,952 | src/world/simple-dungeon.pony | use "collections"
use "random"
use "time"
use "../agents"
use "../datast"
use "../display"
use "../encounters"
use "../game"
use "../generators"
use "../guid"
use "../inventory"
use "../log"
actor SimpleDungeon is World
let _parent_world: World tag
// TODO: Use determinate seed
let _guid_gen: GuidGenerator = GuidGenerator
let _display: Display tag
let _diameter: I32
let _tiles: Tiles
let _agents: Agents
let _turn_manager: TurnManager tag
let _depth: I32
var _last_focus: Pos val
var _present: Bool = false
var _last_turn: I32 = 0
new create(d: I32, t_manager: TurnManager tag, display': Display tag,
depth': I32 = 1, parent': World tag = EmptyWorld,
self: (Self | None) = None)
=>
_diameter = d
_turn_manager = t_manager
_parent_world = parent'
_depth = depth'
let starting_pos = Pos(_diameter / 2, _diameter / 2)
_last_focus = starting_pos
_tiles = SimpleTiles(d)
_display = display'
_agents = Agents(_display)
be increment_turn() => _last_turn = _last_turn + 1
be enter(self: Self) =>
add_agent(self, _last_focus, OccupantCodes.self())
self.update_world(this)
self.enter_world_at(_last_focus, _depth)
_display.log("Entering simple room")
_present = true
fun ref _exit(pos: Pos val, self: Self) =>
_last_focus = pos
remove_occupant(pos)
agents().remove(self)
_present = false
be add_agent(a: Agent tag, pos: Pos val, occupant_code: I32) =>
_agents.add(a)
set_occupant(pos, a, occupant_code)
fun display(): Display tag => _display
fun diameter(): I32 => _diameter
fun ref tile(pos: Pos val): Tile =>
try
_tiles(pos)?
else
Tile.empty()
end
fun ref tiles(): Tiles => _tiles
fun ref agents(): Agents => _agents
fun depth(): I32 => _depth
fun parent(): World tag => _parent_world
fun turn_manager(): (TurnManager | None) => _turn_manager
fun present(): Bool => _present
| 0 | 0.633955 | 1 | 0.633955 | game-dev | MEDIA | 0.928303 | game-dev | 0.785327 | 1 | 0.785327 |
Let-s-Do-Collection/Vinery | 9,574 | common/src/main/java/net/satisfy/vinery/core/block/BasketBlock.java | package net.satisfy.vinery.core.block;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.PathComputationType;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.satisfy.vinery.core.block.entity.BasketBlockEntity;
import net.satisfy.vinery.core.registry.EntityTypeRegistry;
import net.satisfy.vinery.core.util.GeneralUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
@SuppressWarnings("deprecation")
public class BasketBlock extends BaseEntityBlock implements SimpleWaterloggedBlock{
public static final DirectionProperty FACING;
public static final ResourceLocation CONTENTS;
public static final BooleanProperty WATERLOGGED;
public BasketBlock(Properties properties) {
super(properties);
this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(WATERLOGGED,false));
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return simpleCodec(BasketBlock::new);
}
private static final Supplier<VoxelShape> voxelShapeSupplier = () -> {
VoxelShape shape = Shapes.empty();
shape = Shapes.joinUnoptimized(shape, Shapes.box(0.125, 0.3125, 0.4375, 0.125, 0.8125, 0.5625), BooleanOp.OR);
shape = Shapes.joinUnoptimized(shape, Shapes.box(0.875, 0.3125, 0.4375, 0.875, 0.8125, 0.5625), BooleanOp.OR);
shape = Shapes.joinUnoptimized(shape, Shapes.box(0.125, 0.8125, 0.4375, 0.875, 0.8125, 0.5625), BooleanOp.OR);
shape = Shapes.joinUnoptimized(shape, Shapes.box(0.125, 0, 0.1875, 0.875, 0.4375, 0.8125), BooleanOp.OR);
return shape;
};
public static final Map<Direction, VoxelShape> SHAPE = net.minecraft.Util.make(new HashMap<>(), map -> {
for (Direction direction : Direction.Plane.HORIZONTAL.stream().toList()) {
map.put(direction, GeneralUtil.rotateShape(Direction.NORTH, direction, voxelShapeSupplier.get()));
}
});
@Override
public @NotNull VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {
return SHAPE.get(state.getValue(FACING));
}
@Override
public @NotNull InteractionResult useWithoutItem(BlockState blockState, Level level, BlockPos blockPos, Player player, BlockHitResult blockHitResult) {
if (level.isClientSide) {
return InteractionResult.SUCCESS;
} else {
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity instanceof BasketBlockEntity) {
player.openMenu((BasketBlockEntity)blockEntity);
}
return InteractionResult.CONSUME;
}
}
public BlockState playerWillDestroy(Level level, BlockPos blockPos, BlockState blockState, Player player) {
if (!level.isClientSide) {
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity instanceof BasketBlockEntity basketBlockEntity) {
ItemStack itemStack = new ItemStack(blockState.getBlock());
basketBlockEntity.saveToItem(itemStack,level.registryAccess());
double x = blockPos.getX() + 0.5;
double y = blockPos.getY() + 0.5;
double z = blockPos.getZ() + 0.5;
ItemEntity itemEntity = new ItemEntity(level, x, y, z, itemStack);
itemEntity.setDefaultPickUpDelay();
level.addFreshEntity(itemEntity);
}
}
return super.playerWillDestroy(level, blockPos, blockState, player);
}
public @NotNull List<ItemStack> getDrops(BlockState blockState, LootParams.Builder builder) {
BlockEntity blockEntity = builder.getOptionalParameter(LootContextParams.BLOCK_ENTITY);
if (blockEntity instanceof BasketBlockEntity basketBlockEntity) {
builder = builder.withDynamicDrop(CONTENTS, (consumer) -> {
for(int i = 0; i < basketBlockEntity.getContainerSize(); ++i) {
consumer.accept(basketBlockEntity.getItem(i));
}
});
}
return super.getDrops(blockState, builder);
}
public void setPlacedBy(Level level, BlockPos blockPos, BlockState blockState, LivingEntity livingEntity, ItemStack itemStack) {
if (itemStack.has(DataComponents.CUSTOM_NAME)) {
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity instanceof BasketBlockEntity) {
blockEntity.setComponents(DataComponentMap.builder().set(DataComponents.CUSTOM_NAME,itemStack.getHoverName()).build());
}
}
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState blockState, BlockEntityType<T> blockEntityType) {
return level.isClientSide ? createTickerHelper(blockEntityType, EntityTypeRegistry.BASKET_ENTITY.get(), BasketBlockEntity::lidAnimateTick) : null;
}
public void onRemove(BlockState blockState, Level level, BlockPos blockPos, BlockState blockState2, boolean bl) {
if (!blockState.is(blockState2.getBlock())) {
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity instanceof BasketBlockEntity) {
level.updateNeighbourForOutputSignal(blockPos, blockState.getBlock());
}
super.onRemove(blockState, level, blockPos, blockState2, bl);
}
}
public @NotNull ItemStack getCloneItemStack(LevelReader levelReader, BlockPos blockPos, BlockState blockState) {
ItemStack itemStack = super.getCloneItemStack(levelReader, blockPos, blockState);
levelReader.getBlockEntity(blockPos, EntityTypeRegistry.BASKET_ENTITY.get()).ifPresent((basketBlockEntity) -> basketBlockEntity.saveToItem(itemStack,levelReader.registryAccess()));
return itemStack;
}
public @NotNull RenderShape getRenderShape(BlockState blockState) {
return RenderShape.ENTITYBLOCK_ANIMATED;
}
public boolean hasAnalogOutputSignal(BlockState blockState) {
return true;
}
public int getAnalogOutputSignal(BlockState blockState, Level level, BlockPos blockPos) {
return AbstractContainerMenu.getRedstoneSignalFromBlockEntity(level.getBlockEntity(blockPos));
}
public @NotNull BlockState rotate(BlockState state, Rotation rotation) {
return state.setValue(FACING, rotation.rotate(state.getValue(FACING)));
}
public @NotNull BlockState mirror(BlockState state, Mirror mirror) {
return state.rotate(mirror.getRotation(state.getValue(FACING)));
}
@Nullable
@Override
@SuppressWarnings("unused")
public BlockState getStateForPlacement(BlockPlaceContext blockPlaceContext) {
FluidState fluidState = blockPlaceContext.getLevel().getFluidState(blockPlaceContext.getClickedPos());
return this.defaultBlockState().setValue(FACING, blockPlaceContext.getHorizontalDirection().getOpposite());
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
return new BasketBlockEntity(blockPos,blockState);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING, WATERLOGGED);
}
public boolean isPathfindable(BlockState arg, BlockGetter arg2, BlockPos arg3, PathComputationType arg4) {
return false;
}
static{
FACING = HorizontalDirectionalBlock.FACING;
WATERLOGGED = BlockStateProperties.WATERLOGGED;
CONTENTS = ResourceLocation.parse("contents");
}
} | 0 | 0.898144 | 1 | 0.898144 | game-dev | MEDIA | 0.998247 | game-dev | 0.971663 | 1 | 0.971663 |
macroquest/macroquest | 4,502 | src/plugins/lua/bindings/lua_MQBindings.h | /*
* MacroQuest: The extension platform for EverQuest
* Copyright (C) 2002-present MacroQuest Authors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#pragma once
#include "LuaCommon.h"
#include <mq/Plugin.h>
namespace mq {
struct MQTypeVar;
struct MQTopLevelObject;
}
namespace mq::datatypes {
class MQ2Type;
}
namespace mq::lua {
std::tuple<const std::string&, const std::string&, int, bool> GetArgInfo(sol::function func);
}
namespace mq::lua::bindings {
//----------------------------------------------------------------------------
class lua_MQCommand
{
public:
lua_MQCommand(std::string_view command);
void operator()(sol::variadic_args va, sol::this_state s);
std::string command;
};
//----------------------------------------------------------------------------
class lua_MQTopLevelObject;
class lua_MQTypeVar
{
friend class lua_MQTopLevelObject;
public:
lua_MQTypeVar(const std::string& str);
/**
* \brief wraps an MQ type var in a lua implementation
* \param self the MQ type var data source to be represented in lua
*/
lua_MQTypeVar(const MQTypeVar& self);
bool operator==(const lua_MQTypeVar& right) const;
bool EqualData(const lua_MQTopLevelObject& right) const;
bool EqualNil(const sol::lua_nil_t&) const;
MQTypeVar EvaluateMember(const char* index = nullptr) const;
static std::string ToString(const lua_MQTypeVar& obj);
sol::object Call(std::string index, sol::this_state L) const;
sol::object CallInt(int index, sol::this_state L) const;
sol::object CallVA(sol::this_state L, sol::variadic_args args) const;
sol::object CallEmpty(sol::this_state L) const;
sol::object Get(sol::stack_object key, sol::this_state L) const;
datatypes::MQ2Type* GetType() const;
private:
MQTypeVar m_self;
std::string m_member;
};
//----------------------------------------------------------------------------
class lua_MQTopLevelObject
{
public:
lua_MQTopLevelObject() = default;
// this will allow users an alternate way to Get data items
lua_MQTopLevelObject(sol::this_state L, const std::string& str);
lua_MQTopLevelObject(sol::this_state L, const MQTopLevelObject* const self);
lua_MQTypeVar EvaluateSelf() const;
bool operator==(const lua_MQTopLevelObject& right) const;
bool EqualVar(const lua_MQTypeVar& right) const;
bool EqualNil(const sol::lua_nil_t&) const;
static std::string ToString(const lua_MQTopLevelObject& data);
sol::object Call(const std::string& index, sol::this_state L) const;
sol::object CallInt(int index, sol::this_state L) const;
sol::object CallVA(sol::this_state L, sol::variadic_args args) const;
sol::object CallEmpty(sol::this_state L) const;
sol::object Get(sol::stack_object key, sol::this_state L) const;
datatypes::MQ2Type* GetType() const;
private:
const MQTopLevelObject* const self = nullptr;
};
//----------------------------------------------------------------------------
class LuaAbstractDataType;
// A custom DataType implementation that serves as a proxy between the Macro
// interface and the lua bindings.
class LuaProxyType : public MQ2Type
{
public:
LuaProxyType(const std::string& typeName, LuaAbstractDataType* luaType);
virtual ~LuaProxyType();
virtual bool FromData(MQVarPtr& VarPtr, const MQTypeVar& Source) override;
virtual bool FromString(MQVarPtr& VarPTr, const char* Source) override;
virtual void InitVariable(MQVarPtr& VarPtr) override {}
virtual void FreeVariable(MQVarPtr& VarPtr) override {}
virtual bool GetMember(MQVarPtr VarPtr, const char* Member, char* Index, MQTypeVar& Dest) override;
virtual bool ToString(MQVarPtr VarPtr, char* Destination) override;
void RegisterMembers();
private:
LuaAbstractDataType* m_luaType;
};
//----------------------------------------------------------------------------
class LuaTableType : public MQ2Type
{
public:
LuaTableType();
virtual bool GetMember(MQVarPtr VarPtr, const char* Member, char* Index, MQTypeVar& Dest) override;
bool ToString(MQVarPtr VarPtr, char* Destination) override;
};
//----------------------------------------------------------------------------
} // namespace mq::lua::bindings
| 0 | 0.833478 | 1 | 0.833478 | game-dev | MEDIA | 0.311509 | game-dev | 0.568238 | 1 | 0.568238 |
Tuinity/Moonrise | 7,443 | src/main/java/ca/spottedleaf/moonrise/patches/chunk_system/scheduling/task/ChunkLightTask.java | package ca.spottedleaf.moonrise.patches.chunk_system.scheduling.task;
import ca.spottedleaf.concurrentutil.util.Priority;
import ca.spottedleaf.moonrise.common.util.WorldUtil;
import ca.spottedleaf.moonrise.patches.chunk_system.scheduling.ChunkTaskScheduler;
import ca.spottedleaf.moonrise.patches.chunk_system.scheduling.PriorityHolder;
import ca.spottedleaf.moonrise.patches.starlight.light.StarLightEngine;
import ca.spottedleaf.moonrise.patches.starlight.light.StarLightInterface;
import ca.spottedleaf.moonrise.patches.starlight.light.StarLightLightingProvider;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.function.BooleanSupplier;
public final class ChunkLightTask extends ChunkProgressionTask {
private static final Logger LOGGER = LogManager.getLogger();
private final ChunkAccess fromChunk;
private final LightTaskPriorityHolder priorityHolder;
public ChunkLightTask(final ChunkTaskScheduler scheduler, final ServerLevel world, final int chunkX, final int chunkZ,
final ChunkAccess chunk, final Priority priority) {
super(scheduler, world, chunkX, chunkZ);
if (!Priority.isValidPriority(priority)) {
throw new IllegalArgumentException("Invalid priority " + priority);
}
this.priorityHolder = new LightTaskPriorityHolder(priority, this);
this.fromChunk = chunk;
}
@Override
public boolean isScheduled() {
return this.priorityHolder.isScheduled();
}
@Override
public ChunkStatus getTargetStatus() {
return ChunkStatus.LIGHT;
}
@Override
public void schedule() {
this.priorityHolder.schedule();
}
@Override
public void cancel() {
this.priorityHolder.cancel();
}
@Override
public Priority getPriority() {
return this.priorityHolder.getPriority();
}
@Override
public void lowerPriority(final Priority priority) {
this.priorityHolder.raisePriority(priority);
}
@Override
public void setPriority(final Priority priority) {
this.priorityHolder.setPriority(priority);
}
@Override
public void raisePriority(final Priority priority) {
this.priorityHolder.raisePriority(priority);
}
private static final class LightTaskPriorityHolder extends PriorityHolder {
private final ChunkLightTask task;
private LightTaskPriorityHolder(final Priority priority, final ChunkLightTask task) {
super(priority);
this.task = task;
}
@Override
protected void cancelScheduled() {
final ChunkLightTask task = this.task;
task.complete(null, null);
}
@Override
protected Priority getScheduledPriority() {
final ChunkLightTask task = this.task;
return ((StarLightLightingProvider)task.world.getChunkSource().getLightEngine()).starlight$getLightEngine().getServerLightQueue().getPriority(task.chunkX, task.chunkZ);
}
@Override
protected void scheduleTask(final Priority priority) {
final ChunkLightTask task = this.task;
final StarLightInterface starLightInterface = ((StarLightLightingProvider)task.world.getChunkSource().getLightEngine()).starlight$getLightEngine();
final StarLightInterface.ServerLightQueue lightQueue = starLightInterface.getServerLightQueue();
lightQueue.queueChunkLightTask(new ChunkPos(task.chunkX, task.chunkZ), new LightTask(starLightInterface, task), priority);
lightQueue.setPriority(task.chunkX, task.chunkZ, priority);
}
@Override
protected void lowerPriorityScheduled(final Priority priority) {
final ChunkLightTask task = this.task;
final StarLightInterface starLightInterface = ((StarLightLightingProvider)task.world.getChunkSource().getLightEngine()).starlight$getLightEngine();
final StarLightInterface.ServerLightQueue lightQueue = starLightInterface.getServerLightQueue();
lightQueue.lowerPriority(task.chunkX, task.chunkZ, priority);
}
@Override
protected void setPriorityScheduled(final Priority priority) {
final ChunkLightTask task = this.task;
final StarLightInterface starLightInterface = ((StarLightLightingProvider)task.world.getChunkSource().getLightEngine()).starlight$getLightEngine();
final StarLightInterface.ServerLightQueue lightQueue = starLightInterface.getServerLightQueue();
lightQueue.setPriority(task.chunkX, task.chunkZ, priority);
}
@Override
protected void raisePriorityScheduled(final Priority priority) {
final ChunkLightTask task = this.task;
final StarLightInterface starLightInterface = ((StarLightLightingProvider)task.world.getChunkSource().getLightEngine()).starlight$getLightEngine();
final StarLightInterface.ServerLightQueue lightQueue = starLightInterface.getServerLightQueue();
lightQueue.raisePriority(task.chunkX, task.chunkZ, priority);
}
}
private static final class LightTask implements BooleanSupplier {
private final StarLightInterface lightEngine;
private final ChunkLightTask task;
public LightTask(final StarLightInterface lightEngine, final ChunkLightTask task) {
this.lightEngine = lightEngine;
this.task = task;
}
@Override
public boolean getAsBoolean() {
final ChunkLightTask task = this.task;
// executed on light thread
if (!task.priorityHolder.markExecuting()) {
// cancelled
return false;
}
try {
final Boolean[] emptySections = StarLightEngine.getEmptySectionsForChunk(task.fromChunk);
if (task.fromChunk.isLightCorrect() && task.fromChunk.getPersistedStatus().isOrAfter(ChunkStatus.LIGHT)) {
this.lightEngine.forceLoadInChunk(task.fromChunk, emptySections);
this.lightEngine.checkChunkEdges(task.chunkX, task.chunkZ);
} else {
task.fromChunk.setLightCorrect(false);
this.lightEngine.lightChunk(task.fromChunk, emptySections);
task.fromChunk.setLightCorrect(true);
}
// we need to advance status
if (task.fromChunk instanceof ProtoChunk chunk && chunk.getPersistedStatus() == ChunkStatus.LIGHT.getParent()) {
chunk.setPersistedStatus(ChunkStatus.LIGHT);
}
} catch (final Throwable thr) {
LOGGER.fatal(
"Failed to light chunk " + task.fromChunk.getPos().toString()
+ " in world '" + WorldUtil.getWorldName(this.lightEngine.getWorld()) + "'", thr
);
task.complete(null, thr);
return true;
}
task.complete(task.fromChunk, null);
return true;
}
}
}
| 0 | 0.882803 | 1 | 0.882803 | game-dev | MEDIA | 0.553267 | game-dev | 0.963644 | 1 | 0.963644 |
BigBang1112/gbx-net | 3,291 | Src/GBX.NET.Imaging/CGameCtnChallengeExtensions.cs | using System.Drawing;
using System.Drawing.Imaging;
using GBX.NET.Engines.Game;
namespace GBX.NET.Imaging;
/// <summary>
/// Imaging extensions for <see cref="CGameCtnChallenge"/>.
/// </summary>
public static class CGameCtnChallengeExtensions
{
/// <summary>
/// Gets the map thumbnail as <see cref="Bitmap"/>.
/// </summary>
/// <param name="node">CGameCtnChallenge</param>
/// <returns>Thumbnail as <see cref="Bitmap"/>.</returns>
public static Bitmap? GetThumbnailBitmap(this CGameCtnChallenge node)
{
if (node.Thumbnail is null)
{
return null;
}
using var ms = new MemoryStream(node.Thumbnail);
var bitmap = (Bitmap)Image.FromStream(ms);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
return bitmap;
}
/// <summary>
/// Exports the map's thumbnail.
/// </summary>
/// <param name="node">CGameCtnChallenge</param>
/// <param name="stream">Stream to export to.</param>
/// <param name="format">Image format to use.</param>
public static void ExportThumbnail(this CGameCtnChallenge node, Stream stream, ImageFormat format)
{
var thumbnail = GetThumbnailBitmap(node);
if (thumbnail is null)
{
return;
}
if (format == ImageFormat.Jpeg)
{
SaveAsJpeg(stream, thumbnail);
}
else
{
thumbnail.Save(stream, format);
}
}
private static void SaveAsJpeg(Stream stream, Bitmap thumbnail)
{
var encoding = new EncoderParameters(1);
encoding.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
var encoder = ImageCodecInfo.GetImageDecoders().Where(x => x.FormatID == ImageFormat.Jpeg.Guid).First();
thumbnail.Save(stream, encoder, encoding);
}
/// <summary>
/// Exports the map's thumbnail.
/// </summary>
/// <param name="node">CGameCtnChallenge</param>
/// <param name="fileName">File to export to.</param>
/// <param name="format">Image format to use.</param>
public static void ExportThumbnail(this CGameCtnChallenge node, string fileName, ImageFormat format)
{
using var fs = File.Create(fileName);
ExportThumbnail(node, fs, format);
}
/// <summary>
/// Replaces a thumbnail (any popular image format) to use for the map.
/// </summary>
/// <param name="node">CGameCtnChallenge</param>
/// <param name="stream">Stream to import from.</param>
public static Bitmap ImportThumbnail(this CGameCtnChallenge node, Stream stream)
{
var bitmap = new Bitmap(stream);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
using var ms = new MemoryStream();
SaveAsJpeg(ms, bitmap);
node.Thumbnail = ms.ToArray();
return bitmap;
}
/// <summary>
/// Replaces a thumbnail (any popular image format) to use for the map.
/// </summary>
/// <param name="node">CGameCtnChallenge</param>
/// <param name="fileName">File to import from.</param>
public static Bitmap ImportThumbnail(this CGameCtnChallenge node, string fileName)
{
using var fs = File.OpenRead(fileName);
return ImportThumbnail(node, fs);
}
}
| 0 | 0.90245 | 1 | 0.90245 | game-dev | MEDIA | 0.652053 | game-dev,graphics-rendering | 0.68716 | 1 | 0.68716 |
magefree/mage | 1,538 | Mage.Sets/src/mage/cards/s/StreakingOilgorger.java | package mage.cards.s;
import mage.MageInt;
import mage.abilities.common.MaxSpeedAbility;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.HasteAbility;
import mage.abilities.keyword.LifelinkAbility;
import mage.abilities.keyword.StartYourEnginesAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class StreakingOilgorger extends CardImpl {
public StreakingOilgorger(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}");
this.subtype.add(SubType.VAMPIRE);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Haste
this.addAbility(HasteAbility.getInstance());
// Start your engines!
this.addAbility(new StartYourEnginesAbility());
// Max speed -- This creature has lifelink.
this.addAbility(new MaxSpeedAbility(new GainAbilitySourceEffect(
LifelinkAbility.getInstance(), Duration.WhileOnBattlefield
)));
}
private StreakingOilgorger(final StreakingOilgorger card) {
super(card);
}
@Override
public StreakingOilgorger copy() {
return new StreakingOilgorger(this);
}
}
| 0 | 0.835159 | 1 | 0.835159 | game-dev | MEDIA | 0.922444 | game-dev | 0.946146 | 1 | 0.946146 |
PrimeDecomp/prime | 4,681 | src/MetroidPrime/Weapons/CIceBeam.cpp | #include "MetroidPrime/Weapons/CIceBeam.hpp"
#include "MetroidPrime/CStateManager.hpp"
#include "MetroidPrime/SFX/Weapons.h"
#include "Kyoto/Audio/CSfxHandle.hpp"
#include "Kyoto/Particles/CElementGen.hpp"
CIceBeam::CIceBeam(CAssetId characterId, EWeaponType type, TUniqueId playerId,
EMaterialTypes playerMaterial, const CVector3f& scale)
: CGunWeapon(characterId, type, playerId, playerMaterial, scale)
, x21c_iceSmoke(gpSimplePool->GetObj("IceSmoke"))
, x228_ice2nd1(gpSimplePool->GetObj("Ice2nd_1"))
, x234_ice2nd2(gpSimplePool->GetObj("Ice2nd_2"))
, x248_24_loaded(false)
, x248_25_inEndFx(false) {}
CIceBeam::~CIceBeam() {}
void CIceBeam::ReInitVariables() {
x240_smokeGen = nullptr;
x244_chargeFx = nullptr;
x248_24_loaded = false;
x248_25_inEndFx = false;
x1cc_enabledSecondaryEffect = kSFT_None;
}
void CIceBeam::PreRenderGunFx(const CStateManager& mgr, const CTransform4f& xf) {
// Empty
}
void CIceBeam::PostRenderGunFx(const CStateManager& mgr, const CTransform4f& xf) {
bool subtractBlend = mgr.GetThermalDrawFlag() == kTD_Hot;
if (subtractBlend)
CElementGen::SetSubtractBlend(true);
if (x240_smokeGen.get())
x240_smokeGen->Render();
if (x1cc_enabledSecondaryEffect != kSFT_None && x244_chargeFx.get())
x244_chargeFx->Render();
CGunWeapon::PostRenderGunFx(mgr, xf);
if (subtractBlend)
CElementGen::SetSubtractBlend(false);
}
static const char* LBEAM = "LBEAM";
void CIceBeam::UpdateGunFx(bool shotSmoke, float dt, const CStateManager& mgr,
const CTransform4f& xf) {
if (x240_smokeGen.get()) {
CTransform4f beamLoc = x10_solidModelData->GetScaledLocatorTransform(rstl::string_l(LBEAM));
x240_smokeGen->SetTranslation(beamLoc.GetTranslation());
x240_smokeGen->SetOrientation(beamLoc.GetRotation());
x240_smokeGen->Update(dt);
}
if (x244_chargeFx.get()) {
if (x248_25_inEndFx && x244_chargeFx->IsSystemDeletable()) {
x1cc_enabledSecondaryEffect = kSFT_None;
x244_chargeFx = nullptr;
}
if (x1cc_enabledSecondaryEffect != kSFT_None) {
if (x248_25_inEndFx) {
x244_chargeFx->SetTranslation(xf.GetTranslation());
x244_chargeFx->SetOrientation(xf.GetRotation());
} else {
x244_chargeFx->SetGlobalOrientAndTrans(xf);
}
x244_chargeFx->Update(dt);
}
}
CGunWeapon::UpdateGunFx(shotSmoke, dt, mgr, xf);
}
void CIceBeam::Update(float dt, CStateManager& mgr) {
CGunWeapon::Update(dt, mgr);
if (!x248_24_loaded) {
x248_24_loaded = x21c_iceSmoke.IsLoaded() && x228_ice2nd1.IsLoaded() && x234_ice2nd2.IsLoaded();
if (x248_24_loaded) {
x240_smokeGen = rs_new CElementGen(x21c_iceSmoke);
x240_smokeGen->SetGlobalScale(x4_scale);
x240_smokeGen->SetParticleEmission(false);
}
}
}
void CIceBeam::Fire(bool underwater, float dt, CPlayerState::EChargeStage chargeState,
const CTransform4f& xf, CStateManager& mgr, TUniqueId homingTarget,
float chargeFactor1, float chargeFactor2) {
static ushort soundId[2] = {SFXwpn_fire_ice_normal, SFXwpn_fire_ice_charged};
CGunWeapon::Fire(underwater, dt, chargeState, xf, mgr, homingTarget, chargeFactor1,
chargeFactor2);
NWeaponTypes::play_sfx(soundId[size_t(chargeState)], underwater, false, 0x4a);
}
void CIceBeam::Load(CStateManager& mgr, bool subtypeBasePose) {
CGunWeapon::Load(mgr, subtypeBasePose);
x21c_iceSmoke.Lock();
x228_ice2nd1.Lock();
x234_ice2nd2.Lock();
x248_25_inEndFx = false;
}
void CIceBeam::Unload(CStateManager& mgr) {
CGunWeapon::Unload(mgr);
x234_ice2nd2.Unlock();
x228_ice2nd1.Unlock();
x21c_iceSmoke.Unlock();
ReInitVariables();
}
bool CIceBeam::IsLoaded() const { return CGunWeapon::IsLoaded() && x248_24_loaded; }
void CIceBeam::EnableSecondaryFx(ESecondaryFxType type) {
switch (type) {
case kSFT_CancelCharge:
case kSFT_None:
if (x1cc_enabledSecondaryEffect == kSFT_None)
break;
default:
switch (type) {
case kSFT_None:
case kSFT_ToCombo:
case kSFT_CancelCharge:
if (!x248_25_inEndFx) {
x244_chargeFx = rs_new CElementGen(x234_ice2nd2);
x244_chargeFx->SetGlobalScale(x4_scale);
x248_25_inEndFx = true;
x1cc_enabledSecondaryEffect = kSFT_CancelCharge;
}
break;
case kSFT_Charge:
x244_chargeFx = rs_new CElementGen(x228_ice2nd1);
x244_chargeFx->SetGlobalScale(x4_scale);
x1cc_enabledSecondaryEffect = type;
x248_25_inEndFx = false;
break;
}
break;
}
}
void CIceBeam::EnableFx(bool enable) {
if (x240_smokeGen.get())
x240_smokeGen->SetParticleEmission(enable);
}
| 0 | 0.871502 | 1 | 0.871502 | game-dev | MEDIA | 0.258154 | game-dev | 0.926534 | 1 | 0.926534 |
PaddlePaddle/Paddle-Lite-Demo | 12,895 | image_classification/android/app/java/image_classification/app/src/main/java/com/baidu/paddle/lite/demo/image_classification/Predictor.java | package com.baidu.paddle.lite.demo.image_classification;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import com.baidu.paddle.lite.MobileConfig;
import com.baidu.paddle.lite.PaddlePredictor;
import com.baidu.paddle.lite.PowerMode;
import com.baidu.paddle.lite.Tensor;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Vector;
import static android.graphics.Color.blue;
import static android.graphics.Color.green;
import static android.graphics.Color.red;
public class Predictor {
private static final String TAG = Predictor.class.getSimpleName();
public boolean isLoaded = false;
public int warmupIterNum = 1;
public int inferIterNum = 1;
public int cpuThreadNum = 1;
public String cpuPowerMode = "LITE_POWER_HIGH";
public String modelPath = "";
public String modelName = "";
protected PaddlePredictor paddlePredictor = null;
protected float inferenceTime = 0;
// Only for image classification
protected Vector<String> wordLabels = new Vector<String>();
protected String inputColorFormat = "RGB";
protected long[] inputShape = new long[]{1, 3, 224, 224};
protected float[] inputMean = new float[]{0.485f, 0.456f, 0.406f};
protected float[] inputStd = new float[]{0.229f, 0.224f, 0.225f};
protected Bitmap inputImage = null;
protected String top1Result = "";
protected String top2Result = "";
protected String top3Result = "";
protected float preprocessTime = 0;
protected float postprocessTime = 0;
public Predictor() {
}
public boolean init(Context appCtx, String modelPath, String labelPath, int cpuThreadNum, String cpuPowerMode,
String inputColorFormat,
long[] inputShape, float[] inputMean,
float[] inputStd) {
if (inputShape.length != 4) {
Log.i(TAG, "Size of input shape should be: 4");
return false;
}
if (inputMean.length != inputShape[1]) {
Log.i(TAG, "Size of input mean should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputStd.length != inputShape[1]) {
Log.i(TAG, "Size of input std should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputShape[0] != 1) {
Log.i(TAG, "Only one batch is supported in the image classification demo, you can use any batch size in " +
"your Apps!");
return false;
}
if (inputShape[1] != 1 && inputShape[1] != 3) {
Log.i(TAG, "Only one/three channels are supported in the image classification demo, you can use any " +
"channel size in your Apps!");
return false;
}
if (!inputColorFormat.equalsIgnoreCase("RGB") && !inputColorFormat.equalsIgnoreCase("BGR")) {
Log.i(TAG, "Only RGB and BGR color format is supported.");
return false;
}
isLoaded = loadModel(appCtx, modelPath, cpuThreadNum, cpuPowerMode);
if (!isLoaded) {
return false;
}
isLoaded = loadLabel(appCtx, labelPath);
if (!isLoaded) {
return false;
}
this.inputColorFormat = inputColorFormat;
this.inputShape = inputShape;
this.inputMean = inputMean;
this.inputStd = inputStd;
return true;
}
protected boolean loadModel(Context appCtx, String modelPath, int cpuThreadNum, String cpuPowerMode) {
// Release model if exists
releaseModel();
// Load model
if (modelPath.isEmpty()) {
return false;
}
String realPath = modelPath;
if (!modelPath.substring(0, 1).equals("/")) {
// Read model files from custom path if the first character of mode path is '/'
// otherwise copy model to cache from assets
realPath = appCtx.getCacheDir() + "/" + modelPath;
// push model to mobile
Utils.copyDirectoryFromAssets(appCtx, modelPath, realPath);
}
if (realPath.isEmpty()) {
return false;
}
MobileConfig config = new MobileConfig();
config.setModelFromFile(realPath + File.separator + "model.nb");
config.setThreads(cpuThreadNum);
if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_HIGH")) {
config.setPowerMode(PowerMode.LITE_POWER_HIGH);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_LOW")) {
config.setPowerMode(PowerMode.LITE_POWER_LOW);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_FULL")) {
config.setPowerMode(PowerMode.LITE_POWER_FULL);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_NO_BIND")) {
config.setPowerMode(PowerMode.LITE_POWER_NO_BIND);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_RAND_HIGH")) {
config.setPowerMode(PowerMode.LITE_POWER_RAND_HIGH);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_RAND_LOW")) {
config.setPowerMode(PowerMode.LITE_POWER_RAND_LOW);
} else {
Log.e(TAG, "Unknown cpu power mode!");
return false;
}
paddlePredictor = PaddlePredictor.createPaddlePredictor(config);
this.cpuThreadNum = cpuThreadNum;
this.cpuPowerMode = cpuPowerMode;
this.modelPath = realPath;
this.modelName = realPath.substring(realPath.lastIndexOf("/") + 1);
return true;
}
public void releaseModel() {
paddlePredictor = null;
isLoaded = false;
cpuThreadNum = 1;
cpuPowerMode = "LITE_POWER_HIGH";
modelPath = "";
modelName = "";
}
protected boolean loadLabel(Context appCtx, String labelPath) {
wordLabels.clear();
// Load word labels from file
try {
InputStream assetsInputStream = appCtx.getAssets().open(labelPath);
int available = assetsInputStream.available();
byte[] lines = new byte[available];
assetsInputStream.read(lines);
assetsInputStream.close();
String words = new String(lines);
String[] contents = words.split("\n");
for (String content : contents) {
int first_space_pos = content.indexOf(" ");
if (first_space_pos >= 0 && first_space_pos < content.length()) {
wordLabels.add(content.substring(first_space_pos));
}
}
Log.i(TAG, "Word label size: " + wordLabels.size());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
}
return true;
}
public Tensor getInput(int idx) {
if (!isLoaded()) {
return null;
}
return paddlePredictor.getInput(idx);
}
public Tensor getOutput(int idx) {
if (!isLoaded()) {
return null;
}
return paddlePredictor.getOutput(idx);
}
public boolean preProcess(){
// Set input shape
Tensor inputTensor = getInput(0);
inputTensor.resize(inputShape);
Date start = new Date();
int channels = (int) inputShape[1];
int width = (int) inputShape[3];
int height = (int) inputShape[2];
float[] inputData = new float[channels * width * height];
if (channels == 3) {
int[] channelIdx = null;
if (inputColorFormat.equalsIgnoreCase("RGB")) {
channelIdx = new int[]{0, 1, 2};
} else if (inputColorFormat.equalsIgnoreCase("BGR")) {
channelIdx = new int[]{2, 1, 0};
} else {
Log.i(TAG, "Unknown color format " + inputColorFormat + ", only RGB and BGR color format is " +
"supported!");
return false;
}
int[] channelStride = new int[]{width * height, width * height * 2};
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int color = inputImage.getPixel(x, y);
float[] rgb = new float[]{(float) red(color) / 255.0f, (float) green(color) / 255.0f,
(float) blue(color) / 255.0f};
inputData[y * width + x] = (rgb[channelIdx[0]] - inputMean[0]) / inputStd[0];
inputData[y * width + x + channelStride[0]] = (rgb[channelIdx[1]] - inputMean[1]) / inputStd[1];
inputData[y * width + x + channelStride[1]] = (rgb[channelIdx[2]] - inputMean[2]) / inputStd[2];
}
}
} else if (channels == 1) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int color = inputImage.getPixel(x, y);
float gray = (float) (red(color) + green(color) + blue(color)) / 3.0f / 255.0f;
inputData[y * width + x] = (gray - inputMean[0]) / inputStd[0];
}
}
} else {
Log.i(TAG, "Unsupported channel size " + Integer.toString(channels) + ", only channel 1 and 3 is " +
"supported!");
return false;
}
inputTensor.setData(inputData);
Date end = new Date();
preprocessTime = (float) (end.getTime() - start.getTime());
return true;
}
public void postProcess() {
Tensor outputTensor = getOutput(0);
long outputShape[] = outputTensor.shape();
Date start = new Date();
long outputSize = 1;
for (long s : outputShape) {
outputSize *= s;
}
int[] max_index = new int[3]; // Top3 indices
double[] max_num = new double[3]; // Top3 scores
for (int i = 0; i < outputSize; i++) {
float tmp = outputTensor.getFloatData()[i];
int tmp_index = i;
for (int j = 0; j < 3; j++) {
if (tmp > max_num[j]) {
tmp_index += max_index[j];
max_index[j] = tmp_index - max_index[j];
tmp_index -= max_index[j];
tmp += max_num[j];
max_num[j] = tmp - max_num[j];
tmp -= max_num[j];
}
}
}
Date end = new Date();
postprocessTime = (float) (end.getTime() - start.getTime());
if (wordLabels.size() > 0) {
top1Result = "Top1: " + wordLabels.get(max_index[0]) + " - " + String.format("%.3f", max_num[0]);
top2Result = "Top2: " + wordLabels.get(max_index[1]) + " - " + String.format("%.3f", max_num[1]);
top3Result = "Top3: " + wordLabels.get(max_index[2]) + " - " + String.format("%.3f", max_num[2]);
}
}
public boolean runModel() {
if (inputImage == null || !isLoaded()) {
return false;
}
// Set input shape
boolean pre_val = preProcess();
if (!pre_val){
return false;
}
// Warm up
for (int i = 0; i < warmupIterNum; i++) {
paddlePredictor.run();
}
// Run inference
Date start = new Date();
for (int i = 0; i < inferIterNum; i++) {
paddlePredictor.run();
}
Date end = new Date();
inferenceTime = (end.getTime() - start.getTime()) / (float) inferIterNum;
// Fetch output tensor
postProcess();
return true;
}
public boolean isLoaded() {
return paddlePredictor != null && isLoaded;
}
public String modelPath() {
return modelPath;
}
public String modelName() {
return modelName;
}
public int cpuThreadNum() {
return cpuThreadNum;
}
public String cpuPowerMode() {
return cpuPowerMode;
}
public float inferenceTime() {
return inferenceTime;
}
public Bitmap inputImage() {
return inputImage;
}
public String top1Result() {
return top1Result;
}
public String top2Result() {
return top2Result;
}
public String top3Result() {
return top3Result;
}
public float preprocessTime() {
return preprocessTime;
}
public float postprocessTime() {
return postprocessTime;
}
public void setInputImage(Bitmap image) {
if (image == null) {
return;
}
// Scale image to the size of input tensor
Bitmap rgbaImage = image.copy(Bitmap.Config.ARGB_8888, true);
Bitmap scaleImage = Bitmap.createScaledBitmap(rgbaImage, (int) inputShape[3], (int) inputShape[2], true);
this.inputImage = scaleImage;
}
}
| 0 | 0.884128 | 1 | 0.884128 | game-dev | MEDIA | 0.298689 | game-dev | 0.956637 | 1 | 0.956637 |
MassiveCraft/MassiveCore | 1,252 | src/com/massivecraft/massivecore/command/type/TypeWorldId.java | package com.massivecraft.massivecore.command.type;
import com.massivecraft.massivecore.mixin.MixinWorld;
import org.bukkit.command.CommandSender;
import java.util.Collection;
public class TypeWorldId extends TypeAbstractChoice<String>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static TypeWorldId i = new TypeWorldId();
public static TypeWorldId get() { return i; }
public TypeWorldId() { super(String.class); }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String getName()
{
return "world";
}
@Override
public String getVisualInner(String value, CommandSender sender)
{
return MixinWorld.get().getWorldDisplayName(value);
}
@Override
public String getNameInner(String value)
{
return MixinWorld.get().getWorldAliasOrId(value);
}
@Override
public String getIdInner(String value)
{
return value;
}
@Override
public Collection<String> getAll()
{
return MixinWorld.get().getWorldIds();
}
@Override
public boolean canSee(String value, CommandSender sender)
{
return MixinWorld.get().canSeeWorld(sender, value);
}
}
| 0 | 0.753941 | 1 | 0.753941 | game-dev | MEDIA | 0.946616 | game-dev | 0.828973 | 1 | 0.828973 |
MagerValp/u4remastered | 13,392 | src/patchedgame/use_towne.s | .include "uscii.i"
player_xpos = $0010
player_ypos = $0011
tile_xpos = $0012
tile_ypos = $0013
map_x = $0014
map_y = $0015
new_x = $0016
new_y = $0017
britannia_x = $0018
britannia_y = $0019
current_location = $001a
game_mode = $001b
dungeon_level = $001c
balloon_flying = $001d
player_transport = $001e
party_size = $001f
dng_direction = $0020
light_duration = $0021
moon_phase_trammel = $0022
moon_phase_felucca = $0023
horse_mode = $0024
player_has_spoken_to_lb = $0025
last_humility_check = $0027
altar_room_principle = $0028
last_found_reagent = $002a
ship_hull = $002b
move_counter = $002c
key_buf = $0030
key_buf_len = $0038
charptr = $003d
magic_aura = $0046
aura_duration = $0047
tile_under_player = $0048
tile_north = $0049
tile_south = $004a
tile_east = $004b
tile_west = $004c
music_volume = $004d
console_xpos = $004e
console_ypos = $004f
diskid = $0050
numdrives = $0051
currdisk_drive1 = $0052
currdisk_drive2 = $0053
currplayer = $0054
hexnum = $0056
bcdnum = $0057
zptmp1 = $005a
damage = $005c
reqdisk = $005e
currdrive = $005f
lt_y = $0060
lt_x = $0061
lt_rwflag = $0062
lt_addr_hi = $0063
monster_type = $0066
game_mode_temp = $0068
moongate_tile = $006d
moongate_xpos = $006e
moongate_ypos = $006f
tilerow = $0072
movement_mode = $0074
direction = $0075
delta_x = $0078
delta_y = $0079
temp_x = $007a
temp_y = $007b
ptr2 = $007c
ptr1 = $007e
j_waitkey = $0800
j_player_teleport = $0803
j_move_east = $0806
j_move_west = $0809
j_move_south = $080c
j_move_north = $080f
j_drawinterface = $0812
j_drawview = $0815
j_update_britannia = $0818
j_primm_xy = $081e
j_primm = $0821
j_console_out = $0824
j_clearbitmap = $0827
j_mulax = $082a
j_get_stats_ptr = $082d
j_printname = $0830
j_printbcd = $0833
j_drawcursor = $0836
j_drawcursor_xy = $0839
j_drawvert = $083c
j_drawhoriz = $083f
j_request_disk = $0842
j_update_status = $0845
j_blocked_tile = $0848
j_update_view = $084b
j_rand = $084e
j_loadsector = $0851
j_playsfx = $0854
j_update_view_combat = $0857
j_getnumber = $085a
j_getplayernum = $085d
j_update_wind = $0860
j_animate_view = $0863
j_printdigit = $0866
j_clearstatwindow = $0869
j_animate_creatures = $086c
j_centername = $086f
j_print_direction = $0872
j_clearview = $0875
j_invertview = $0878
j_centerstring = $087b
j_printstring = $087e
j_gettile_bounds = $0881
j_gettile_britannia = $0884
j_gettile_opposite = $0887
j_gettile_currmap = $088a
j_gettile_tempmap = $088d
j_get_player_tile = $0890
j_gettile_towne = $0893
j_gettile_dungeon = $0896
div32 = $1572
div16 = $1573
mul32 = $1578
mul16 = $1579
j_fileio = $a100
j_readblock = $a103
j_loadtitle = $a106
j_togglesnd = $a109
j_kernalin = $a10c
j_setirqv = $a10f
j_clearkbd = $a112
j_irqhandler = $a115
party_stats = $aa00
virtues_and_stats = $ab00
torches = $ab08
gems = $ab09
keys = $ab0a
sextant = $ab0b
stones = $ab0c
runes = $ab0d
items = $ab0e
threepartkey = $ab0f
food_hi = $ab10
food_lo = $ab11
food_frac = $ab12
gold = $ab13
horn = $ab15
wheel = $ab16
skull = $ab17
armour = $ab18
weapons = $ab20
reagents = $ab38
mixtures = $ab40
map_status = $ac00
object_xpos = $ac20
object_ypos = $ac40
object_tile = $ac60
currmap = $ae00
tempmap = $ae80
inbuffer = $af00
music_ctl = $af20
music_nop = $af23
bmplineaddr_lo = $e000
bmplineaddr_hi = $e0c0
chrlineaddr_lo = $e180
chrlineaddr_hi = $e198
tile_color = $e1b0
music_init = $ec00
.segment "OVERLAY"
use:
jsr j_primm
.byte "Which item:", $8d
.byte 0
jsr get_input
jsr compare_keywords
bpl keyword_matched
jsr j_primm
.byte $8d
.byte "Not usable item!", $8d
.byte 0
rts
print_none_owned:
jsr j_primm
.byte $8d
.byte "None owned!", $8d
.byte 0
rts
print_no_effect:
jsr j_primm
.byte $8d
.byte "Hmm...No effect!", $8d
.byte 0
rts
keyword_matched:
asl a
tay
lda keyword_handlers,y
sta ptr1
lda keyword_handlers+1,y
sta ptr1+1
jmp (ptr1)
keyword_handlers:
.addr use_stone
.addr use_bell
.addr use_book
.addr use_candle
.addr use_key
.addr use_horn
.addr use_wheel
.addr use_skull
use_stone:
lda stones
bne @have_stone
jmp print_none_owned
@have_stone:
jsr j_primm
.byte $8d
.byte "No place to", $8d
.byte "use them!", $8d
.byte 0
rts
use_bell:
lda items
and #$04
bne @have_bell
jmp print_none_owned
@have_bell:
jmp print_no_effect
use_book:
lda items
and #$02
bne @have_book
jmp print_none_owned
@have_book:
jmp print_no_effect
use_candle:
lda items
and #$01
bne @have_candle
jmp print_none_owned
@have_candle:
jmp print_no_effect
use_key:
lda threepartkey
bne @have_key
jmp print_none_owned
@have_key:
jmp print_no_effect
use_horn:
lda horn
bne @have_horn
jmp print_none_owned
@have_horn:
jmp print_no_effect
use_wheel:
lda wheel
bne @have_wheel
jmp print_none_owned
@have_wheel:
jmp print_no_effect
use_skull:
lda skull
cmp #$01
beq @have_skull
jmp print_none_owned
@have_skull:
jsr j_primm
.byte $8d
.byte "You hold the", $8d
.byte "evil skull of", $8d
.byte "Mondain the", $8d
.byte "wizard aloft....", $8d
.byte 0
ldx #$1f
@clear:
lda #$00
ldy object_tile,x
cpy #$5e
beq @lord_british
sta object_tile,x
sta map_status,x
sta $acc0,x
sta $ace0,x
jmp @skip
@lord_british:
lda #$ff
sta $acc0,x
@skip:
dex
bpl @clear
jsr shake_screen
jsr j_invertview
jsr shake_screen
jsr j_invertview
jsr shake_screen
jsr j_update_view
lda #$07
sta $6a
@next_virtue:
ldy $6a
lda #$05
jsr dec_virtue
dec $6a
bpl @next_virtue
jsr j_update_status
rts
get_input:
lda #$bf
jsr j_console_out
lda #$00
sta $6a
@get_char:
jsr j_waitkey
cmp #$8d
beq @got_input
cmp #$94
beq @backspace
cmp #$a0
bcc @get_char
ldx $6a
sta inbuffer,x
jsr j_console_out
inc $6a
lda $6a
cmp #$0f
bcc @get_char
bcs @got_input
@backspace:
lda $6a
beq @get_char
dec $6a
dec console_xpos
lda #$a0
jsr j_console_out
dec console_xpos
jmp @get_char
@got_input:
ldx $6a
lda #$a0
@pad_spaces:
sta inbuffer,x
inx
cpx #$06
bcc @pad_spaces
lda #$8d
jsr j_console_out
rts
compare_keywords:
lda #$07
sta $6a
@next:
lda $6a
asl a
asl a
tay
ldx #$00
@compare:
lda keywords,y
cmp inbuffer,x
bne @nomatch
iny
inx
cpx #$04
bcc @compare
lda $6a
rts
@nomatch:
dec $6a
bpl @next
lda $6a
rts
keywords:
.byte "STON"
.byte "BELL"
.byte "BOOK"
.byte "CAND"
.byte "KEY "
.byte "HORN"
.byte "WHEE"
.byte "SKUL"
shake_screen:
lda #$06
jsr j_playsfx
jsr shake_up
jsr shake_down
jsr shake_up
jsr shake_down
jsr shake_up
jsr shake_down
jsr shake_up
jsr shake_down
rts
shake_down:
ldx #$ae
@next:
lda bmplineaddr_lo+9,x
sta ptr1
lda bmplineaddr_hi+9,x
sta ptr1+1
lda bmplineaddr_lo+7,x
sta ptr2
lda bmplineaddr_hi+7,x
sta ptr2+1
ldy #$b0
@copy:
lda (ptr2),y
sta (ptr1),y
tya
sec
sbc #$08
tay
bne @copy
jsr j_rand
bmi @skip
jsr j_togglesnd
@skip:
dex
bne @next
rts
shake_up:
ldx #$00
@next:
lda bmplineaddr_lo+8,x
sta ptr1
lda bmplineaddr_hi+8,x
sta ptr1+1
lda bmplineaddr_lo+10,x
sta ptr2
lda bmplineaddr_hi+10,x
sta ptr2+1
ldy #$b0
@copy:
lda (ptr2),y
sta (ptr1),y
tya
sec
sbc #$08
tay
bne @copy
jsr j_rand
bmi @skip
jsr j_togglesnd
@skip:
inx
cpx #$ae
bcc @next
rts
dec_virtue:
sta zptmp1
sty $59
lda virtues_and_stats,y
beq @lost_an_eight
@continue:
sed
sec
sbc zptmp1
beq @underflow
bcs @store
@underflow:
lda #$01
@store:
sta virtues_and_stats,y
cld
rts
@lost_an_eight:
jsr j_primm
.byte $8d
.byte "THOU HAST LOST", $8d
.byte "AN EIGHTH!", $8d
.byte 0
lda #$99
ldy $59
jmp @continue
@_garbage:
.byte $CE,$8D,$C9,$CE,$D4,$CF,$A0,$D4 ; 8ABE NMINTO T
.byte $C8,$C5,$A0,$C1,$C2,$D9,$D3,$D3 ; 8AC6 HE ABYSS
.byte $A1,$8D,$00,$A9,$FF,$8D,$17,$AB ; 8ACE !M.).MW+
.byte $A9,$07,$85,$6A,$A0,$6A,$A9,$10 ; 8AD6 )GEj j)P
.byte $20,$04,$8C,$C6,$6A,$10,$F5,$20 ; 8ADE DLFjPu
.byte $86,$8B,$20,$78,$08,$20,$86,$8B ; 8AE6 FK xH FK
.byte $20,$78,$08,$20,$86,$8B,$60,$A9 ; 8AEE xH FK`)
.byte $BF,$20,$24,$08,$A9,$00,$85,$6A ; 8AF6 ? $H).Ej
.byte $20,$00,$08,$C9,$8D,$F0,$2C,$C9 ; 8AFE .HIMp,I
.byte $94,$F0,$16,$C9,$A0,$90,$F1,$A6 ; 8B06 TpVI Pq&
.byte $6A,$9D,$00,$AF,$20,$24,$08,$E6 ; 8B0E j]./ $Hf
.byte $6A,$A5,$6A,$C9,$0F,$90,$E1,$B0 ; 8B16 j%jIOPa0
.byte $12,$A5,$6A,$F0,$DB,$C6,$6A,$C6 ; 8B1E R%jp[FjF
.byte $4E,$A9,$A0,$20,$24,$08,$C6,$4E ; 8B26 N) $HFN
.byte $4C,$FE,$8A,$A6,$6A,$A9,$A0,$9D ; 8B2E L~J&j) ]
.byte $00,$AF,$E8,$E0,$06,$90,$F8,$A9 ; 8B36 ./h`FPx)
.byte $8D,$20,$24,$08,$60,$A9,$07,$85 ; 8B3E M $H`)GE
.byte $6A,$A5,$6A,$0A,$0A,$A8,$A2,$00 ; 8B46 j%jJJ(".
.byte $B9,$66,$8B,$DD,$00,$AF,$D0,$09 ; 8B4E 9fK]./PI
.byte $C8,$E8,$E0,$04,$90,$F2,$A5,$6A ; 8B56 Hh`DPr%j
.byte $60,$C6,$6A,$10,$E4,$A5,$6A,$60 ; 8B5E `FjPd%j`
.byte $D3,$D4,$CF,$CE,$C2,$C5,$CC,$CC ; 8B66 STONBELL
.byte $C2,$CF,$CF,$CB,$C3,$C1,$CE,$C4 ; 8B6E BOOKCAND
.byte $CB,$C5,$D9,$A0,$C8,$CF,$D2,$CE ; 8B76 KEY HORN
.byte $D7,$C8,$C5,$C5,$D3,$CB,$D5,$CC ; 8B7E WHEESKUL
.byte $A9,$06,$20,$54,$08,$20,$D3,$8B ; 8B86 )F TH SK
.byte $20,$A4,$8B,$20,$D3,$8B,$20,$A4 ; 8B8E $K SK $
.byte $8B,$20,$D3,$8B,$20,$A4,$8B,$20 ; 8B96 K SK $K
.byte $D3,$8B,$20,$A4,$8B,$60,$A2,$AE ; 8B9E SK $K`".
.byte $BD,$09,$E0,$85,$7E,$BD,$C9,$E0 ; 8BA6 =I`E~=I`
.byte $85,$7F,$BD,$07,$E0,$85,$7C,$BD ; 8BAE E.=G`E|=
.byte $C7,$E0,$85,$7D,$A0,$B0,$B1,$7C ; 8BB6 G`E} 01|
.byte $91,$7E,$98,$38,$E9,$08,$A8,$D0 ; 8BBE Q~X8iH(P
.byte $F5,$20,$4E,$08,$30,$03,$2C,$09 ; 8BC6 u NH0C,I
.byte $A1,$CA,$D0,$D4,$60,$A2,$00,$BD ; 8BCE !JPT`".=
.byte $08,$E0,$85,$7E,$BD,$C8,$E0,$85 ; 8BD6 H`E~=H`E
.byte $7F,$BD,$0A,$E0,$85,$7C,$BD,$CA ; 8BDE .=J`E|=J
.byte $E0,$85,$7D,$A0,$B0,$B1,$7C,$91 ; 8BE6 `E} 01|Q
.byte $7E,$98,$38,$E9,$08,$A8,$D0,$F5 ; 8BEE ~X8iH(Pu
.byte $20,$4E,$08,$30,$03,$2C,$09,$A1 ; 8BF6 NH0C,I!
.byte $E8,$E0,$AE,$90,$D2,$60,$85,$59 ; 8BFE h`.PR`EY
.byte $F8,$18,$B9,$00,$AB,$F0,$06,$65 ; 8C06 xX9.+pFe
.byte $59,$90,$02,$A9,$99,$99,$00,$AB ; 8C0E YPB)YY.+
.byte $D8,$60,$85,$5A,$84,$59,$B9,$00 ; 8C16 X`EZDY9.
.byte $AB,$F0,$0F,$F8,$38,$E5,$5A,$F0 ; 8C1E +pOx8eZp
.byte $02,$B0,$02,$A9,$01,$99,$00,$AB ; 8C26 B0B)AY.+
.byte $D8,$60,$20,$21,$08,$8D,$D4,$C8 ; 8C2E X` !HMTH
.byte $CF,$D5,$A0,$C8,$C1,$D3,$D4,$A0 ; 8C36 OU HAST
.byte $CC,$CF,$D3,$D4,$8D,$C1,$CE,$A0 ; 8C3E LOSTMAN
.byte $C5,$C9,$C7,$C8,$D4,$C8,$A1,$8D ; 8C46 EIGHTH!M
.byte $00,$A9,$99,$A4,$59,$4C,$21,$8C ; 8C4E .)Y$YL!L
.byte $00,$20,$54,$08,$20,$23,$83,$A5 ; 8C56 . TH #C%
.byte $24,$F0,$06,$20,$9D,$44,$20,$4B ; 8C5E $pF ]D K
.byte $08,$20,$9D,$44,$4C,$2E,$62,$A9 ; 8C66 H ]DL.b)
.byte $10,$85,$1E,$20,$AF,$45,$20,$23 ; 8C6E PE^ /E #
.byte $83,$4C,$2E,$62,$20,$B9,$45,$20 ; 8C76 CL.b 9E
.byte $23,$83,$A5,$4C,$20,$B9,$46,$10 ; 8C7E #C%L 9FP
.byte $03,$4C,$EE,$41,$A9,$00,$20,$96 ; 8C86 CLnA). V
.byte $6A,$F0,$06,$20,$74,$41,$4C,$2E ; 8C8E jpF tAL.
.byte $62,$20,$09,$08,$4C,$2E,$62,$A5 ; 8C96 b IHL.b%
.byte $4C,$20,$48,$08,$10,$05,$68,$68 ; 8C9E L HHPEhh
.byte $4C,$EE,$41,$A5,$4C,$20,$84,$46 ; 8CA6 LnA%L DF
.byte $F0,$06,$20,$74,$41,$4C,$D4,$44 ; 8CAE pF tALTD
.byte $A9,$00,$20,$54,$08,$A5,$1B,$C9 ; 8CB6 ). TH%[I
.byte $01,$D0,$08,$20,$09,$08,$A5,$4C ; 8CBE APH IH%L
.byte $4C,$76,$86,$C6,$10,$A5,$10,$10 ; 8CC6 LvFFP%PP
.byte $05,$68,$68,$4C,$1D,$46,$60,$A5 ; 8CCE EhhL]F`%
.byte $1B,$C9,$03,$D0,$1F,$20,$AF,$45 ; 8CD6 [ICP_ /E
.byte $20,$21,$08,$F2,$E9,$E7,$E8,$F4 ; 8CDE !Hright
.byte $8D,$00,$18,$A5,$20,$69,$01,$29 ; 8CE6 M.X% iA)
.byte $03,$85,$20,$20,$00,$8C,$20,$72 ; 8CEE CE .L r
.byte $08,$4C,$7B,$40,$A5,$1E,$C9,$18 ; 8CF6 HL{@%^IX
.byte $D0,$03,$F9,$A0,$ED,$E1,$F9,$A0 ; 8CFE PCy may
.byte $E2,$E5,$8D,$EC,$EF,$F3,$F4,$A0 ; 8D06 beMlost
.byte $E6,$EF,$F2,$E5,$F6,$E5,$F2,$AE ; 8D0E forever.
.byte $00,$20,$7D,$91,$20,$21,$08,$8D ; 8D16 . }Q !HM
.byte $8D,$D2,$E5,$F4,$F5,$F2,$EE,$A0 ; 8D1E MReturn
.byte $EE,$EF,$F7,$A0,$F5,$EE,$F4,$EF ; 8D26 now unto
.byte $8D,$F4,$E8,$E9,$EE,$E5,$A0,$EF ; 8D2E Mthine o
.byte $F7,$EE,$A0,$F7,$EF,$F2,$EC,$E4 ; 8D36 wn world
.byte $AC,$8D,$EC,$E9,$F6,$E5,$A0,$F4 ; 8D3E ,Mlive t
.byte $E8,$E5,$F2,$E5,$A0,$E1,$F3,$A0 ; 8D46 here as
.byte $E1,$EE,$8D,$E5,$F8,$E1,$ED,$F0 ; 8D4E anMexamp
.byte $EC,$E5,$A0,$F4,$EF,$A0,$F4,$E8 ; 8D56 le to th
.byte $F9,$8D,$F0,$E5,$EF,$F0,$EC,$E5 ; 8D5E yMpeople
.byte $AC,$A0,$E1,$F3,$A0,$EF,$F5,$F2 ; 8D66 , as our
.byte $8D,$ED,$E5,$ED,$EF,$F2,$F9,$A0 ; 8D6E Mmemory
.byte $EF,$E6,$A0,$F4,$E8,$F9,$8D,$E7 ; 8D76 of thyMg
.byte $E1,$EC,$EC,$E1,$EE,$F4,$A0,$E4 ; 8D7E allant d
.byte $E5,$E5,$E4,$F3,$8D,$F3,$E5,$F2 ; 8D86 eedsMser
.byte $F6,$E5,$F3,$A0,$F5,$F3,$AE,$00 ; 8D8E ves us..
.byte $20,$7D,$91,$20,$75,$08,$20,$CF ; 8D96 }Q uH O
.byte $92,$20,$21,$08,$8D,$8D,$C1,$F3 ; 8D9E R !HMMAs
.byte $A0,$F4,$E8,$E5,$A0,$F3,$EF,$F5 ; 8DA6 the sou
.byte $EE,$E4,$A0,$EF,$E6,$8D,$F4,$E8 ; 8DAE nd ofMth
.byte $E5,$A0,$F6,$EF,$E9,$E3,$E5,$A0 ; 8DB6 e voice
.byte $F4,$F2,$E1,$E9,$EC,$F3,$8D,$EF ; 8DBE trailsMo
.byte $E6,$E6,$AC,$A0,$E4,$E1,$F2,$EB ; 8DC6 ff, dark
.byte $EE,$E5,$F3,$F3,$8D,$F3,$E5,$E5 ; 8DCE nessMsee
.byte $ED,$F3,$A0,$F4,$EF,$A0,$F2,$E9 ; 8DD6 ms to ri
.byte $F3,$E5,$8D,$E1,$F2,$EF,$F5,$EE ; 8DDE seMaroun
.byte $E4,$A0,$F9,$EF,$F5,$AE,$8D,$D4 ; 8DE6 d you.MT
.byte $E8,$E5,$F2,$E5,$A0,$E9,$F3,$A0 ; 8DEE here is
.byte $E1,$8D,$ED,$EF,$ED,$E5,$EE,$F4 ; 8DF6 aMmoment
.byte $A0,$EF ; 8DFE o
| 0 | 0.861055 | 1 | 0.861055 | game-dev | MEDIA | 0.783015 | game-dev | 0.726163 | 1 | 0.726163 |
arscan/encom-globe | 5,702 | src/SmokeProvider.js | var THREE = require('three'),
utils = require('./utils');
var vertexShader = [
"#define PI 3.141592653589793238462643",
"#define DISTANCE 500.0",
"attribute float myStartTime;",
"attribute float myStartLat;",
"attribute float myStartLon;",
"attribute float altitude;",
"attribute float active;",
"uniform float currentTime;",
"uniform vec3 color;",
"varying vec4 vColor;",
"",
"vec3 getPos(float lat, float lon)",
"{",
" if (lon < -180.0){",
" lon = lon + 360.0;",
" }",
" float phi = (90.0 - lat) * PI / 180.0;",
" float theta = (180.0 - lon) * PI / 180.0;",
" float x = DISTANCE * sin(phi) * cos(theta) * altitude;",
" float y = DISTANCE * cos(phi) * altitude;",
" float z = DISTANCE * sin(phi) * sin(theta) * altitude;",
" return vec3(x, y, z);",
"}",
"",
"void main()",
"{",
" float dt = currentTime - myStartTime;",
" if (dt < 0.0){",
" dt = 0.0;",
" }",
" if (dt > 0.0 && active > 0.0) {",
" dt = mod(dt,1500.0);",
" }",
" float opacity = 1.0 - dt/ 1500.0;",
" if (dt == 0.0 || active == 0.0){",
" opacity = 0.0;",
" }",
" vec3 newPos = getPos(myStartLat, myStartLon - ( dt / 50.0));",
" vColor = vec4( color, opacity );", // set color associated to vertex; use later in fragment shader.
" vec4 mvPosition = modelViewMatrix * vec4( newPos, 1.0 );",
" gl_PointSize = 2.5 - (dt / 1500.0);",
" gl_Position = projectionMatrix * mvPosition;",
"}"
].join("\n");
var fragmentShader = [
"varying vec4 vColor;",
"void main()",
"{",
" gl_FragColor = vColor;",
" float depth = gl_FragCoord.z / gl_FragCoord.w;",
" float fogFactor = smoothstep(1500.0, 1800.0, depth );",
" vec3 fogColor = vec3(0.0);",
" gl_FragColor = mix( vColor, vec4( fogColor, gl_FragColor.w), fogFactor );",
"}"
].join("\n");
var SmokeProvider = function(scene, _opts){
/* options that can be passed in */
var opts = {
smokeCount: 5000,
smokePerPin: 30,
smokePerSecond: 20
}
if(_opts){
for(var i in opts){
if(_opts[i] !== undefined){
opts[i] = _opts[i];
}
}
}
this.opts = opts;
this.geometry = new THREE.Geometry();
this.attributes = {
myStartTime: {type: 'f', value: []},
myStartLat: {type: 'f', value: []},
myStartLon: {type: 'f', value: []},
altitude: {type: 'f', value: []},
active: {type: 'f', value: []}
};
this.uniforms = {
currentTime: { type: 'f', value: 0.0},
color: { type: 'c', value: new THREE.Color("#aaa")},
}
var material = new THREE.ShaderMaterial( {
uniforms: this.uniforms,
attributes: this.attributes,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: true
});
for(var i = 0; i< opts.smokeCount; i++){
var vertex = new THREE.Vector3();
vertex.set(0,0,0);
this.geometry.vertices.push( vertex );
this.attributes.myStartTime.value[i] = 0.0;
this.attributes.myStartLat.value[i] = 0.0;
this.attributes.myStartLon.value[i] = 0.0;
this.attributes.altitude.value[i] = 0.0;
this.attributes.active.value[i] = 0.0;
}
this.attributes.myStartTime.needsUpdate = true;
this.attributes.myStartLat.needsUpdate = true;
this.attributes.myStartLon.needsUpdate = true;
this.attributes.altitude.needsUpdate = true;
this.attributes.active.needsUpdate = true;
this.smokeIndex = 0;
this.totalRunTime = 0;
scene.add( new THREE.ParticleSystem( this.geometry, material));
};
SmokeProvider.prototype.setFire = function(lat, lon, altitude){
var point = utils.mapPoint(lat, lon);
/* add the smoke */
var startSmokeIndex = this.smokeIndex;
for(var i = 0; i< this.opts.smokePerPin; i++){
this.geometry.vertices[this.smokeIndex].set(point.x * altitude, point.y * altitude, point.z * altitude);
this.geometry.verticesNeedUpdate = true;
this.attributes.myStartTime.value[this.smokeIndex] = this.totalRunTime + (1000*i/this.opts.smokePerSecond + 1500);
this.attributes.myStartLat.value[this.smokeIndex] = lat;
this.attributes.myStartLon.value[this.smokeIndex] = lon;
this.attributes.altitude.value[this.smokeIndex] = altitude;
this.attributes.active.value[this.smokeIndex] = 1.0;
this.attributes.myStartTime.needsUpdate = true;
this.attributes.myStartLat.needsUpdate = true;
this.attributes.myStartLon.needsUpdate = true;
this.attributes.altitude.needsUpdate = true;
this.attributes.active.needsUpdate = true;
this.smokeIndex++;
this.smokeIndex = this.smokeIndex % this.geometry.vertices.length;
}
return startSmokeIndex;
};
SmokeProvider.prototype.extinguish = function(index){
for(var i = 0; i< this.opts.smokePerPin; i++){
this.attributes.active.value[(i + index) % this.opts.smokeCount] = 0.0;
this.attributes.active.needsUpdate = true;
}
};
SmokeProvider.prototype.changeAltitude = function(altitude, index){
for(var i = 0; i< this.opts.smokePerPin; i++){
this.attributes.altitude.value[(i + index) % this.opts.smokeCount] = altitude;
this.attributes.altitude.needsUpdate = true;
}
};
SmokeProvider.prototype.tick = function(totalRunTime){
this.totalRunTime = totalRunTime;
this.uniforms.currentTime.value = this.totalRunTime;
};
module.exports = SmokeProvider;
| 0 | 0.752623 | 1 | 0.752623 | game-dev | MEDIA | 0.603486 | game-dev,web-frontend | 0.823523 | 1 | 0.823523 |
stesproject/godot-2d-topdown-template | 53,208 | addons/dialogue_manager/dialogue_manager.gd | extends Node
const DialogueResource = preload("./dialogue_resource.gd")
const DialogueLine = preload("./dialogue_line.gd")
const DialogueResponse = preload("./dialogue_response.gd")
const DMConstants = preload("./constants.gd")
const Builtins = preload("./utilities/builtins.gd")
const DMSettings = preload("./settings.gd")
const DMCompiler = preload("./compiler/compiler.gd")
const DMCompilerResult = preload("./compiler/compiler_result.gd")
const DMResolvedLineData = preload("./compiler/resolved_line_data.gd")
## Emitted when a dialogue balloon is created and dialogue starts
signal dialogue_started(resource: DialogueResource)
## Emitted when a title is encountered while traversing dialogue, usually when jumping from a
## goto line
signal passed_title(title: String)
## Emitted when a line of dialogue is encountered.
signal got_dialogue(line: DialogueLine)
## Emitted when a mutation is encountered.
signal mutated(mutation: Dictionary)
## Emitted when some dialogue has reached the end.
signal dialogue_ended(resource: DialogueResource)
## Used internally.
signal bridge_get_next_dialogue_line_completed(line: DialogueLine)
## Used internally
signal bridge_dialogue_started(resource: DialogueResource)
## Used inernally
signal bridge_mutated()
## The list of globals that dialogue can query
var game_states: Array = []
## Allow dialogue to call singletons
var include_singletons: bool = true
## Allow dialogue to call static methods/properties on classes
var include_classes: bool = true
## Manage translation behaviour
var translation_source: DMConstants.TranslationSource = DMConstants.TranslationSource.Guess
## Used to resolve the current scene. Override if your game manages the current scene itself.
var get_current_scene: Callable = func():
var current_scene: Node = Engine.get_main_loop().current_scene
if current_scene == null:
current_scene = Engine.get_main_loop().root.get_child(Engine.get_main_loop().root.get_child_count() - 1)
return current_scene
var _has_loaded_autoloads: bool = false
var _autoloads: Dictionary = {}
var _node_properties: Array = []
var _method_info_cache: Dictionary = {}
var _dotnet_dialogue_manager: RefCounted
func _ready() -> void:
# Cache the known Node2D properties
_node_properties = ["Script Variables"]
var temp_node: Node2D = Node2D.new()
for property in temp_node.get_property_list():
_node_properties.append(property.name)
temp_node.free()
# Make the dialogue manager available as a singleton
if not Engine.has_singleton("DialogueManager"):
Engine.register_singleton("DialogueManager", self)
## Step through lines and run any mutations until we either hit some dialogue or the end of the conversation
func get_next_dialogue_line(resource: DialogueResource, key: String = "", extra_game_states: Array = [], mutation_behaviour: DMConstants.MutationBehaviour = DMConstants.MutationBehaviour.Wait) -> DialogueLine:
# You have to provide a valid dialogue resource
if resource == null:
assert(false, DMConstants.translate(&"runtime.no_resource"))
if resource.lines.size() == 0:
assert(false, DMConstants.translate(&"runtime.no_content").format({ file_path = resource.resource_path }))
# Inject any "using" states into the game_states
for state_name in resource.using_states:
var autoload = Engine.get_main_loop().root.get_node_or_null(state_name)
if autoload == null:
printerr(DMConstants.translate(&"runtime.unknown_autoload").format({ autoload = state_name }))
else:
extra_game_states = [autoload] + extra_game_states
# Inject "self" into the extra game states.
extra_game_states = [{ "self": resource }] + extra_game_states
# Get the line data
var dialogue: DialogueLine = await get_line(resource, key, extra_game_states)
# If our dialogue is nothing then we hit the end
if not _is_valid(dialogue):
dialogue_ended.emit.call_deferred(resource)
return null
# Run the mutation if it is one
if dialogue.type == DMConstants.TYPE_MUTATION:
var actual_next_id: String = dialogue.next_id.split("|")[0]
match mutation_behaviour:
DMConstants.MutationBehaviour.Wait:
await _mutate(dialogue.mutation, extra_game_states)
DMConstants.MutationBehaviour.DoNotWait:
_mutate(dialogue.mutation, extra_game_states)
DMConstants.MutationBehaviour.Skip:
pass
if actual_next_id in [DMConstants.ID_END_CONVERSATION, DMConstants.ID_NULL, null]:
# End the conversation
dialogue_ended.emit.call_deferred(resource)
return null
else:
return await get_next_dialogue_line(resource, dialogue.next_id, extra_game_states, mutation_behaviour)
else:
got_dialogue.emit(dialogue)
return dialogue
## Get a line by its ID
func get_line(resource: DialogueResource, key: String, extra_game_states: Array) -> DialogueLine:
key = key.strip_edges()
# See if we were given a stack instead of just the one key
var stack: Array = key.split("|")
key = stack.pop_front()
var id_trail: String = "" if stack.size() == 0 else "|" + "|".join(stack)
# Key is blank so just use the first title (or start of file)
if key == null or key == "":
if resource.first_title.is_empty():
key = resource.lines.keys()[0]
else:
key = resource.first_title
# See if we just ended the conversation
if key in [DMConstants.ID_END, DMConstants.ID_NULL, null]:
if stack.size() > 0:
return await get_line(resource, "|".join(stack), extra_game_states)
else:
return null
elif key == DMConstants.ID_END_CONVERSATION:
return null
# See if it is a title
if key.begins_with("~ "):
key = key.substr(2)
if resource.titles.has(key):
key = resource.titles.get(key)
if key in resource.titles.values():
passed_title.emit(resource.titles.find_key(key))
if not resource.lines.has(key):
assert(false, DMConstants.translate(&"errors.key_not_found").format({ key = key }))
var data: Dictionary = resource.lines.get(key)
# If next_id is an expression we need to resolve it.
if data.has(&"next_id_expression"):
data.next_id = await _resolve(data.next_id_expression, extra_game_states)
# This title key points to another title key so we should jump there instead
if data.type == DMConstants.TYPE_TITLE and data.next_id in resource.titles.values():
return await get_line(resource, data.next_id + id_trail, extra_game_states)
# Handle match statements
if data.type == DMConstants.TYPE_MATCH:
var value = await _resolve_condition_value(data, extra_game_states)
var else_cases: Array[Dictionary] = data.cases.filter(func(s): return s.has("is_else"))
var else_case: Dictionary = {} if else_cases.size() == 0 else else_cases.front()
var next_id: String = ""
for case in data.cases:
if case == else_case:
continue
elif await _check_case_value(value, case, extra_game_states):
next_id = case.next_id
# Nothing matched so check for else case
if next_id == "":
if not else_case.is_empty():
next_id = else_case.next_id
else:
next_id = data.next_id_after
return await get_line(resource, next_id + id_trail, extra_game_states)
# Check for weighted random lines.
if data.has(&"siblings"):
# Only count siblings that pass their condition (if they have one).
var successful_siblings: Array = data.siblings.filter(func(sibling): return not sibling.has("condition") or await _check_condition(sibling, extra_game_states))
var target_weight: float = randf_range(0, successful_siblings.reduce(func(total, sibling): return total + sibling.weight, 0))
var cummulative_weight: float = 0
for sibling in successful_siblings:
if target_weight < cummulative_weight + sibling.weight:
data = resource.lines.get(sibling.id)
break
else:
cummulative_weight += sibling.weight
# Find any simultaneously said lines.
var concurrent_lines: Array[DialogueLine] = []
if data.has(&"concurrent_lines"):
# If the list includes this line then it isn't the origin line so ignore it.
if not data.concurrent_lines.has(data.id):
for concurrent_id: String in data.concurrent_lines:
var concurrent_line: DialogueLine = await get_line(resource, concurrent_id, extra_game_states)
if concurrent_line:
concurrent_lines.append(concurrent_line)
# If this line is blank and it's the last line then check for returning snippets.
if data.type in [DMConstants.TYPE_COMMENT, DMConstants.TYPE_UNKNOWN]:
if data.next_id in [DMConstants.ID_END, DMConstants.ID_NULL, null]:
if stack.size() > 0:
return await get_line(resource, "|".join(stack), extra_game_states)
else:
return null
else:
return await get_line(resource, data.next_id + id_trail, extra_game_states)
# If the line is a random block then go to the start of the block.
elif data.type == DMConstants.TYPE_RANDOM:
data = resource.lines.get(data.next_id)
# Check conditions.
elif data.type in [DMConstants.TYPE_CONDITION, DMConstants.TYPE_WHILE]:
# "else" will have no actual condition.
if await _check_condition(data, extra_game_states):
return await get_line(resource, data.next_id + id_trail, extra_game_states)
elif data.has("next_sibling_id") and not data.next_sibling_id.is_empty():
return await get_line(resource, data.next_sibling_id + id_trail, extra_game_states)
else:
return await get_line(resource, data.next_id_after + id_trail, extra_game_states)
# Evaluate jumps.
elif data.type == DMConstants.TYPE_GOTO:
if data.is_snippet and not id_trail.begins_with("|" + data.next_id_after):
id_trail = "|" + data.next_id_after + id_trail
return await get_line(resource, data.next_id + id_trail, extra_game_states)
elif data.type == DMConstants.TYPE_DIALOGUE:
if not data.has(&"id"):
data.id = key
# Set up a line object.
var line: DialogueLine = await create_dialogue_line(data, extra_game_states)
line.concurrent_lines = concurrent_lines
# If the jump point somehow has no content then just end.
if not line: return null
# If we are the first of a list of responses then get the other ones.
if data.type == DMConstants.TYPE_RESPONSE:
# Note: For some reason C# has occasional issues with using the responses property directly
# so instead we use set and get here.
line.set(&"responses", await _get_responses(data.get(&"responses", []), resource, id_trail, extra_game_states))
return line
# Inject the next node's responses if they have any.
if resource.lines.has(line.next_id):
var next_line: Dictionary = resource.lines.get(line.next_id)
# If the response line is marked as a title then make sure to emit the passed_title signal.
if line.next_id in resource.titles.values():
passed_title.emit(resource.titles.find_key(line.next_id))
# If the responses come from a snippet then we need to come back here afterwards.
if next_line.type == DMConstants.TYPE_GOTO and next_line.is_snippet and not id_trail.begins_with("|" + next_line.next_id_after):
id_trail = "|" + next_line.next_id_after + id_trail
# If the next line is a title then check where it points to see if that is a set of responses.
while [DMConstants.TYPE_TITLE, DMConstants.TYPE_GOTO].has(next_line.type) and resource.lines.has(next_line.next_id):
next_line = resource.lines.get(next_line.next_id)
if next_line != null and next_line.type == DMConstants.TYPE_RESPONSE:
# Note: For some reason C# has occasional issues with using the responses property directly
# so instead we use set and get here.
line.set(&"responses", await _get_responses(next_line.get(&"responses", []), resource, id_trail, extra_game_states))
line.next_id = "|".join(stack) if line.next_id == DMConstants.ID_NULL else line.next_id + id_trail
return line
## Replace any variables, etc in the text.
func get_resolved_line_data(data: Dictionary, extra_game_states: Array = []) -> DMResolvedLineData:
var text: String = translate(data)
# Resolve variables
for replacement in data.get(&"text_replacements", [] as Array[Dictionary]):
var value = await _resolve(replacement.expression.duplicate(true), extra_game_states)
var index: int = text.find(replacement.value_in_text)
if index == -1:
# The replacement wasn't found but maybe the regular quotes have been replaced
# by special quotes while translating.
index = text.replace("“", "\"").replace("”", "\"").find(replacement.value_in_text)
if index > -1:
text = text.substr(0, index) + str(value) + text.substr(index + replacement.value_in_text.length())
var compilation: DMCompilation = DMCompilation.new()
# Resolve random groups
for found in compilation.regex.INLINE_RANDOM_REGEX.search_all(text):
var options = found.get_string(&"options").split(&"|")
text = text.replace(&"[[%s]]" % found.get_string(&"options"), options[randi_range(0, options.size() - 1)])
# Do a pass on the markers to find any conditionals
var markers: DMResolvedLineData = DMResolvedLineData.new(text)
# Resolve any conditionals and update marker positions as needed
if data.type == DMConstants.TYPE_DIALOGUE:
var resolved_text: String = markers.text
var conditionals: Array[RegExMatch] = compilation.regex.INLINE_CONDITIONALS_REGEX.search_all(resolved_text)
var replacements: Array = []
for conditional in conditionals:
var condition_raw: String = conditional.strings[conditional.names.condition]
var body: String = conditional.strings[conditional.names.body]
var body_else: String = ""
if &"[else]" in body:
var bits = body.split(&"[else]")
body = bits[0]
body_else = bits[1]
var condition: Dictionary = compilation.extract_condition("if " + condition_raw, false, 0)
# If the condition fails then use the else of ""
if not await _check_condition({ condition = condition }, extra_game_states):
body = body_else
replacements.append({
start = conditional.get_start(),
end = conditional.get_end(),
string = conditional.get_string(),
body = body
})
for i in range(replacements.size() - 1, -1, -1):
var r: Dictionary = replacements[i]
resolved_text = resolved_text.substr(0, r.start) + r.body + resolved_text.substr(r.end, 9999)
# Move any other markers now that the text has changed
var offset: int = r.end - r.start - r.body.length()
for key in [&"pauses", &"speeds", &"time"]:
if markers.get(key) == null: continue
var marker = markers.get(key)
var next_marker: Dictionary = {}
for index in marker:
if index < r.start:
next_marker[index] = marker[index]
elif index > r.start:
next_marker[index - offset] = marker[index]
markers.set(key, next_marker)
var mutations: Array[Array] = markers.mutations
var next_mutations: Array[Array] = []
for mutation in mutations:
var index = mutation[0]
if index < r.start:
next_mutations.append(mutation)
elif index > r.start:
next_mutations.append([index - offset, mutation[1]])
markers.mutations = next_mutations
markers.text = resolved_text
return markers
## Replace any variables, etc in the character name
func get_resolved_character(data: Dictionary, extra_game_states: Array = []) -> String:
var character: String = data.get(&"character", "")
# Resolve variables
for replacement in data.get(&"character_replacements", []):
var value = await _resolve(replacement.expression.duplicate(true), extra_game_states)
var index: int = character.find(replacement.value_in_text)
if index > -1:
character = character.substr(0, index) + str(value) + character.substr(index + replacement.value_in_text.length())
# Resolve random groups
var random_regex: RegEx = RegEx.new()
random_regex.compile("\\[\\[(?<options>.*?)\\]\\]")
for found in random_regex.search_all(character):
var options = found.get_string(&"options").split("|")
character = character.replace("[[%s]]" % found.get_string(&"options"), options[randi_range(0, options.size() - 1)])
return character
## Generate a dialogue resource on the fly from some text
func create_resource_from_text(text: String) -> Resource:
var result: DMCompilerResult = DMCompiler.compile_string(text, "")
if result.errors.size() > 0:
printerr(DMConstants.translate(&"runtime.errors").format({ count = result.errors.size() }))
for error in result.errors:
printerr(DMConstants.translate(&"runtime.error_detail").format({
line = error.line_number + 1,
message = DMConstants.get_error_message(error.error)
}))
assert(false, DMConstants.translate(&"runtime.errors_see_details").format({ count = result.errors.size() }))
var resource: DialogueResource = DialogueResource.new()
resource.using_states = result.using_states
resource.titles = result.titles
resource.first_title = result.first_title
resource.character_names = result.character_names
resource.lines = result.lines
resource.raw_text = text
return resource
#region Balloon helpers
## Show the example balloon
func show_example_dialogue_balloon(resource: DialogueResource, title: String = "", extra_game_states: Array = []) -> CanvasLayer:
var balloon: Node = load(_get_example_balloon_path()).instantiate()
_start_balloon.call_deferred(balloon, resource, title, extra_game_states)
return balloon
## Show the configured dialogue balloon
func show_dialogue_balloon(resource: DialogueResource, title: String = "", extra_game_states: Array = []) -> Node:
var balloon_path: String = DMSettings.get_setting(DMSettings.BALLOON_PATH, _get_example_balloon_path())
if not ResourceLoader.exists(balloon_path):
balloon_path = _get_example_balloon_path()
return show_dialogue_balloon_scene(balloon_path, resource, title, extra_game_states)
## Show a given balloon scene
func show_dialogue_balloon_scene(balloon_scene, resource: DialogueResource, title: String = "", extra_game_states: Array = []) -> Node:
if balloon_scene is String:
balloon_scene = load(balloon_scene)
if balloon_scene is PackedScene:
balloon_scene = balloon_scene.instantiate()
var balloon: Node = balloon_scene
_start_balloon.call_deferred(balloon, resource, title, extra_game_states)
return balloon
# Call "start" on the given balloon.
func _start_balloon(balloon: Node, resource: DialogueResource, title: String, extra_game_states: Array) -> void:
get_current_scene.call().add_child(balloon)
if balloon.has_method(&"start"):
balloon.start(resource, title, extra_game_states)
elif balloon.has_method(&"Start"):
balloon.Start(resource, title, extra_game_states)
else:
assert(false, DMConstants.translate(&"runtime.dialogue_balloon_missing_start_method"))
dialogue_started.emit(resource)
bridge_dialogue_started.emit(resource)
# Get the path to the example balloon
func _get_example_balloon_path() -> String:
var is_small_window: bool = ProjectSettings.get_setting("display/window/size/viewport_width") < 400
var balloon_path: String = "/example_balloon/small_example_balloon.tscn" if is_small_window else "/example_balloon/example_balloon.tscn"
return get_script().resource_path.get_base_dir() + balloon_path
#endregion
#region dotnet bridge
func _get_dotnet_dialogue_manager() -> RefCounted:
if not is_instance_valid(_dotnet_dialogue_manager):
_dotnet_dialogue_manager = load(get_script().resource_path.get_base_dir() + "/DialogueManager.cs").new()
return _dotnet_dialogue_manager
func _bridge_get_new_instance() -> Node:
# For some reason duplicating the node with its signals doesn't work so we have to copy them over manually
var instance = new()
for s: Dictionary in dialogue_started.get_connections():
instance.dialogue_started.connect(s.callable)
for s: Dictionary in passed_title.get_connections():
instance.passed_title.connect(s.callable)
for s: Dictionary in got_dialogue.get_connections():
instance.got_dialogue.connect(s.callable)
for s: Dictionary in mutated.get_connections():
instance.mutated.connect(s.callable)
for s: Dictionary in dialogue_ended.get_connections():
instance.dialogue_ended.connect(s.callable)
instance.get_current_scene = get_current_scene
return instance
func _bridge_get_next_dialogue_line(resource: DialogueResource, key: String, extra_game_states: Array = []) -> void:
# dotnet needs at least one await tick of the signal gets called too quickly
await Engine.get_main_loop().process_frame
var line = await get_next_dialogue_line(resource, key, extra_game_states)
bridge_get_next_dialogue_line_completed.emit(line)
func _bridge_mutate(mutation: Dictionary, extra_game_states: Array, is_inline_mutation: bool = false) -> void:
await _mutate(mutation, extra_game_states, is_inline_mutation)
bridge_mutated.emit()
#endregion
#region Internal helpers
# Show a message or crash with error
func show_error_for_missing_state_value(message: String, will_show: bool = true) -> void:
if not will_show: return
if DMSettings.get_setting(DMSettings.IGNORE_MISSING_STATE_VALUES, false):
push_error(message)
elif will_show:
# If you're here then you're missing a method or property in your game state. The error
# message down in the debugger will give you some more information.
assert(false, message)
# Translate a string
func translate(data: Dictionary) -> String:
if translation_source == DMConstants.TranslationSource.None:
return data.text
var translation_key: String = data.get(&"translation_key", data.text)
if translation_key == "" or translation_key == data.text:
return tr(data.text)
else:
# Line IDs work slightly differently depending on whether the translation came from a
# CSV or a PO file. CSVs use the line ID (or the line itself) as the translatable string
# whereas POs use the ID as context and the line itself as the translatable string.
match translation_source:
DMConstants.TranslationSource.PO:
return tr(data.text, StringName(translation_key))
DMConstants.TranslationSource.CSV:
return tr(translation_key)
DMConstants.TranslationSource.Guess:
var translation_files: Array = ProjectSettings.get_setting(&"internationalization/locale/translations")
if translation_files.filter(func(f: String): return f.get_extension() in [&"po", &"mo"]).size() > 0:
# Assume PO
return tr(data.text, StringName(translation_key))
else:
# Assume CSV
return tr(translation_key)
return tr(translation_key)
# Create a line of dialogue
func create_dialogue_line(data: Dictionary, extra_game_states: Array) -> DialogueLine:
match data.type:
DMConstants.TYPE_DIALOGUE:
var resolved_data: DMResolvedLineData = await get_resolved_line_data(data, extra_game_states)
return DialogueLine.new({
id = data.get(&"id", ""),
type = DMConstants.TYPE_DIALOGUE,
next_id = data.next_id,
character = await get_resolved_character(data, extra_game_states),
character_replacements = data.get(&"character_replacements", [] as Array[Dictionary]),
text = resolved_data.text,
text_replacements = data.get(&"text_replacements", [] as Array[Dictionary]),
translation_key = data.get(&"translation_key", data.text),
pauses = resolved_data.pauses,
speeds = resolved_data.speeds,
inline_mutations = resolved_data.mutations,
time = resolved_data.time,
tags = data.get(&"tags", []),
extra_game_states = extra_game_states
})
DMConstants.TYPE_RESPONSE:
return DialogueLine.new({
id = data.get(&"id", ""),
type = DMConstants.TYPE_RESPONSE,
next_id = data.next_id,
tags = data.get(&"tags", []),
extra_game_states = extra_game_states
})
DMConstants.TYPE_MUTATION:
return DialogueLine.new({
id = data.get(&"id", ""),
type = DMConstants.TYPE_MUTATION,
next_id = data.next_id,
mutation = data.mutation,
extra_game_states = extra_game_states
})
return null
# Create a response
func create_response(data: Dictionary, extra_game_states: Array) -> DialogueResponse:
var resolved_data: DMResolvedLineData = await get_resolved_line_data(data, extra_game_states)
return DialogueResponse.new({
id = data.get(&"id", ""),
type = DMConstants.TYPE_RESPONSE,
next_id = data.next_id,
is_allowed = data.is_allowed,
character = await get_resolved_character(data, extra_game_states),
character_replacements = data.get(&"character_replacements", [] as Array[Dictionary]),
text = resolved_data.text,
text_replacements = data.get(&"text_replacements", [] as Array[Dictionary]),
tags = data.get(&"tags", []),
translation_key = data.get(&"translation_key", data.text)
})
# Get the current game states
func _get_game_states(extra_game_states: Array) -> Array:
if not _has_loaded_autoloads:
_has_loaded_autoloads = true
# Add any autoloads to a generic state so we can refer to them by name
for child in Engine.get_main_loop().root.get_children():
# Ignore the dialogue manager
if child.name == &"DialogueManager": continue
# Ignore the current main scene
if Engine.get_main_loop().current_scene and child.name == Engine.get_main_loop().current_scene.name: continue
# Add the node to our known autoloads
_autoloads[child.name] = child
game_states = [_autoloads]
# Add any other state shortcuts from settings
for node_name in DMSettings.get_setting(DMSettings.STATE_AUTOLOAD_SHORTCUTS, ""):
var state: Node = Engine.get_main_loop().root.get_node_or_null(node_name)
if state:
game_states.append(state)
var current_scene: Node = get_current_scene.call()
var unique_states: Array = []
for state in extra_game_states + [current_scene] + game_states:
if state != null and not unique_states.has(state):
unique_states.append(state)
return unique_states
# Check if a condition is met
func _check_condition(data: Dictionary, extra_game_states: Array) -> bool:
return bool(await _resolve_condition_value(data, extra_game_states))
# Resolve a condition's expression value
func _resolve_condition_value(data: Dictionary, extra_game_states: Array) -> Variant:
if data.get(&"condition", null) == null: return true
if data.condition.is_empty(): return true
return await _resolve(data.condition.expression.duplicate(true), extra_game_states)
# Check if a match value matches a case value
func _check_case_value(match_value: Variant, data: Dictionary, extra_game_states: Array) -> bool:
if data.get(&"condition", null) == null: return true
if data.condition.is_empty(): return true
var expression: Array[Dictionary] = data.condition.expression.duplicate(true)
# If the when is a comparison when insert the match value as the first value to compare to
var already_compared: bool = false
if expression[0].type == DMConstants.TOKEN_COMPARISON:
expression.insert(0, {
type = DMConstants.TOKEN_VALUE,
value = match_value
})
already_compared = true
var resolved_value = await _resolve(expression, extra_game_states)
if already_compared:
return resolved_value
else:
return match_value == resolved_value
# Make a change to game state or run a method
func _mutate(mutation: Dictionary, extra_game_states: Array, is_inline_mutation: bool = false) -> void:
var expression: Array[Dictionary] = mutation.expression
# Handle built in mutations
if expression[0].type == DMConstants.TOKEN_FUNCTION and expression[0].function in [&"wait", &"Wait", &"debug", &"Debug"]:
var args: Array = await _resolve_each(expression[0].value, extra_game_states)
match expression[0].function:
&"wait", &"Wait":
mutated.emit(mutation.merged({ is_inline = is_inline_mutation }))
await Engine.get_main_loop().create_timer(float(args[0])).timeout
return
&"debug", &"Debug":
prints("Debug:", args)
await Engine.get_main_loop().process_frame
# Or pass through to the resolver
else:
if not _mutation_contains_assignment(mutation.expression) and not is_inline_mutation:
mutated.emit(mutation.merged({ is_inline = is_inline_mutation }))
if mutation.get("is_blocking", true):
await _resolve(mutation.expression.duplicate(true), extra_game_states)
return
else:
_resolve(mutation.expression.duplicate(true), extra_game_states)
# Wait one frame to give the dialogue handler a chance to yield
await Engine.get_main_loop().process_frame
# Check if a mutation contains an assignment token.
func _mutation_contains_assignment(mutation: Array) -> bool:
for token in mutation:
if token.type == DMConstants.TOKEN_ASSIGNMENT:
return true
return false
# Replace an array of line IDs with their response prompts
func _get_responses(ids: Array, resource: DialogueResource, id_trail: String, extra_game_states: Array) -> Array[DialogueResponse]:
var responses: Array[DialogueResponse] = []
for id in ids:
var data: Dictionary = resource.lines.get(id).duplicate(true)
data.is_allowed = await _check_condition(data, extra_game_states)
var response: DialogueResponse = await create_response(data, extra_game_states)
response.next_id += id_trail
responses.append(response)
return responses
# Get a value on the current scene or game state
func _get_state_value(property: String, extra_game_states: Array):
# Special case for static primitive calls
if property == "Color":
return Color()
elif property == "Vector2":
return Vector2.ZERO
elif property == "Vector3":
return Vector3.ZERO
elif property == "Vector4":
return Vector4.ZERO
elif property == "Quaternion":
return Quaternion()
var expression = Expression.new()
if expression.parse(property) != OK:
assert(false, DMConstants.translate(&"runtime.invalid_expression").format({ expression = property, error = expression.get_error_text() }))
# Warn about possible name collisions
_warn_about_state_name_collisions(property, extra_game_states)
for state in _get_game_states(extra_game_states):
if typeof(state) == TYPE_DICTIONARY:
if state.has(property):
return state.get(property)
else:
var result = expression.execute([], state, false)
if not expression.has_execute_failed():
return result
if include_singletons and Engine.has_singleton(property):
return Engine.get_singleton(property)
if include_classes:
for class_data in ProjectSettings.get_global_class_list():
if class_data.get(&"class") == property:
return load(class_data.path).new()
show_error_for_missing_state_value(DMConstants.translate(&"runtime.property_not_found").format({ property = property, states = _get_state_shortcut_names(extra_game_states) }))
# Print warnings for top-level state name collisions.
func _warn_about_state_name_collisions(target_key: String, extra_game_states: Array) -> void:
# Don't run the check if this is a release build
if not OS.is_debug_build(): return
# Also don't run if the setting is off
if not DMSettings.get_setting(DMSettings.WARN_ABOUT_METHOD_PROPERTY_OR_SIGNAL_NAME_CONFLICTS, false): return
# Get the list of state shortcuts.
var state_shortcuts: Array = []
for node_name in DMSettings.get_setting(DMSettings.STATE_AUTOLOAD_SHORTCUTS, ""):
var state: Node = Engine.get_main_loop().root.get_node_or_null(node_name)
if state:
state_shortcuts.append(state)
# Check any top level names for a collision
var states_with_key: Array = []
for state in extra_game_states + [get_current_scene.call()] + state_shortcuts:
if state is Dictionary:
if state.keys().has(target_key):
states_with_key.append("Dictionary")
else:
var script: Script = (state as Object).get_script()
if script == null:
continue
for method in script.get_script_method_list():
if method.name == target_key and not states_with_key.has(state.name):
states_with_key.append(state.name)
break
for property in script.get_script_property_list():
if property.name == target_key and not states_with_key.has(state.name):
states_with_key.append(state.name)
break
for signal_info in script.get_script_signal_list():
if signal_info.name == target_key and not states_with_key.has(state.name):
states_with_key.append(state.name)
break
if states_with_key.size() > 1:
push_warning(DMConstants.translate(&"runtime.top_level_states_share_name").format({ states = ", ".join(states_with_key), key = target_key }))
# Set a value on the current scene or game state
func _set_state_value(property: String, value, extra_game_states: Array) -> void:
for state in _get_game_states(extra_game_states):
if typeof(state) == TYPE_DICTIONARY:
if state.has(property):
state[property] = value
return
elif _thing_has_property(state, property):
state.set(property, value)
return
if property.to_snake_case() != property:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.property_not_found_missing_export").format({ property = property, states = _get_state_shortcut_names(extra_game_states) }))
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.property_not_found").format({ property = property, states = _get_state_shortcut_names(extra_game_states) }))
# Get the list of state shortcut names
func _get_state_shortcut_names(extra_game_states: Array) -> String:
var states = _get_game_states(extra_game_states)
states.erase(_autoloads)
return ", ".join(states.map(func(s): return "\"%s\"" % (s.name if "name" in s else s)))
# Resolve an array of expressions.
func _resolve_each(array: Array, extra_game_states: Array) -> Array:
var results: Array = []
for item in array:
if not item[0].type in [DMConstants.TOKEN_BRACE_CLOSE, DMConstants.TOKEN_BRACKET_CLOSE, DMConstants.TOKEN_PARENS_CLOSE]:
results.append(await _resolve(item.duplicate(true), extra_game_states))
return results
# Collapse any expressions
func _resolve(tokens: Array, extra_game_states: Array):
var i: int = 0
var limit: int = 0
# Handle groups first
for token in tokens:
if token.type == DMConstants.TOKEN_GROUP:
token.type = DMConstants.TOKEN_VALUE
token.value = await _resolve(token.value, extra_game_states)
# Then variables/methods
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_NULL_COALESCE:
var caller: Dictionary = tokens[i - 1]
if caller.value == null:
# If the caller is null then the method/property is also null
caller.type = DMConstants.TOKEN_VALUE
caller.value = null
tokens.remove_at(i + 1)
tokens.remove_at(i)
else:
token.type = DMConstants.TOKEN_DOT
elif token.type == DMConstants.TOKEN_FUNCTION:
var function_name: String = token.function
var args = await _resolve_each(token.value, extra_game_states)
if tokens[i - 1].type == DMConstants.TOKEN_DOT:
# If we are calling a deeper function then we need to collapse the
# value into the thing we are calling the function on
var caller: Dictionary = tokens[i - 2]
if Builtins.is_supported(caller.value):
caller.type = DMConstants.TOKEN_VALUE
caller.value = Builtins.resolve_method(caller.value, function_name, args)
tokens.remove_at(i)
tokens.remove_at(i - 1)
i -= 2
elif _thing_has_method(caller.value, function_name, args):
caller.type = DMConstants.TOKEN_VALUE
caller.value = await _resolve_thing_method(caller.value, function_name, args)
tokens.remove_at(i)
tokens.remove_at(i - 1)
i -= 2
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.method_not_callable").format({ method = function_name, object = str(caller.value) }))
else:
var found: bool = false
match function_name:
&"str":
token.type = DMConstants.TOKEN_VALUE
token.value = str(args[0])
found = true
&"Vector2":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector2(args[0], args[1])
found = true
&"Vector2i":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector2i(args[0], args[1])
found = true
&"Vector3":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector3(args[0], args[1], args[2])
found = true
&"Vector3i":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector3i(args[0], args[1], args[2])
found = true
&"Vector4":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector4(args[0], args[1], args[2], args[3])
found = true
&"Vector4i":
token.type = DMConstants.TOKEN_VALUE
token.value = Vector4i(args[0], args[1], args[2], args[3])
found = true
&"Quaternion":
token.type = DMConstants.TOKEN_VALUE
token.value = Quaternion(args[0], args[1], args[2], args[3])
found = true
&"Callable":
token.type = DMConstants.TOKEN_VALUE
match args.size():
0:
token.value = Callable()
1:
token.value = Callable(args[0])
2:
token.value = Callable(args[0], args[1])
found = true
&"Color":
token.type = DMConstants.TOKEN_VALUE
match args.size():
0:
token.value = Color()
1:
token.value = Color(args[0])
2:
token.value = Color(args[0], args[1])
3:
token.value = Color(args[0], args[1], args[2])
4:
token.value = Color(args[0], args[1], args[2], args[3])
found = true
&"load", &"Load":
token.type = DMConstants.TOKEN_VALUE
token.value = load(args[0])
found = true
&"roll_dice", &"RollDice":
token.type = DMConstants.TOKEN_VALUE
token.value = randi_range(1, args[0])
found = true
_:
# Check for top level name conflicts
_warn_about_state_name_collisions(function_name, extra_game_states)
for state in _get_game_states(extra_game_states):
if _thing_has_method(state, function_name, args):
token.type = DMConstants.TOKEN_VALUE
token.value = await _resolve_thing_method(state, function_name, args)
found = true
break
show_error_for_missing_state_value(DMConstants.translate(&"runtime.method_not_found").format({
method = args[0] if function_name in ["call", "call_deferred"] else function_name,
states = _get_state_shortcut_names(extra_game_states)
}), not found)
elif token.type == DMConstants.TOKEN_DICTIONARY_REFERENCE:
var value
if i > 0 and tokens[i - 1].type == DMConstants.TOKEN_DOT:
# If we are deep referencing then we need to get the parent object.
# `parent.value` is the actual object and `token.variable` is the name of
# the property within it.
value = tokens[i - 2].value[token.variable]
# Clean up the previous tokens
token.erase("variable")
tokens.remove_at(i - 1)
tokens.remove_at(i - 2)
i -= 2
else:
# Otherwise we can just get this variable as a normal state reference
value = _get_state_value(token.variable, extra_game_states)
var index = await _resolve(token.value, extra_game_states)
if typeof(value) == TYPE_DICTIONARY:
if tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# If the next token is an assignment then we need to leave this as a reference
# so that it can be resolved once everything ahead of it has been resolved
token.type = "dictionary"
token.value = value
token.key = index
else:
if value.has(index):
token.type = DMConstants.TOKEN_VALUE
token.value = value[index]
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.key_not_found").format({ key = str(index), dictionary = token.variable }))
elif typeof(value) == TYPE_ARRAY:
if tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# If the next token is an assignment then we need to leave this as a reference
# so that it can be resolved once everything ahead of it has been resolved
token.type = "array"
token.value = value
token.key = index
else:
if index >= 0 and index < value.size():
token.type = DMConstants.TOKEN_VALUE
token.value = value[index]
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.array_index_out_of_bounds").format({ index = index, array = token.variable }))
elif token.type == DMConstants.TOKEN_DICTIONARY_NESTED_REFERENCE:
var dictionary: Dictionary = tokens[i - 1]
var index = await _resolve(token.value, extra_game_states)
var value = dictionary.value
if typeof(value) == TYPE_DICTIONARY:
if tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# If the next token is an assignment then we need to leave this as a reference
# so that it can be resolved once everything ahead of it has been resolved
dictionary.type = "dictionary"
dictionary.key = index
dictionary.value = value
tokens.remove_at(i)
i -= 1
else:
if dictionary.value.has(index):
dictionary.value = value.get(index)
tokens.remove_at(i)
i -= 1
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.key_not_found").format({ key = str(index), dictionary = value }))
elif typeof(value) == TYPE_ARRAY:
if tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# If the next token is an assignment then we need to leave this as a reference
# so that it can be resolved once everything ahead of it has been resolved
dictionary.type = "array"
dictionary.value = value
dictionary.key = index
tokens.remove_at(i)
i -= 1
else:
if index >= 0 and index < value.size():
dictionary.value = value[index]
tokens.remove_at(i)
i -= 1
else:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.array_index_out_of_bounds").format({ index = index, array = value }))
elif token.type == DMConstants.TOKEN_ARRAY:
token.type = DMConstants.TOKEN_VALUE
token.value = await _resolve_each(token.value, extra_game_states)
elif token.type == DMConstants.TOKEN_DICTIONARY:
token.type = DMConstants.TOKEN_VALUE
var dictionary = {}
for key in token.value.keys():
var resolved_key = await _resolve([key], extra_game_states)
var preresolved_value = token.value.get(key)
if typeof(preresolved_value) != TYPE_ARRAY:
preresolved_value = [preresolved_value]
var resolved_value = await _resolve(preresolved_value, extra_game_states)
dictionary[resolved_key] = resolved_value
token.value = dictionary
elif token.type == DMConstants.TOKEN_VARIABLE or token.type == DMConstants.TOKEN_NUMBER:
if str(token.value) == "null":
token.type = DMConstants.TOKEN_VALUE
token.value = null
elif str(token.value) == "self":
token.type = DMConstants.TOKEN_VALUE
token.value = extra_game_states[0].self
elif tokens[i - 1].type == DMConstants.TOKEN_DOT:
var caller: Dictionary = tokens[i - 2]
var property = token.value
if tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# If the next token is an assignment then we need to leave this as a reference
# so that it can be resolved once everything ahead of it has been resolved
caller.type = "property"
caller.property = property
else:
# If we are requesting a deeper property then we need to collapse the
# value into the thing we are referencing from
caller.type = DMConstants.TOKEN_VALUE
if Builtins.is_supported(caller.value):
caller.value = Builtins.resolve_property(caller.value, property)
else:
caller.value = caller.value.get(property)
tokens.remove_at(i)
tokens.remove_at(i - 1)
i -= 2
elif tokens.size() > i + 1 and tokens[i + 1].type == DMConstants.TOKEN_ASSIGNMENT:
# It's a normal variable but we will be assigning to it so don't resolve
# it until everything after it has been resolved
token.type = "variable"
else:
if token.type == DMConstants.TOKEN_NUMBER:
token.type = DMConstants.TOKEN_VALUE
token.value = token.value
else:
token.type = DMConstants.TOKEN_VALUE
token.value = _get_state_value(str(token.value), extra_game_states)
i += 1
# Then multiply and divide
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_OPERATOR and token.value in ["*", "/", "%"]:
token.type = DMConstants.TOKEN_VALUE
token.value = _apply_operation(token.value, tokens[i - 1].value, tokens[i + 1].value)
tokens.remove_at(i + 1)
tokens.remove_at(i - 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
# Then addition and subtraction
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_OPERATOR and token.value in ["+", "-"]:
token.type = DMConstants.TOKEN_VALUE
token.value = _apply_operation(token.value, tokens[i - 1].value, tokens[i + 1].value)
tokens.remove_at(i + 1)
tokens.remove_at(i - 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
# Then negations
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_NOT:
token.type = DMConstants.TOKEN_VALUE
token.value = not tokens[i + 1].value
tokens.remove_at(i + 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
# Then comparisons
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_COMPARISON:
token.type = DMConstants.TOKEN_VALUE
token.value = _compare(token.value, tokens[i - 1].value, tokens[i + 1].value)
tokens.remove_at(i + 1)
tokens.remove_at(i - 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
# Then and/or
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_AND_OR:
token.type = DMConstants.TOKEN_VALUE
token.value = _apply_operation(token.value, tokens[i - 1].value, tokens[i + 1].value)
tokens.remove_at(i + 1)
tokens.remove_at(i - 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
# Lastly, resolve any assignments
i = 0
limit = 0
while i < tokens.size() and limit < 1000:
limit += 1
var token: Dictionary = tokens[i]
if token.type == DMConstants.TOKEN_ASSIGNMENT:
var lhs: Dictionary = tokens[i - 1]
var value
match lhs.type:
&"variable":
value = _apply_operation(token.value, _get_state_value(lhs.value, extra_game_states), tokens[i + 1].value)
_set_state_value(lhs.value, value, extra_game_states)
&"property":
value = _apply_operation(token.value, lhs.value.get(lhs.property), tokens[i + 1].value)
if typeof(lhs.value) == TYPE_DICTIONARY:
lhs.value[lhs.property] = value
else:
lhs.value.set(lhs.property, value)
&"dictionary":
value = _apply_operation(token.value, lhs.value.get(lhs.key, null), tokens[i + 1].value)
lhs.value[lhs.key] = value
&"array":
show_error_for_missing_state_value(
DMConstants.translate(&"runtime.array_index_out_of_bounds").format({ index = lhs.key, array = lhs.value }),
lhs.key >= lhs.value.size()
)
value = _apply_operation(token.value, lhs.value[lhs.key], tokens[i + 1].value)
lhs.value[lhs.key] = value
_:
show_error_for_missing_state_value(DMConstants.translate(&"runtime.left_hand_size_cannot_be_assigned_to"))
token.type = DMConstants.TOKEN_VALUE
token.value = value
tokens.remove_at(i + 1)
tokens.remove_at(i - 1)
i -= 1
i += 1
if limit >= 1000:
assert(false, DMConstants.translate(&"runtime.something_went_wrong"))
return tokens[0].value
# Compare two values.
func _compare(operator: String, first_value, second_value) -> bool:
match operator:
&"in":
if first_value == null or second_value == null:
return false
else:
return first_value in second_value
&"<":
if first_value == null:
return true
elif second_value == null:
return false
else:
return first_value < second_value
&">":
if first_value == null:
return false
elif second_value == null:
return true
else:
return first_value > second_value
&"<=":
if first_value == null:
return true
elif second_value == null:
return false
else:
return first_value <= second_value
&">=":
if first_value == null:
return false
elif second_value == null:
return true
else:
return first_value >= second_value
&"==":
if first_value == null:
if typeof(second_value) == TYPE_BOOL:
return second_value == false
else:
return second_value == null
else:
return first_value == second_value
&"!=":
if first_value == null:
if typeof(second_value) == TYPE_BOOL:
return second_value == true
else:
return second_value != null
else:
return first_value != second_value
return false
# Apply an operation from one value to another.
func _apply_operation(operator: String, first_value, second_value):
match operator:
&"=":
return second_value
&"+", &"+=":
return first_value + second_value
&"-", &"-=":
return first_value - second_value
&"/", &"/=":
return first_value / second_value
&"*", &"*=":
return first_value * second_value
&"%":
return first_value % second_value
&"and":
return first_value and second_value
&"or":
return first_value or second_value
assert(false, DMConstants.translate(&"runtime.unknown_operator"))
# Check if a dialogue line contains meaningful information.
func _is_valid(line: DialogueLine) -> bool:
if line == null:
return false
if line.type == DMConstants.TYPE_MUTATION and line.mutation == null:
return false
if line.type == DMConstants.TYPE_RESPONSE and line.get(&"responses").size() == 0:
return false
return true
# Check that a thing has a given method.
func _thing_has_method(thing, method: String, args: Array) -> bool:
if not is_instance_valid(thing):
return false
if Builtins.is_supported(thing, method):
return thing != _autoloads
elif thing is Dictionary:
return false
if method in [&"call", &"call_deferred"]:
return thing.has_method(args[0])
if method == &"emit_signal":
return thing.has_signal(args[0])
if thing.has_method(method):
return true
if method.to_snake_case() != method and DMSettings.check_for_dotnet_solution():
# If we get this far then the method might be a C# method with a Task return type
return _get_dotnet_dialogue_manager().ThingHasMethod(thing, method, args)
return false
# Check if a given property exists
func _thing_has_property(thing: Object, property: String) -> bool:
if thing == null:
return false
for p in thing.get_property_list():
if _node_properties.has(p.name):
# Ignore any properties on the base Node
continue
if p.name == property:
return true
return false
func _get_method_info_for(thing: Variant, method: String, args: Array) -> Dictionary:
# Use the thing instance id as a key for the caching dictionary.
var thing_instance_id: int = thing.get_instance_id()
if not _method_info_cache.has(thing_instance_id):
var methods: Dictionary = {}
for m in thing.get_method_list():
methods["%s:%d" % [m.name, m.args.size()]] = m
if not methods.has(m.name):
methods[m.name] = m
_method_info_cache[thing_instance_id] = methods
var methods: Dictionary = _method_info_cache.get(thing_instance_id, {})
var method_key: String = "%s:%d" % [method, args.size()]
if methods.has(method_key):
return methods.get(method_key)
else:
return methods.get(method)
func _resolve_thing_method(thing, method: String, args: Array):
if Builtins.is_supported(thing):
var result = Builtins.resolve_method(thing, method, args)
if not Builtins.has_resolve_method_failed():
return result
if thing.has_method(method):
# Try to convert any literals to the right type
var method_info: Dictionary = _get_method_info_for(thing, method, args)
var method_args: Array = method_info.args
if method_info.flags & METHOD_FLAG_VARARG == 0 and method_args.size() < args.size():
assert(false, DMConstants.translate(&"runtime.expected_n_got_n_args").format({ expected = method_args.size(), method = method, received = args.size()}))
for i in range(0, min(method_args.size(), args.size())):
var m: Dictionary = method_args[i]
var to_type: int = typeof(args[i])
if m.type == TYPE_ARRAY:
match m.hint_string:
&"String":
to_type = TYPE_PACKED_STRING_ARRAY
&"int":
to_type = TYPE_PACKED_INT64_ARRAY
&"float":
to_type = TYPE_PACKED_FLOAT64_ARRAY
&"Vector2":
to_type = TYPE_PACKED_VECTOR2_ARRAY
&"Vector3":
to_type = TYPE_PACKED_VECTOR3_ARRAY
_:
if m.hint_string != "":
assert(false, DMConstants.translate(&"runtime.unsupported_array_type").format({ type = m.hint_string}))
if typeof(args[i]) != to_type:
args[i] = convert(args[i], to_type)
return await thing.callv(method, args)
# If we get here then it's probably a C# method with a Task return type
var dotnet_dialogue_manager = _get_dotnet_dialogue_manager()
dotnet_dialogue_manager.ResolveThingMethod(thing, method, args)
return await dotnet_dialogue_manager.Resolved
| 0 | 0.944306 | 1 | 0.944306 | game-dev | MEDIA | 0.70497 | game-dev | 0.924244 | 1 | 0.924244 |
ees4/KeepTradeCut-Scraper | 16,475 | ktc_to_sheets.py | import requests
from bs4 import BeautifulSoup
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from tqdm import tqdm
import sys,time,random
from datetime import date, datetime
"""
Scrapes all Superflex and 1QB values for all players in the live keeptradecut database.
Returns players where players is a list of player and pick dicts
"""
def scrape_ktc(scrape_redraft = False):
# universal vars
URL = "https://keeptradecut.com/dynasty-rankings?page={0}&filters=QB|WR|RB|TE|RDP&format={1}"
all_elements = []
players = []
for format in [1,0]:
if format == 1:
# find all elements with class "onePlayer"
for page in tqdm(range(10), desc="Linking to keeptradecut.com's 1QB rankings...",unit="page"):
page = requests.get(URL.format(page,format))
soup = BeautifulSoup(page.content, "html.parser")
player_elements = soup.find_all(class_="onePlayer")
for player_element in player_elements:
all_elements.append(player_element)
# player information
for player_element in all_elements:
# find elements within the player container
player_name_element = player_element.find(class_="player-name")
player_position_element = player_element.find(class_="position")
player_value_element = player_element.find(class_="value")
player_age_element = player_element.find(class_="position hidden-xs")
# extract player information
player_name = player_name_element.get_text(strip=True)
team_suffix = (player_name[-3:] if player_name[-3:] == 'RFA' else player_name[-4:] if player_name[-4] == 'R' else player_name[-2:] if player_name[-2:] == 'FA' else player_name[-3:] if player_name[-3:].isupper() else "")
# remove the team suffix
player_name = player_name.replace(team_suffix, "").strip()
player_position_rank = player_position_element.get_text(strip=True)
player_value = player_value_element.get_text(strip=True)
player_value = int(player_value)
player_position = player_position_rank[:2]
# handle NoneType for player_age_element
if player_age_element:
player_age_text = player_age_element.get_text(strip=True)
player_age = float(player_age_text[:4]) if player_age_text else 0
else:
player_age = 0
# split team and rookie
if team_suffix[0] == 'R':
player_team = team_suffix[1:]
player_rookie = "Yes"
else:
player_team = team_suffix
player_rookie = "No"
if player_position == "PI":
pick_info = {
"Player Name": player_name,
"Position Rank": None,
"Position": player_position,
"Team": None,
"Value": player_value,
"Age": None,
"Rookie": None,
"SFPosition Rank": None,
"SFValue": 0,
"RdrftPosition Rank": None,
"RdrftValue": 0,
"SFRdrftPosition Rank": None,
"SFRdrftValue": 0
}
players.append(pick_info)
else:
player_info = {
"Player Name": player_name,
"Position Rank": player_position_rank,
"Position": player_position,
"Team": player_team,
"Value": player_value,
"Age": player_age,
"Rookie": player_rookie,
"SFPosition Rank": None,
"SFValue": 0,
"RdrftPosition Rank": None,
"RdrftValue": 0,
"SFRdrftPosition Rank": None,
"SFRdrftValue": 0
}
players.append(player_info)
else:
# find all elements with class "onePlayer"
for page in tqdm(range(10), desc="Linking to keeptradecut.com's Superflex rankings...",unit="page"):
page = requests.get(URL.format(page,format))
soup = BeautifulSoup(page.content, "html.parser")
player_elements = soup.find_all(class_="onePlayer")
for player_element in player_elements:
all_elements.append(player_element)
for player_element in all_elements:
# find elements within the player container
player_name_element = player_element.find(class_="player-name")
player_position_element = player_element.find(class_="position")
player_value_element = player_element.find(class_="value")
player_age_element = player_element.find(class_="position hidden-xs")
# extract and print player information
player_name = player_name_element.get_text(strip=True)
team_suffix = (player_name[-3:] if player_name[-3:] == 'RFA' else player_name[-4:] if player_name[-4] == 'R' else player_name[-2:] if player_name[-2:] == 'FA' else player_name[-3:] if player_name[-3:].isupper() else "")
# remove the team suffix
player_name = player_name.replace(team_suffix, "").strip()
player_position_rank = player_position_element.get_text(strip=True)
player_position = player_position_rank[:2]
player_value = player_value_element.get_text(strip=True)
player_value = int(player_value)
if player_position == "PI":
for pick in players:
if pick["Player Name"] == player_name:
pick["SFValue"] = player_value
break
else:
for player in players:
if player["Player Name"] == player_name:
player["SFPosition Rank"] = player_position_rank
player["SFValue"] = player_value
break
# add ktc redraft values for 'contender'/'rebuilder' evaluation
if scrape_redraft:
players = add_redraft_values(players)
return players
"""
Given a scraped player value list, uploads those values to the appropriate sheet
using the appropriate league settings.
"""
def upload_to_league(players, gc, key, format='1QB', tep=0):
# modify data for the league's settings
if format == '1QB':
header = [f"Updated {date.today().strftime('%m/%d/%y')} at {datetime.now().strftime('%I:%M%p').lower()}", "Position Rank", "Position", "Team", "Value", "Age", "Rookie", "SFPosition Rank", "SFValue", "RdrftPosition Rank", "RdrftValue"]
# add player data to the rows database
rows_data = [[
player["Player Name"],
player["Position Rank"],
player["Position"],
player["Team"],
player["Value"],
player["Age"],
player["Rookie"],
player["SFPosition Rank"],
player["SFValue"],
player["RdrftPosition Rank"],
player["RdrftValue"]
] for player in players]
# add the header row
rows_data.insert(0,header)
elif format == 'SF':
header = [f"Updated {date.today().strftime('%m/%d/%y')} at {datetime.now().strftime('%I:%M%p').lower()}", "Position Rank", "Position", "Team", "Value", "Age", "Rookie", "1QBPosition Rank", "1QBValue", "RdrftPosition Rank", "RdrftValue"]
# add player data to the rows database
rows_data = [[
player["Player Name"],
player["SFPosition Rank"],
player["Position"],
player["Team"],
player["SFValue"],
player["Age"],
player["Rookie"],
player["Position Rank"],
player["Value"],
player["SFRdrftPosition Rank"],
player["SFRdrftValue"]
] for player in players]
# add the header row
rows_data.insert(0,header)
else:
sys.exit(f"Error: invalid format -- {format}")
# adjust player values by TEP setting
rows_data = tep_adjust(rows_data, tep)
# make player values unique for indexing and searchability
rows_data = make_unique(rows_data)
# open the spreadsheet, clear the first tab, append new data
print(f"Connecting to {key[1]} google sheet...")
spreadsheet = gc.open_by_key(key[0])
worksheet = spreadsheet.get_worksheet(0)
worksheet.clear()
worksheet.append_rows(rows_data)
print(f"Data upload to {key[1]} on {date.today().strftime('%B %d, %Y')} successful.")
"""
Scrapes all values for all players in the live keeptradecut database.
Returns players where players is a list of player and pick dicts
"""
def add_redraft_values(players):
# universal vars
URL = "https://keeptradecut.com/fantasy-rankings?page={0}&filters=QB|WR|RB|TE&format={1}"
all_elements = []
for format in [1,2]:
if format == 1:
# Find all elements with class "onePlayer"
for page in tqdm(range(10), desc="Linking to keeptradecut.com's Redraft 1QB rankings...",unit="page"):
page = requests.get(URL.format(page,format))
soup = BeautifulSoup(page.content, "html.parser")
player_elements = soup.find_all(class_="onePlayer")
for player_element in player_elements:
all_elements.append(player_element)
for player_element in all_elements:
# Find elements within the player container
player_name_element = player_element.find(class_="player-name")
player_position_element = player_element.find(class_="position")
player_value_element = player_element.find(class_="value")
# Extract and print player information
player_name = player_name_element.get_text(strip=True)
team_suffix = (player_name[-3:] if player_name[-3:] == 'RFA' else player_name[-4:] if player_name[-4] == 'R' else player_name[-2:] if player_name[-2:] == 'FA' else player_name[-3:] if player_name[-3:].isupper() else "")
# Remove the team suffix
player_name = player_name.replace(team_suffix, "").strip()
player_position_rank = player_position_element.get_text(strip=True)
player_value = player_value_element.get_text(strip=True)
player_value = int(player_value)
for player in players:
if player["Player Name"] == player_name:
player["RdrftPosition Rank"] = player_position_rank
player["RdrftValue"] = player_value
break
else:
# Find all elements with class "onePlayer"
for page in tqdm(range(10), desc="Linking to keeptradecut.com's Redraft Superflex rankings...",unit="page"):
page = requests.get(URL.format(page,format))
soup = BeautifulSoup(page.content, "html.parser")
player_elements = soup.find_all(class_="onePlayer")
for player_element in player_elements:
all_elements.append(player_element)
for player_element in all_elements:
# Find elements within the player container
player_name_element = player_element.find(class_="player-name")
player_position_element = player_element.find(class_="position")
player_value_element = player_element.find(class_="value")
# Extract and print player information
player_name = player_name_element.get_text(strip=True)
team_suffix = (player_name[-3:] if player_name[-3:] == 'RFA' else player_name[-4:] if player_name[-4] == 'R' else player_name[-2:] if player_name[-2:] == 'FA' else player_name[-3:] if player_name[-3:].isupper() else "")
# Remove the team suffix
player_name = player_name.replace(team_suffix, "").strip()
player_position_rank = player_position_element.get_text(strip=True)
player_value = player_value_element.get_text(strip=True)
player_value = int(player_value)
for player in players:
if player["Player Name"] == player_name:
player["SFRdrftPosition Rank"] = player_position_rank
player["SFRdrftValue"] = player_value
break
return players
"""
Given a preliminary set of player rows, adjusts the tight end values for any TEP
setting.
Returns an adjusted, re-sorted set of player rows
"""
def tep_adjust(rows_data, tep):
# sort the original values to make sure rows_data is ordered
header = rows_data[0]
rows_data = sorted(rows_data[1:], key=lambda x: x[4], reverse = True)
rows_data.insert(0,header)
# base case
if tep == 0:
return rows_data
# adjust constants based on TEP 'level'
s = 0.2
if tep == 1:
t_mult = 1.1
r = 250
elif tep == 2:
t_mult = 1.2
r = 350
elif tep == 3:
t_mult = 1.3
r = 450
else:
sys.exit(f"Error: invalid TEP value -- {tep}")
# adjust SF, 1QB, and optionally redraft values
values = [4, 8, 10] if rows_data[1][10] > 1 else [4, 8]
# adjust all tight end values based on TEP level
for value in values:
rank = 0
max_player_val = rows_data[1][value]
for player in rows_data[1:]:
if player[2] == "TE":
t = t_mult * player[value]
n = rank / (len(rows_data) - 25) * r + s * r
player[value] = min(max_player_val - 1, round(t + n,2))
rank += 1
# re-sort the adjusted values for the sheet
header = rows_data[0]
rows_data = sorted(rows_data[1:], key=lambda x: x[4], reverse = True)
rows_data.insert(0,header)
return rows_data
"""
Given a set of player rows, adjusts all the values to ensure they are unique.
Returns an adjusted, but not re-sorted, set of player rows
"""
def make_unique(rows_data):
# make SF, 1QB, and optionally redraft values unique
values = [4, 8, 10] if rows_data[1][10] > 1 else [4, 8]
# adjust all values
for value in values:
#initialize empty set of seen values
seen_values = set()
for player in rows_data:
current_value = player[value]
while current_value in seen_values:
# if the current value is a duplicate, subtract 0.01
current_value -= 0.01
# update the set of seen values
seen_values.add(current_value)
# update the new, unique player value
player[value] = current_value
return rows_data
"""
Main method
"""
if __name__ == "__main__":
# league sheet api keys
your_league_key = ['replace this with your google sheets key', "Nickname for Your Home League (for example)"]
# your_other_league_key = ['replace this', "Your other league (again, example)"]
# optionally, also pull redraft values for players in database
update_redraft = False
if "redraft" in sys.argv:
update_redraft = True
# pull all player and pick values
players = scrape_ktc(scrape_redraft=update_redraft)
# set up google sheets credentials
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name('YOUR_FILEPATH/credentials.json', scope)
gc = gspread.authorize(credentials)
# upload appropriate values/pick values to each sheet
upload_to_league(players, gc, your_league_key, format='1QB', tep=0)
# upload_to_league(players, gc, your_other_league_key, format='SF', tep=1)
| 0 | 0.512464 | 1 | 0.512464 | game-dev | MEDIA | 0.693804 | game-dev | 0.904444 | 1 | 0.904444 |
CFPAOrg/Modpack-GuideBook-i18n | 133,021 | project/FTB Interactions/2.12.1/scripts/gregtech.zs | import crafttweaker.item.IItemStack;
import crafttweaker.liquid.ILiquidStack;
import crafttweaker.item.IIngredient;
import mods.artisanworktables.builder.RecipeBuilder;
import mods.gregtech.recipe.RecipeMap;
import crafttweaker.data.IData;
import crafttweaker.oredict.IOreDict;
import crafttweaker.oredict.IOreDictEntry;
import crafttweaker.block.IBlockDefinition;
import crafttweaker.block.IBlockProperties;
import crafttweaker.block.IBlock;
import mods.contenttweaker.VanillaFactory;
import mods.contenttweaker.Block;
import mods.gregtech.recipe.RecipeMaps;
print("---------------Gregtech Start------------------");
val alloyer = mods.gregtech.recipe.RecipeMap.getByName("alloy_smelter");
val brewery = mods.gregtech.recipe.RecipeMap.getByName("brewer");
var fusionReactor = mods.gregtech.recipe.RecipeMap.getByName("fusion_reactor");
val extruder = mods.gregtech.recipe.RecipeMap.getByName("extruder");
val mixer = mods.gregtech.recipe.RecipeMap.getByName("mixer");
val implosion = mods.gregtech.recipe.RecipeMap.getByName("implosion_compressor");
val macerator = mods.gregtech.recipe.RecipeMap.getByName("macerator");
val assembler = mods.gregtech.recipe.RecipeMap.getByName("assembler");
val solidifier = mods.gregtech.recipe.RecipeMap.getByName("fluid_solidifier");
val plasma_arc_furnace = mods.gregtech.recipe.RecipeMap.getByName("plasma_arc_furnace");
val chemReactor = mods.gregtech.recipe.RecipeMap.getByName("chemical_reactor");
val forgeHammer = mods.gregtech.recipe.RecipeMap.getByName("forge_hammer");
val fluidExtractor = mods.gregtech.recipe.RecipeMap.getByName("fluid_extractor");
val extractor = mods.gregtech.recipe.RecipeMap.getByName("extractor");
val bender = mods.gregtech.recipe.RecipeMap.getByName("metal_bender");
val compressor = mods.gregtech.recipe.RecipeMap.getByName("compressor");
val electrolyzer = mods.gregtech.recipe.RecipeMap.getByName("electrolyzer");
val spinnyGoFast = mods.gregtech.recipe.RecipeMap.getByName("centrifuge");
val blast_furnace = mods.gregtech.recipe.RecipeMap.getByName("blast_furnace");
val arc_furnace = mods.gregtech.recipe.RecipeMap.getByName("arc_furnace");
val wiremill = mods.gregtech.recipe.RecipeMap.getByName("wiremill");
val packer = mods.gregtech.recipe.RecipeMap.getByName("packer");
val chemical_bath = mods.gregtech.recipe.RecipeMap.getByName("chemical_bath");
val lathe = mods.gregtech.recipe.RecipeMap.getByName("lathe");
val cracker = mods.gregtech.recipe.RecipeMap.getByName("cracker");
val autoclave = mods.gregtech.recipe.RecipeMap.getByName("autoclave");
val vacfreezer = mods.gregtech.recipe.RecipeMap.getByName("vacuum_freezer");
val thermalCent = mods.gregtech.recipe.RecipeMap.getByName("thermal_centrifuge");
val cutting_saw = mods.gregtech.recipe.RecipeMap.getByName("cutting_saw");
val assembly_line = mods.gregtech.recipe.RecipeMap.getByName("assembly_line");
val distillery = mods.gregtech.recipe.RecipeMap.getByName("distillery");
val distillation_tower = mods.gregtech.recipe.RecipeMap.getByName("distillery");
#AA crystal packaging
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal>)
.duration(10)
.EUt(12)
.buildAndRegister();
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard:1>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal:1>)
.duration(10)
.EUt(12)
.buildAndRegister();
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard:2>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal:2>)
.duration(10)
.EUt(12)
.buildAndRegister();
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard:3>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal:3>)
.duration(10)
.EUt(12)
.buildAndRegister();
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard:4>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal:4>)
.duration(10)
.EUt(12)
.buildAndRegister();
packer.recipeBuilder()
.inputs(<actuallyadditions:item_crystal_shard:5>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<actuallyadditions:item_crystal:5>)
.duration(10)
.EUt(12)
.buildAndRegister();
#emerald packager
packer.recipeBuilder()
.inputs(<ore:nuggetEmerald>*9)
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.outputs(<minecraft:emerald>)
.duration(10)
.EUt(12)
.buildAndRegister();
#bucket
lathe.recipeBuilder()
.inputs(<ore:blockIron>)
.outputs(<minecraft:bucket>*3)
.duration(60)
.EUt(18)
.buildAndRegister();
#iron block
compressor.recipeBuilder()
.inputs(<ore:ingotIron>*9)
.outputs(<ore:blockIron>.firstItem)
.duration(60)
.EUt(18)
.buildAndRegister();
#Gold block
compressor.recipeBuilder()
.inputs(<ore:ingotGold>*9)
.outputs(<ore:blockGold>.firstItem)
.duration(60)
.EUt(18)
.buildAndRegister();
#Polyeth bar from sheet
#Steel in arc furnace
arc_furnace.findRecipe(30,
[<ore:platePlastic>.firstItem],
[<liquid:oxygen> * 60])
.remove();
arc_furnace.recipeBuilder()
.inputs(<ore:platePlastic>)
.fluidInputs([<liquid:oxygen> * 60])
.outputs(<ore:ingotPlastic>.firstItem)
.duration(60)
.EUt(24)
.buildAndRegister();
#Steel in arc furnace
arc_furnace.recipeBuilder()
.inputs(<ore:ingotWroughtIron>)
.fluidInputs([<liquid:oxygen> * 60])
.outputs(<ore:ingotSteel>.firstItem)
.duration(60)
.EUt(24)
.buildAndRegister();
#Ardite in arc furnace
arc_furnace.recipeBuilder()
.inputs(<ore:dustArdite>)
.fluidInputs([<liquid:oxygen> * 60])
.outputs(<tconstruct:ingots:1>)
.duration(60)
.EUt(24)
.buildAndRegister();
#aluminium ore in arc furnace
arc_furnace.recipeBuilder()
.inputs(<ore:oreAluminium>)
.fluidInputs([<liquid:oxygen> * 60])
.outputs(<ore:ingotAluminium>.firstItem)
.duration(60)
.EUt(24)
.buildAndRegister();
#Ardite ore in arc furnace
arc_furnace.recipeBuilder()
.inputs(<ore:oreArdite>)
.fluidInputs([<liquid:oxygen> * 60])
.outputs(<tconstruct:ingots:1>)
.duration(60)
.EUt(24)
.buildAndRegister();
#tiny sulfur from tiny blaze powder
recipes.addShapeless(<gregtech:meta_item_1:65>, [<rusticthaumaturgy:dust_tiny_blaze>]);
#red alloy fix
bender.findRecipe(24,
[<ore:plateRedAlloy>.firstItem, <gregtech:meta_item_1:32766>.withTag({Configuration: 4})],
[null])
.remove();
#golden apples
macerator.findRecipe(8,
[<minecraft:golden_apple:1>],
[null])
.remove();
arc_furnace.findRecipe(30,
[<minecraft:golden_apple:1>],
[<liquid:oxygen>*4320])
.remove();
plasma_arc_furnace.findRecipe(10,
[<minecraft:golden_apple:1>],
[<liquid:plasma.argon>*6])
.remove();
plasma_arc_furnace.findRecipe(30,
[<minecraft:golden_apple:1>],
[<liquid:plasma.nitrogen>*19])
.remove();
bender.recipeBuilder()
.inputs(<ore:plateRedAlloy>.firstItem)
.notConsumable(integratedCircuit.withTag({Configuration: 4}))
.outputs(<ore:foilRedAlloy>.firstItem*4)
.duration(50)
.EUt(12)
.buildAndRegister();
#Remove useless LV Thermal Centrifuge
mods.jei.JEI.removeAndHide(<gregtech:machine:460>);
#woodentanks
mods.jei.JEI.removeAndHide(<gregtech:machine:811>);
recipes.addShaped(<gregtech:meta_tool:7>.withTag({"GT.ToolStats": {PrimaryMaterial: "rubber", MaxDurability: 256, DigSpeed: 4.0 as float, AttackDamage: 1.0 as float, HarvestLevel: 1}}),
[[<ore:itemRubber>, <ore:itemRubber>, null],
#soft hammer
[<ore:itemRubber>, <ore:itemRubber>, <ore:stickWood>],
[<ore:itemRubber>, <ore:itemRubber>, null]]);
mods.jei.JEI.addItem(<gregtech:meta_tool:7>.withTag({"GT.ToolStats": {PrimaryMaterial: "rubber", MaxDurability: 256, DigSpeed: 4.0 as float, AttackDamage: 1.0 as float, HarvestLevel: 1}}));
#Beacon Pulverization Nerf
macerator.findRecipe(8,
[<minecraft:beacon>],
[null])
.remove();
#remote GT Wheat
recipes.removeByRecipeName("gregtech:wheat_to_dust");
#GT Flour to Pam's Flour
recipes.addShaped(<harvestcraft:flouritem>, [[null, null, null],[null, <gregtech:meta_item_1:2345>, null], [null, null, null]]);
#thermal dusts from rods
macerator.recipeBuilder()
.inputs(<ore:rodBlizz>)
.outputs(<thermalfoundation:material:2049>*4)
.duration(120)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<ore:rodBasalz>)
.outputs(<thermalfoundation:material:2053>*4)
.duration(120)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<ore:rodBlitz>)
.outputs(<thermalfoundation:material:2051>*4)
.duration(120)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<minecraft:beacon>)
.outputs(<ore:dustGlass>.firstItem * 5)
.chancedOutput(<ore:powderMana>.firstItem * 4, 10000, 2000)
.chancedOutput(<ore:dustDiamond>.firstItem * 4, 10000, 2000)
.duration(30)
.EUt(7)
.buildAndRegister();
#Lutetium in Thermal Centrifurge
thermalCent.findRecipe(60,
[<ore:crushedPurifiedThorium>.firstItem],
[null])
.remove();
macerator.findRecipe(12,[<ore:crushedCentrifugedCoal>.firstItem],[null]).remove();
#remove thorium from coal
thermalCent.findRecipe(60,
[<ore:crushedPurifiedCoal>.firstItem],
[null])
.remove();
macerator.findRecipe(12,[<ore:crushedPurifiedCoal>.firstItem],[null]).remove();
macerator.recipeBuilder()
.inputs(<ore:crushedPurifiedCoal>)
.outputs(<ore:dustPureCoal>.firstItem)
.duration(200)
.EUt(12)
.buildAndRegister();
thermalCent.recipeBuilder()
.inputs([<ore:crushedPurifiedThorium>])
.outputs([<ore:crushedCentrifugedThorium>.firstItem, <ore:dustTinyLutetium>.firstItem * 3])
.EUt(60)
.duration(4600)
.buildAndRegister();
#awakened draconium
forgeHammer.recipeBuilder()
.inputs([<ore:blockDraconiumAwakened>])
.outputs([<draconicevolution:draconic_ingot>*9])
.EUt(24)
.duration(20)
.buildAndRegister();
#Netherite blocks to ingotts
forgeHammer.recipeBuilder()
.inputs([<netherbackport:netheriteblock>])
.outputs([<netherbackport:netheriteingot>*9])
.EUt(24)
.duration(20)
.buildAndRegister();
#Sphalerite Electrolysis
electrolyzer.recipeBuilder()
.inputs([<ore:dustSphalerite> * 2])
.outputs([<ore:dustZinc>.firstItem, <ore:dustSulfur>.firstItem])
.EUt(60)
.duration(600)
.buildAndRegister();
#remove Zeolite Electrolysis
electrolyzer.findRecipe(60, [<ore:dustZeolite>.firstItem*141],[]).remove();
electrolyzer.recipeBuilder()
.inputs([<ore:dustZeolite>*64])
.outputs([<ore:dustSodium>.firstItem, <ore:dustCalcium>.firstItem*4,<ore:dustSilicon>.firstItem*64, <ore:dustAluminium>.firstItem*9])
.fluidOutputs([<liquid:water> * 28000, <liquid:oxygen> * 32000])
.EUt(60)
.duration(1200)
.buildAndRegister();
#remove duplicate wheat recipe
macerator.findRecipe(8,
[<minecraft:wheat>],
[null])
.remove();
#remove wheat to plantball recipe
compressor.findRecipe(2,
[<minecraft:wheat>*8],
[null])
.remove();
compressor.findRecipe(2,
[<minecraft:wheat>*9],
[null])
.remove();
forgeHammer.recipeBuilder()
.inputs([<minecraft:wheat>*9])
.outputs([<minecraft:hay_block>])
.EUt(24)
.duration(20)
.buildAndRegister();
#Remove GT Chests
var generalDisabled as IItemStack[] = [
<gregtech:machine:802>,
<gregtech:machine:803>,
<gregtech:machine:804>,
<gregtech:machine:805>,
<gregtech:machine:806>
];
for i in generalDisabled {
mods.jei.JEI.removeAndHide(i);
}
#Lutetium in Pulverizer
macerator.findRecipe(12,
[<ore:crushedCentrifugedThorium>.firstItem],
[null])
.remove();
macerator.recipeBuilder()
.inputs([<ore:crushedPurifiedThorium>])
.outputs([<ore:dustThorium>.firstItem])
.chancedOutput(<ore:dustLutetium>.firstItem, 1400, 300)
.EUt(12)
.duration(40)
.buildAndRegister();
#diamond sawblade recipe
recipes.remove(<ore:craftingDiamondBlade>.firstItem);
recipes.addShaped(<ore:craftingDiamondBlade>.firstItem, [
[null, <ore:dustSmallDiamond>, null],
[<ore:dustSmallDiamond>, <ore:gearBrass>, <ore:dustSmallDiamond>],
[null, <ore:dustSmallDiamond>, null]]);
#salt water
mixer.findRecipe(8, [<ore:itemSalt>.firstItem], [<liquid:water> * 1000]).remove();
chemReactor.findRecipe(30, [<ore:dustNetherQuartz>.firstItem*3, <ore:dustSodium>.firstItem], [<liquid:water> * 1000]).remove();
#Salt water
chemReactor.recipeBuilder()
.inputs(<ore:itemSalt>)
.fluidInputs([<liquid:water> * 1000])
.fluidOutputs([<liquid:salt_water> * 1000])
.duration(160)
.EUt(18)
.buildAndRegister();
#Cluster Mills
mods.jei.JEI.removeAndHide(<gregtech:machine:2008>);
mods.jei.JEI.removeAndHide(<gregtech:machine:2009>);
mods.jei.JEI.removeAndHide(<gregtech:machine:2010>);
mods.jei.JEI.removeAndHide(<gregtech:machine:2011>);
#platinum sludge
chemReactor.findRecipe(30, [<ore:crushedPurifiedChalcopyrite>.firstItem], [<liquid:nitric_acid> * 1000]).remove();
chemReactor.findRecipe(30, [<ore:crushedPurifiedPentlandite>.firstItem], [<liquid:nitric_acid> * 1000]).remove();
chemReactor.findRecipe(30, [<ore:crushedPurifiedPentlandite>.firstItem], [<liquid:nitric_acid> * 1000]).remove();
spinnyGoFast.findRecipe(30, [<ore:dustPlatinumGroupSludge>.firstItem], [null]).remove();
mods.jei.JEI.removeAndHide(<ore:dustSmallPlatinumGroupSludge>.firstItem);
mods.jei.JEI.removeAndHide(<ore:dustPlatinumGroupSludge>.firstItem);
mods.jei.JEI.removeAndHide(<ore:dustTinyPlatinumGroupSludge>.firstItem);
mods.jei.JEI.removeAndHide(<ore:blockPlatinumGroupSludge>.firstItem);
#useless basic laser engraver
mods.jei.JEI.removeAndHide(<meta_tile_entity:gregtech:laser_engraver.lv>);
#Autoclave additions for missing gems
var autoclaveGems as string[] = [
"Topaz",
"Tanzanite",
"Almandine",
"BlueTopaz",
"Jasper",
"GarnetRed",
"GarnetYellow",
"Vinteum"
];
for input in autoclaveGems {
var dust as IItemStack = oreDict["crushedPurified"~input].firstItem;
var gem as IItemStack = oreDict["gem"~input].firstItem;
autoclave.recipeBuilder()
.inputs(dust * 1)
.fluidInputs([<liquid:water> * 1000])
.chancedOutput(gem, 5000, 750)
.duration(2000)
.EUt(24)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(dust * 1)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(gem * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
}
#saltpeter
autoclave.recipeBuilder()
.inputs(<ore:itemSalt>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 20])
.outputs(<ore:dustSaltpeter>.firstItem)
.duration(100)
.EUt(18)
.buildAndRegister();
#thaumcraft dusts
autoclave.recipeBuilder()
.inputs(<ore:dustAerInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "aer"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustAquaInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "aqua"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustIgnisInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "ignis"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustTerraInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "terra"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustEntropyInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "perditio"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustOrdoInfused>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<thaumcraft:crystal_essence>.withTag({Aspects: [{amount: 1, key: "ordo"}]}) * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
#lazurite
autoclave.recipeBuilder()
.inputs(<ore:dustLazurite> * 1)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<ore:gemLazurite>.firstItem * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
#Iron Bar Loop
macerator.findRecipe(8, [<minecraft:iron_bars>], []).remove();
macerator.recipeBuilder()
.inputs(<minecraft:iron_bars>)
.outputs(<ore:dustTinyIron>.firstItem * 3)
.duration(80)
.EUt(8)
.buildAndRegister();
#steam turbine reicpe
recipes.remove(<gregtech:machine:518>);
recipes.addShaped(<gregtech:machine:518>,
[[<ore:circuitHigh>, <ore:gearSteel>, <ore:circuitHigh>],
[<ore:gearSteel>, <gregtech:machine:504>, <ore:gearSteel>],
[<ore:plateVinteum>, <ore:gearSteel>, <ore:plateVinteum>]]);
#Advanced Alloy
recipes.removeByRecipeName("gregtech:ingot_mixed_metal");
#coal autoclave
autoclave.recipeBuilder()
.inputs(<ore:dustCoal>)
.fluidInputs([<liquid:water> * 1000])
.chancedOutput(<minecraft:coal>, 5000, 750)
.duration(2000)
.EUt(24)
.buildAndRegister();
autoclave.recipeBuilder()
.inputs(<ore:dustCoal>)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 10])
.outputs(<minecraft:coal> * 1)
.duration(100)
.EUt(4)
.buildAndRegister();
#Certus Quartz Rod (additional faster recipe)
lathe.recipeBuilder()
.inputs(<ore:crystalPureCertusQuartz> * 4)
.outputs(<ore:stickCertusQuartz>.firstItem)
.duration(80)
.EUt(30)
.buildAndRegister();
#Energium Autoclave - Liquid Starlight
autoclave.recipeBuilder()
.inputs(<metaitem:energium_dust> * 9)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 225])
.outputs(<metaitem:energy_crystal>)
.duration(200)
.EUt(120)
.buildAndRegister();
#Nether Quartz Rod (additional faster recipe)
lathe.recipeBuilder()
.inputs(<ore:crystalPureNetherQuartz> * 4)
.outputs(<ore:stickNetherQuartz>.firstItem)
.duration(80)
.EUt(30)
.buildAndRegister();
#ender pearls
fluidExtractor.recipeBuilder()
.inputs(<ore:enderpearl> * 1)
.fluidOutputs([<liquid:ender> * 250])
.duration(160)
.EUt(18)
.buildAndRegister();
#molten infinity
fluidExtractor.recipeBuilder()
.inputs(<contenttweaker:infinityegg> * 1)
.fluidOutputs([<liquid:infinity> * 144])
.duration(80)
.EUt(18)
.buildAndRegister();
//remove duplicate nobel gas recipe
spinnyGoFast.findRecipe(7420, [null], [<liquid:liquid_air>*53000]).remove();
//remove thorium from coal
spinnyGoFast.findRecipe(1152, [<ore:dustImpureCoal>.firstItem], [null]).remove();
spinnyGoFast.findRecipe(240, [<ore:dustPureCoal>.firstItem], [null]).remove();
spinnyGoFast.recipeBuilder()
.inputs(<ore:dustImpureCoal>.firstItem)
.outputs(<ore:dustCoal>.firstItem)
.chancedOutput(<ore:dustTinyCarbon>.firstItem, 8500, 1000)
.duration(48)
.EUt(24)
.buildAndRegister();
spinnyGoFast.recipeBuilder()
.inputs(<ore:dustPureCoal>.firstItem)
.outputs(<ore:dustCoal>.firstItem)
.chancedOutput(<ore:dustTinyCarbon>.firstItem, 8500, 1000)
.duration(48)
.EUt(5)
.buildAndRegister();
spinnyGoFast.recipeBuilder()
.fluidInputs([<liquid:liquid_air> * 53000])
.fluidOutputs([<liquid:nitrogen> * 40000,<liquid:oxygen> * 11000,<liquid:argon> * 1000,<liquid:noble_gases> * 1000])
.duration(1484)
.EUt(30)
.buildAndRegister();
spinnyGoFast.recipeBuilder()
.fluidInputs([<liquid:ender_distillation> * 1000])
.fluidOutputs([<liquid:neutral_matter> * 100])
.chancedOutput(<ore:dustPhosphorus>.firstItem, 5500, 2500)
.chancedOutput(<ore:dustBeryllium>.firstItem, 5500, 2500)
.chancedOutput(<ore:dustPotassium>.firstItem, 8500, 2500)
.chancedOutput(<ore:dustSmallBarium>.firstItem, 8500, 2500)
.chancedOutput(<ore:dustSmallLanthanum>.firstItem, 8500, 2500)
.chancedOutput(<ore:dustTinyNeodymium>.firstItem, 8500, 2500)
.duration(200)
.EUt(1920)
.buildAndRegister();
#ferric turf
spinnyGoFast.recipeBuilder()
.inputs(<advancedrocketry:hotturf>)
.chancedOutput(<ore:dustSilicon>.firstItem, 8500, 1000)
.chancedOutput(<ore:dustSmallIron>.firstItem, 5500, 850)
.chancedOutput(<ore:dustSmallUranium>.firstItem, 3500, 500)
.chancedOutput(<ore:dustSmallPlutonium>.firstItem, 3000, 450)
.chancedOutput(<ore:dustSmallNaquadah>.firstItem, 1500, 200)
.chancedOutput(<ore:dustTinyPlutonium241>.firstItem, 500, 100)
.fluidOutputs([<liquid:sludge> * 100])
.duration(480)
.EUt(30)
.buildAndRegister();
#Flour
mods.primaltech.StoneAnvil.addRecipe(<ore:dustWheat>.firstItem, <minecraft:wheat>);
#Ashes
RecipeBuilder.get("basic")
.setShapeless([<primal_tech:charcoal_block>])
.addTool(<ore:artisanHammers>, 10)
.addOutput(<ore:dustAsh>.firstItem)
.create();
#Bronze hull
recipes.remove(<gregtech:machine_casing:11>);
recipes.addShaped(<gregtech:machine_casing:11>,
[[<ore:plateBronze>, <ore:plateBrass>, <ore:plateBronze>],
[<ore:plateBronze>, craftingToolHardHammer, <ore:plateBronze>],
[<minecraft:brick_block>, <minecraft:brick_block>, <minecraft:brick_block>]]);
#Bronze Hull
recipes.remove(<gregtech:machine_casing:10>);
recipes.addShaped(<gregtech:machine_casing:10>,[
[<ore:plateBronze>, <ore:plateBronze>, <ore:plateBronze>],
[<ore:plateBrass>, craftingToolHardHammer, <ore:plateBrass>],
[<ore:plateBronze>, <ore:plateBronze>, <ore:plateBronze>]]);
#Biomass (Alternate)
brewery.recipeBuilder()
.inputs(<ore:botaniaPetals> * 1)
.fluidInputs([<liquid:water> * 100])
.fluidOutputs([<liquid:biomass> * 300])
.duration(750)
.EUt(3)
.buildAndRegister();
brewery.recipeBuilder()
.inputs(<ore:botaniaPetals> * 1)
.fluidInputs([<liquid:honey> * 100])
.fluidOutputs([<liquid:biomass> * 500])
.duration(600)
.EUt(3)
.buildAndRegister();
#remove tungsten/titanium Boiler upgraes
assembler.findRecipe(500, [<ore:plateTitanium>.firstItem*2, <ore:circuitHigh>.firstItem*2, <gregtech:machine:522>], [null]).remove();
assembler.findRecipe(2000, [<ore:plateTungstenSteel>.firstItem*2, <ore:circuitHigh>.firstItem*2, <gregtech:machine:523>], [null]).remove();
#wool from woven cotten
assembler.recipeBuilder()
.inputs(<harvestcraft:wovencottonitem>*2)
.outputs(<minecraft:wool>)
.duration(20)
.EUt(8)
.buildAndRegister();
#Bronze to steel
assembler.recipeBuilder()
.inputs(<gregtech:metal_casing>, <ore:plateSteel> *2)
.outputs(<gregtech:metal_casing:4>)
.duration(50)
.EUt(8)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<meta_tile_entity:gregtech:large_boiler.bronze>, <ore:cableGtSingleCopper> *4, <ore:circuitHigh> *4)
.outputs(<meta_tile_entity:gregtech:large_boiler.steel>)
.duration(50)
.EUt(8)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<gregtech:boiler_firebox_casing>, <ore:plateSteel> *2)
.outputs(<gregtech:boiler_firebox_casing:1>)
.duration(50)
.EUt(8)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<gregtech:boiler_casing>, <ore:plateSteel> *5)
.outputs(<gregtech:boiler_casing:1>)
.duration(50)
.EUt(8)
.buildAndRegister();
#Drums
assembler.recipeBuilder()
.inputs(<ore:stickLongTitanium>*2, <ore:plateTitanium>*4)
.outputs(<gregtech:machine:2199>)
.duration(80)
.EUt(18)
.buildAndRegister();
#Cheaper diesel engine
assembler.recipeBuilder()
.inputs(<ore:stickLongStainlessSteel>*2, <ore:plateStainlessSteel>*4)
.outputs(<gregtech:machine:2198>)
.duration(80)
.EUt(18)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<ore:stickLongTungstenSteel>*2, <ore:plateTungstenSteel>*4)
.outputs(<gregtech:machine:2200>)
.duration(80)
.EUt(18)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<ore:stickLongSteel>*2, <ore:plateSteel>*4)
.outputs(<gregtech:machine:2197>)
.duration(80)
.EUt(18)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<ore:stickLongBronze>*2, <ore:plateBronze>*4)
.outputs(<gregtech:machine:2196>)
.duration(80)
.EUt(18)
.buildAndRegister();
#assembly line casing
assembler.recipeBuilder()
.inputs(<gregtech:meta_item_1:32654>*2, <ore:frameGtTungstenSteel>, <ore:plateSteel>*4)
.outputs(<gtadditions:ga_multiblock_casing:1>*2)
.duration(80)
.EUt(18)
.buildAndRegister();
#remove and hide tanks
mods.jei.JEI.removeAndHide(<gregtech:machine:811>);
mods.jei.JEI.removeAndHide(<gregtech:machine:812>);
mods.jei.JEI.removeAndHide(<gregtech:machine:813>);
mods.jei.JEI.removeAndHide(<gregtech:machine:814>);
mods.jei.JEI.removeAndHide(<gregtech:machine:815>);
mods.jei.JEI.removeAndHide(<gregtech:machine:816>);
#remove titanium and tungstensteel boilers
mods.jei.JEI.removeAndHide(<gregtech:machine:523>);
mods.jei.JEI.removeAndHide(<gregtech:machine:524>);
#Turbine Upgrades
assembler.recipeBuilder()
.inputs(<gregtech:turbine_casing:5>, <ore:plateTitanium> *2)
.outputs(<gregtech:turbine_casing:4>)
.duration(100)
.EUt(8)
.buildAndRegister();
assembler.recipeBuilder()
.inputs(<gregtech:turbine_casing:4>, <ore:plateTungstenSteel> *2)
.outputs(<gregtech:turbine_casing:6>)
.duration(150)
.EUt(8)
.buildAndRegister();
#cryogenic oxygen and hydrogen
chemReactor.recipeBuilder()
.inputs(<ore:dustCryotheum>)
.fluidInputs([<liquid:oxygen> * 10000])
.fluidOutputs([<liquid:cryogenicoxygen> * 1000])
.duration(50)
.EUt(120)
.buildAndRegister();
chemReactor.recipeBuilder()
.inputs(<ore:dustCryotheum>)
.fluidInputs([<liquid:hydrogen> * 10000])
.fluidOutputs([<liquid:cryogenichydrogen> * 1000])
.duration(50)
.EUt(120)
.buildAndRegister();
#saltpeter from salt
mods.astralsorcery.LightTransmutation.addTransmutation(<ore:blockSalt>.firstItem, <ore:blockSaltpeter>.firstItem, 200);
#Tetranitromethane from glowstone
chemReactor.recipeBuilder()
.inputs(<ore:dustGlowstone>)
.fluidInputs([<liquid:ethenone> * 1000])
.fluidOutputs([<liquid:tetranitromethane> * 2000])
.duration(200)
.EUt(192)
.buildAndRegister();
#Removing Ash Centrifuge into byproducts
spinnyGoFast.findRecipe(30, [<ore:dustAsh>.firstItem], [null]).remove();
#Adding Add to Carbon Dust Centrifurge
spinnyGoFast.recipeBuilder()
.inputs(<ore:dustAsh>)
.outputs(<ore:dustCarbon>.firstItem)
.duration(24)
.EUt(30)
.buildAndRegister();
#Diamond from graphite
implosion.recipeBuilder()
.inputs(<ore:ingotGraphite> *3)
.property("explosives", 2)
.outputs(<minecraft:diamond>)
.duration(40)
.EUt(32)
.buildAndRegister();
#Diamond from diamond dust
implosion.recipeBuilder()
.inputs(<ore:dustDiamond> *3)
.property("explosives", 1)
.outputs(<minecraft:diamond>)
.duration(40)
.EUt(32)
.buildAndRegister();
#remove duplicate diamond nugget
recipes.removeByRecipeName("gregtech:nugget_disassembling_diamond");
#fix gold dust
recipes.removeByRecipeName("gregtech:plate_to_dust_gold");
recipes.removeShaped(<ore:dustGold>.firstItem,
[[null,<ore:plateGold>,null],
[null, craftingToolMortar,null],
[null,null,null]]);
recipes.addShaped(<ore:dustGold>.firstItem,
[[null,<ore:ingotGold>,null],
[null, craftingToolMortar,null],
[null,null,null]]);
#fix iron dust
recipes.removeByRecipeName("gregtech:plate_to_dust_iron");
recipes.removeShaped(<ore:dustIron>.firstItem,
[[null,<ore:plateIron>,null],
[null, craftingToolMortar,null],
[null,null,null]]);
recipes.addShaped(<ore:dustIron>.firstItem,
[[null,<ore:ingotIron>,null],
[null, craftingToolMortar,null],
[null,null,null]]);
#Fine Wire Fix
var fineWireMaterials as string[] = [
"Chrome",
"Darmstadtium",
"Palladium",
"Brass",
"Invar",
"Magnalium",
"Epoxid",
"StainlessSteel",
"TinAlloy",
"Ultimet",
"Bronze",
"WroughtIron",
"Osmiridium",
"SterlingSilver",
"RoseGold",
"BlackBronze",
"BismuthBronze",
"CobaltBrass",
"NeodymiumMagnetic",
"TungstenCarbide",
"VanadiumSteel",
"Hsse",
"Hsss",
"Neutronium",
"Iridium"
];
for name in fineWireMaterials {
var rod as IItemStack = oreDict["stick"~name].firstItem;
var fine as IItemStack = oreDict["wireFine"~name].firstItem;
wiremill.recipeBuilder()
.inputs(rod)
.outputs(fine*2)
.EUt(24)
.duration(80)
.buildAndRegister();
}
#sawdust from menril crystals
macerator.recipeBuilder()
.inputs(<ore:crystalMenril>)
.outputs(<thermalfoundation:material:800>*6)
.duration(30)
.EUt(8)
.buildAndRegister();
#Macerate drums back to dusts
macerator.recipeBuilder()
.inputs(<gregtech:machine:2196>)
.outputs(<ore:dustBronze>.firstItem*6)
.duration(30)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<gregtech:machine:2198>)
.outputs(<ore:dustStainlessSteel>.firstItem*6)
.duration(30)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<gregtech:machine:2197>)
.outputs(<ore:dustSteel>.firstItem*6)
.duration(30)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<gregtech:machine:2199>)
.outputs(<ore:dustTitanium>.firstItem*6)
.duration(30)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<gregtech:machine:2200>)
.outputs(<ore:dustTungstenSteel>.firstItem*6)
.duration(30)
.EUt(8)
.buildAndRegister();
#Honey
fluidExtractor.recipeBuilder()
.inputs(<harvestcraft:honeyitem>)
.fluidOutputs([<liquid:honey> * 250])
.duration(100)
.EUt(30)
.buildAndRegister();
#rubber sapling
mods.bloodmagic.AlchemyArray.addRecipe(<gregtech:sapling>, <actuallyadditions:item_misc:12>, <minecraft:sapling>);
mods.bloodmagic.AlchemyArray.addRecipe(<gregtech:sapling>, <minecraft:slime_ball>, <minecraft:sapling>);
mods.bloodmagic.AlchemyArray.addRecipe(<gregtech:sapling>, <tconstruct:edible:3>, <minecraft:sapling>);
#marble
furnace.addRecipe(<gregtech:mineral>, <gregtech:mineral:4>);
#ore transmutations
<gregtech:machine:2183>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2184>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2185>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2187>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2186>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2188>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2189>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:machine:2190>.addTooltip(format.darkRed("使用液体单元来复制液体,不要用桶。"));
<gregtech:ore_thorium_0>.addTooltip(format.darkRed("通过将焦黑石英块作为催化剂的坠星标位仪式获得。"));
<actuallyadditions:block_misc:2>.addTooltip(format.darkRed("可用作坠星标位的催化剂。"));
<gregtech:ore_uranium_0>.addTooltip(format.darkRed("通过星辉转化钍矿获得。"));
#Blue steel alloy
alloyer.recipeBuilder()
.inputs(<ore:dustLazurite>, <ore:ingotSteel> * 2 )
.outputs(<ore:ingotBluesteel>.firstItem *2)
.duration(40)
.EUt(12)
.buildAndRegister();
#CEF/CEU Conversions
#Remove useless ICEU/ICEF
mods.jei.JEI.removeAndHide(<gregtech:machine:10722>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10723>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10724>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10725>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10726>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10727>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10728>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10729>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10730>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10731>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10732>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10733>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10734>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10735>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10736>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10737>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10738>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10739>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10740>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10741>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10742>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10743>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10744>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10745>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10746>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10747>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10748>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10749>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10750>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10751>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10752>);
mods.jei.JEI.removeAndHide(<gregtech:machine:10753>);
#CEU to CEF conversion recipes
recipes.addShapeless(<gregtech:machine:10650>, [<gregtech:machine:10651>]);
recipes.addShapeless(<gregtech:machine:10652>, [<gregtech:machine:10653>]);
recipes.addShapeless(<gregtech:machine:10654>, [<gregtech:machine:10655>]);
recipes.addShapeless(<gregtech:machine:10656>, [<gregtech:machine:10657>]);
recipes.addShapeless(<gregtech:machine:10658>, [<gregtech:machine:10659>]);
recipes.addShapeless(<gregtech:machine:10660>, [<gregtech:machine:10661>]);
recipes.addShapeless(<gregtech:machine:10662>, [<gregtech:machine:10663>]);
recipes.addShapeless(<gregtech:machine:10664>, [<gregtech:machine:10665>]);
recipes.addShapeless(<gregtech:machine:10666>, [<gregtech:machine:10667>]);
recipes.addShapeless(<gregtech:machine:10668>, [<gregtech:machine:10669>]);
recipes.addShapeless(<gregtech:machine:10670>, [<gregtech:machine:10671>]);
recipes.addShapeless(<gregtech:machine:10672>, [<gregtech:machine:10673>]);
recipes.addShapeless(<gregtech:machine:10674>, [<gregtech:machine:10675>]);
recipes.addShapeless(<gregtech:machine:10676>, [<gregtech:machine:10677>]);
recipes.addShapeless(<gregtech:machine:10678>, [<gregtech:machine:10679>]);
recipes.addShapeless(<gregtech:machine:10680>, [<gregtech:machine:10681>]);
recipes.addShapeless(<gregtech:machine:10682>, [<gregtech:machine:10683>]);
recipes.addShapeless(<gregtech:machine:10684>, [<gregtech:machine:10685>]);
recipes.addShapeless(<gregtech:machine:10686>, [<gregtech:machine:10687>]);
recipes.addShapeless(<gregtech:machine:10688>, [<gregtech:machine:10689>]);
recipes.addShapeless(<gregtech:machine:10690>, [<gregtech:machine:10691>]);
recipes.addShapeless(<gregtech:machine:10692>, [<gregtech:machine:10693>]);
recipes.addShapeless(<gregtech:machine:10694>, [<gregtech:machine:10695>]);
recipes.addShapeless(<gregtech:machine:10696>, [<gregtech:machine:10697>]);
recipes.addShapeless(<gregtech:machine:10698>, [<gregtech:machine:10699>]);
recipes.addShapeless(<gregtech:machine:10700>, [<gregtech:machine:10701>]);
recipes.addShapeless(<gregtech:machine:10702>, [<gregtech:machine:10703>]);
recipes.addShapeless(<gregtech:machine:10704>, [<gregtech:machine:10705>]);
recipes.addShapeless(<gregtech:machine:10706>, [<gregtech:machine:10707>]);
recipes.addShapeless(<gregtech:machine:10708>, [<gregtech:machine:10709>]);
recipes.addShapeless(<gregtech:machine:10710>, [<gregtech:machine:10711>]);
recipes.addShapeless(<gregtech:machine:10712>, [<gregtech:machine:10713>]);
recipes.addShapeless(<gregtech:machine:10714>, [<gregtech:machine:10715>]);
recipes.addShapeless(<gregtech:machine:10716>, [<gregtech:machine:10717>]);
recipes.addShapeless(<gregtech:machine:10718>, [<gregtech:machine:10719>]);
recipes.addShapeless(<gregtech:machine:10720>, [<gregtech:machine:10721>]);
#CEF to CEU conversion recipes
recipes.addShapeless(<gregtech:machine:10651>, [<gregtech:machine:10650>]);
recipes.addShapeless(<gregtech:machine:10653>, [<gregtech:machine:10652>]);
recipes.addShapeless(<gregtech:machine:10655>, [<gregtech:machine:10654>]);
recipes.addShapeless(<gregtech:machine:10657>, [<gregtech:machine:10656>]);
recipes.addShapeless(<gregtech:machine:10659>, [<gregtech:machine:10658>]);
recipes.addShapeless(<gregtech:machine:10661>, [<gregtech:machine:10660>]);
recipes.addShapeless(<gregtech:machine:10663>, [<gregtech:machine:10662>]);
recipes.addShapeless(<gregtech:machine:10665>, [<gregtech:machine:10664>]);
recipes.addShapeless(<gregtech:machine:10667>, [<gregtech:machine:10666>]);
recipes.addShapeless(<gregtech:machine:10669>, [<gregtech:machine:10668>]);
recipes.addShapeless(<gregtech:machine:10671>, [<gregtech:machine:10670>]);
recipes.addShapeless(<gregtech:machine:10673>, [<gregtech:machine:10672>]);
recipes.addShapeless(<gregtech:machine:10675>, [<gregtech:machine:10674>]);
recipes.addShapeless(<gregtech:machine:10677>, [<gregtech:machine:10676>]);
recipes.addShapeless(<gregtech:machine:10679>, [<gregtech:machine:10678>]);
recipes.addShapeless(<gregtech:machine:10681>, [<gregtech:machine:10680>]);
recipes.addShapeless(<gregtech:machine:10683>, [<gregtech:machine:10682>]);
recipes.addShapeless(<gregtech:machine:10685>, [<gregtech:machine:10684>]);
recipes.addShapeless(<gregtech:machine:10687>, [<gregtech:machine:10686>]);
recipes.addShapeless(<gregtech:machine:10689>, [<gregtech:machine:10688>]);
recipes.addShapeless(<gregtech:machine:10691>, [<gregtech:machine:10690>]);
recipes.addShapeless(<gregtech:machine:10693>, [<gregtech:machine:10692>]);
recipes.addShapeless(<gregtech:machine:10695>, [<gregtech:machine:10694>]);
recipes.addShapeless(<gregtech:machine:10697>, [<gregtech:machine:10696>]);
recipes.addShapeless(<gregtech:machine:10699>, [<gregtech:machine:10698>]);
recipes.addShapeless(<gregtech:machine:10701>, [<gregtech:machine:10700>]);
recipes.addShapeless(<gregtech:machine:10703>, [<gregtech:machine:10702>]);
recipes.addShapeless(<gregtech:machine:10705>, [<gregtech:machine:10704>]);
recipes.addShapeless(<gregtech:machine:10707>, [<gregtech:machine:10706>]);
recipes.addShapeless(<gregtech:machine:10709>, [<gregtech:machine:10708>]);
recipes.addShapeless(<gregtech:machine:10711>, [<gregtech:machine:10710>]);
recipes.addShapeless(<gregtech:machine:10713>, [<gregtech:machine:10712>]);
recipes.addShapeless(<gregtech:machine:10715>, [<gregtech:machine:10714>]);
recipes.addShapeless(<gregtech:machine:10717>, [<gregtech:machine:10716>]);
recipes.addShapeless(<gregtech:machine:10719>, [<gregtech:machine:10718>]);
recipes.addShapeless(<gregtech:machine:10721>, [<gregtech:machine:10720>]);
#Bronze hulls
alloyer.recipeBuilder()
.inputs(<ore:plateBronze>*6, <ore:plateBrass> * 2 )
.outputs(<gregtech:machine_casing:10>)
.duration(40)
.EUt(12)
.buildAndRegister();
alloyer.recipeBuilder()
.inputs(<gregtech:machine_casing:10>, <ore:blockBrick>*3)
.outputs(<gregtech:machine_casing:11>*2)
.duration(40)
.EUt(12)
.buildAndRegister();
alloyer.recipeBuilder()
.inputs(<ore:dustLapis>, <ore:ingotSteel> * 4 )
.outputs(<ore:ingotBluesteel>.firstItem * 4)
.duration(60)
.EUt(12)
.buildAndRegister();
var moldsToChisel as IItemStack[] = [
<gregtech:meta_item_1:32300>,
<gregtech:meta_item_1:32317>,
<gregtech:meta_item_1:32305>,
<gregtech:meta_item_1:32304>,
<gregtech:meta_item_1:32303>,
<gregtech:meta_item_1:32301>,
<gregtech:meta_item_1:32315>,
<gregtech:meta_item_1:32314>,
<gregtech:meta_item_1:32313>,
<gregtech:meta_item_1:32309>,
<gregtech:meta_item_1:32308>,
<gregtech:meta_item_1:32307>,
<gregtech:meta_item_1:32306>,
<gregtech:meta_item_1:32373>,
<gregtech:meta_item_1:32372>,
<contenttweaker:smallgearextrudershape>,
<gregtech:meta_item_1:32371>,
<gregtech:meta_item_1:32370>,
<gregtech:meta_item_1:32369>,
<gregtech:meta_item_1:32368>,
<gregtech:meta_item_1:32367>,
<gregtech:meta_item_1:32366>,
<gregtech:meta_item_1:32365>,
<gregtech:meta_item_1:32364>,
<gregtech:meta_item_1:32363>,
<gregtech:meta_item_1:32360>,
<gregtech:meta_item_1:32361>,
<gregtech:meta_item_1:32359>,
<gregtech:meta_item_1:32358>,
<gregtech:meta_item_1:32356>,
<gregtech:meta_item_1:32355>,
<gregtech:meta_item_1:32354>,
<gregtech:meta_item_1:32353>,
<gregtech:meta_item_1:32352>,
<gregtech:meta_item_1:32351>,
<gregtech:meta_item_1:32350>
];
for i in moldsToChisel {
i.addTooltip(format.darkRed("可以通过雕凿其他模具获得。"));
mods.chisel.Carving.addVariation("GTMolds", i);
}
#Pump - LV
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTin>, <ore:ringPaper> * 2, <ore:pipeMediumBronze>, <metaitem:electric.motor.lv>])
.fluidInputs([<liquid:tin> * 648])
.outputs(<metaitem:electric.pump.lv>)
.EUt(15)
.duration(1200)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTin>, <ore:ringRubber> * 2, <ore:pipeMediumBronze>, motorLV])
.fluidInputs([<liquid:tin> * 648])
.outputs(pumpLV)
.EUt(15)
.duration(600)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTin>, <ore:ringStyreneButadieneRubber> * 2, <ore:pipeMediumBronze>, motorLV])
.fluidInputs([<liquid:tin> * 648])
.outputs(pumpLV)
.EUt(15)
.duration(300)
.buildAndRegister();
#Pump - MV
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleCopper>, <ore:ringRubber> * 2, <ore:pipeMediumSteel>, <metaitem:electric.motor.mv>])
.fluidInputs([<liquid:bronze> * 648])
.outputs(pumpMV)
.EUt(60)
.duration(1200)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleCopper>, <ore:ringStyreneButadieneRubber> * 2, <ore:pipeMediumSteel>, motorMV])
.fluidInputs([<liquid:bronze> * 648])
.outputs(pumpMV)
.EUt(60)
.duration(600)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleCopper>, <ore:ringSiliconRubber> * 2, <ore:pipeMediumSteel>, motorMV])
.fluidInputs([<liquid:bronze> * 648])
.outputs(pumpMV)
.EUt(60)
.duration(300)
.buildAndRegister();
#Pump - HV
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleGold>, <ore:ringRubber> * 2, <ore:pipeMediumStainlessSteel>, motorHV])
.fluidInputs([<liquid:steel> * 648])
.outputs(pumpHV)
.EUt(240)
.duration(1200)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleGold>, <ore:ringStyreneButadieneRubber> * 2, <ore:pipeMediumStainlessSteel>, motorHV])
.fluidInputs([<liquid:steel> * 648])
.outputs(pumpHV)
.EUt(240)
.duration(600)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleGold>, <ore:ringSiliconRubber> * 2, <ore:pipeMediumStainlessSteel>, motorHV])
.fluidInputs([<liquid:steel> * 648])
.outputs(pumpHV)
.EUt(240)
.duration(300)
.buildAndRegister();
#Pump - EV
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleAluminium>, <ore:ringRubber> * 2, <ore:pipeMediumTitanium>, motorEV])
.fluidInputs([<liquid:stainless_steel> * 648])
.outputs(pumpEV)
.EUt(960)
.duration(1200)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleAluminium>, <ore:ringStyreneButadieneRubber> * 2, <ore:pipeMediumTitanium>, motorEV])
.fluidInputs([<liquid:stainless_steel> * 648])
.outputs(pumpEV)
.EUt(960)
.duration(600)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleAluminium>, <ore:ringSiliconRubber> * 2, <ore:pipeMediumTitanium>, motorEV])
.fluidInputs([<liquid:stainless_steel> * 648])
.outputs(pumpEV)
.EUt(960)
.duration(300)
.buildAndRegister();
#Pump - IV
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTungsten>, <ore:ringRubber> * 2, <ore:pipeMediumTungstenSteel>, motorIV])
.fluidInputs([<liquid:tungsten_steel> * 648])
.outputs(pumpIV)
.EUt(3840)
.duration(1200)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTungsten>, <ore:ringStyreneButadieneRubber> * 2, <ore:pipeMediumTungstenSteel>, motorIV])
.fluidInputs([<liquid:tungsten_steel> * 648])
.outputs(pumpIV)
.EUt(3840)
.duration(600)
.buildAndRegister();
assembler.recipeBuilder()
.inputs([<ore:cableGtSingleTungsten>, <ore:ringSiliconRubber> * 2, <ore:pipeMediumTungstenSteel>, motorIV])
.fluidInputs([<liquid:tungsten_steel> * 648])
.outputs(pumpIV)
.EUt(3840)
.duration(300)
.buildAndRegister();
#conveyor alternate recipes
solidifier.recipeBuilder()
.fluidInputs([<liquid:moltenvinteum> * 144])
.notConsumable(<metaitem:shape.mold.ball>)
.outputs(<contenttweaker:vinteum_ore_cluster>)
.duration(12)
.EUt(4)
.buildAndRegister();
#Glass fixes (to match TiCon Standards)
solidifier.findRecipe(4, [<metaitem:shape.mold.block>], [<liquid:glass> * 144]).remove();
solidifier.recipeBuilder()
.fluidInputs([<liquid:glass> * 1000])
.notConsumable(<metaitem:shape.mold.block>)
.outputs(<minecraft:glass>)
.duration(12)
.EUt(4)
.buildAndRegister();
solidifier.findRecipe(4, [<metaitem:shape.mold.plate>], [<liquid:glass> * 144]).remove();
//solidifier.findRecipe(8, [<metaitem:shape.mold.plate>], [<liquid:glass> * 144]).remove();
solidifier.recipeBuilder()
.fluidInputs([<liquid:glass> * 1000])
.notConsumable(<metaitem:shape.mold.plate>)
.outputs(<ore:plateGlass>.firstItem)
.duration(12)
.EUt(4)
.buildAndRegister();
solidifier.findRecipe(16, [<metaitem:shape.mold.ball>], [<liquid:glass> * 144]).remove();
solidifier.recipeBuilder()
.fluidInputs([<liquid:glass> * 1000])
.notConsumable(<metaitem:shape.mold.ball>)
.outputs(<metaitem:component.glass.tube>)
.duration(12)
.EUt(4)
.buildAndRegister();
#Glass Fluid Extractor Fixes (Thanks Taheeb)
{// Remove all liquid:glass outputs from fluid extractor
var glassTest = (<liquid:glass> * 0) as ILiquidStack;
for recipe in fluidExtractor.recipes {
if ((recipe.fluidOutputs[0] * 0).matches(glassTest)){ // hardcoded: fluid extractor recipes currently only have one output
print("Removing extractor recipe: " + recipe.inputs[0].matchingItems[0].displayName + " to " + recipe.fluidOutputs[0].displayName + ":" + recipe.fluidOutputs[0].amount);
recipe.remove();
} // end if
} // end for
}// End remove all liquid:glass outputs from fluid extractor
{ // Add liquid:glass producing recipes to fluid extractor
var fluidGlass = <liquid:glass>;
var baseTime as int = 20 * 4;
var voltage as int = 28;
var inputs as IIngredient[] = [<ore:sand>, <ore:blockGlass>, <ore:paneGlass>, <ore:dustQuartzite>, <ore:dustGlass>];
var outputs as ILiquidStack[] = [fluidGlass*1000, fluidGlass*1000, fluidGlass*((1000*6/16) as int), fluidGlass*1000, fluidGlass*1000];
var durations as int[] = [baseTime, baseTime, ((baseTime as float) * (6.0/16.0)) as int, baseTime, baseTime];
for x in 0 .. inputs.length {
fluidExtractor.recipeBuilder()
.inputs(inputs[x])
.fluidOutputs(outputs[x])
.duration(durations[x])
.EUt(voltage)
.buildAndRegister();
} // end for
} // End add liquid:glass producing recipes to fluid extractor
{ // Remove all liquid:glass input recipes from solidifier
var glassTest = (<liquid:glass> * 0);
for recipe in solidifier.recipes {
for input in recipe.fluidInputs {
if ((input * 0).matches(glassTest)) {
if (!isNull(recipe)) {
recipe.remove();
} // end recipe null check
} // end if glass match
} // end for input
} // end for recipe
} // End remove all liquid:glass input recipes from solidifier
var glass1k as ILiquidStack = <liquid:glass> * 1000;
// this would preferably be a nested array of [ILiquidStack, IItemStack, IItemStack], but
// I couldn't find support for non-homogenous arrays or tuples
// this arrangement can suffer from mismatched array lengths due to bad data entry
var fluidInputs as ILiquidStack[] = [glass1k, glass1k, glass1k];
var moldInputs as IIngredient[] = [<metaitem:shape.mold.block>, <metaitem:shape.mold.plate>, <metaitem:shape.mold.ball>];
var itemOutputs as IItemStack[] = [<minecraft:glass>, <ore:plateGlass>.firstItem, <metaitem:component.glass.tube>];
for x in 0 .. fluidInputs.length {
solidifier.recipeBuilder()
.fluidInputs(fluidInputs[x])
.notConsumable(moldInputs[x])
.outputs([itemOutputs[x]])
.duration(20)
.EUt(7)
.buildAndRegister();
}
#concrete dust fix
//compressor.findRecipe(800, [<ore:dustConcrete>.firstItem * 9], null).remove(); Goddamnit Ga.
recipes.remove(<gregtech:concrete>);
#Concrete_powder
solidifier.findRecipe(8, [<metaitem:shape.mold.block>], [<liquid:concrete> * 1296]).remove();
solidifier.recipeBuilder()
.fluidInputs([<liquid:concrete> * 576])
.notConsumable(<metaitem:shape.mold.block>)
.outputs(<gregtech:concrete> * 4)
.duration(300)
.EUt(14)
.buildAndRegister();
fluidExtractor.findRecipe(32, [<ore:blockConcrete>.firstItem], []).remove();
fluidExtractor.recipeBuilder()
.inputs(<ore:blockConcrete>.firstItem)
.fluidOutputs(<liquid:concrete> * 144)
.duration(80)
.EUt(20)
.buildAndRegister();
#Distllation Tower
recipes.remove(<meta_tile_entity:gregtech:distillation_tower>);
recipes.addShaped(<meta_tile_entity:gregtech:distillation_tower>, [
[<ore:circuitHigh>, <ore:pipeLargeStainlessSteel>, <ore:circuitHigh>],
[<metaitem:electric.pump.hv>, <meta_tile_entity:gregtech:hull.hv>, <metaitem:electric.pump.hv>],
[<ore:circuitHigh>, <ore:pipeLargeStainlessSteel>, <ore:circuitHigh>]]);
distillery.findRecipe(5120, [<gregtech:meta_item_1:32766>.withTag({Configuration: 1})], [<fluid:wood_gas>*1000]).remove();
distillery.recipeBuilder()
.fluidInputs([<liquid:wood_gas> * 1000])
.notConsumable(integratedCircuit.withTag({Configuration: 1}))
.fluidOutputs([<liquid:ethylene> * 200])
.duration(80)
.EUt(64)
.buildAndRegister();
#granite
macerator.findRecipe(8, [<minecraft:stone:1>], null).remove();
macerator.recipeBuilder()
.inputs(<minecraft:stone:1>)
.outputs(<ore:dustGraniteBlack>.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<minecraft:stone:2>)
.outputs(<ore:dustGraniteBlack>.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
macerator.recipeBuilder()
.inputs(<gregtech:granite:4>)
.outputs(<ore:dustGraniteBlack>.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
#Ender Dust
macerator.findRecipe(8, [<minecraft:ender_pearl>], null).remove();
macerator.recipeBuilder()
.inputs(<minecraft:ender_pearl>)
.outputs(<ore:dustEnderPearl>.firstItem)
.duration(40)
.EUt(8)
.buildAndRegister();
#remove base recipes and add back in oredicted glass
macerator.findRecipe(240, [<minecraft:glass>], null).remove();
macerator.recipeBuilder()
.inputs(<ore:blockGlass>)
.outputs(<ore:dustGlass>.firstItem)
.duration(30)
.EUt(8)
.buildAndRegister();
#Energy Output Hatch - MV
recipes.addShaped(<meta_tile_entity:gregtech:energy_hatch.output.mv>, [
[<ore:cableGtDoubleRedAlloy>,<thaumcraft:mechanism_complex>,<ore:cableGtDoubleRedAlloy>],
[<ore:plateGraphite>, <meta_tile_entity:gregtech:energy_hatch.output.lv>,<ore:plateGraphite>],
[<ore:plateNetherQuartz>, <metaitem:component.small.coil>,<ore:plateNetherQuartz>]]);
#Electronic Best Friend
recipes.remove(<meta_tile_entity:gregtech:electric_blast_furnace>);
recipes.addShaped(<meta_tile_entity:gregtech:electric_blast_furnace>,[
[<ore:plateGraphite>, <gregtech:machine:50>, <ore:plateGraphite>],
[<ore:plateGraphite>, <gregtech:metal_casing:2>, <ore:plateGraphite>],
[<ore:cableGtSingleTin>, <ore:circuitLow>, <ore:cableGtSingleTin>]]);
#Flint Axe (adding to JEI manually)
val starterAxe = <gregtech:meta_tool:3>.withTag({
"GT.ToolStats": {
PrimaryMaterial: "flint",
MaxDurability: 55,
DigSpeed: 6.0 as float,
AttackDamage: 1.0 as float,
HarvestLevel: 1}
});
mods.jei.JEI.addItem(starterAxe);
#Glass Dust
recipes.addShapeless(<ore:dustGlass>.firstItem, [<ore:blockGlass>, craftingToolMortar]);
#iron hammer in artisan
val ironHammer = <gregtech:meta_tool:6>.withTag({
CraftingComponents: [
{id: "gregtech:meta_item_2",
Count: 1 as byte,
Damage: 5033 as short},
{id: "minecraft:stick", Count: 1 as byte, Damage: 0 as short}],
"GT.ToolStats": {PrimaryMaterial: "iron", HandleMaterial: "wood"}});
mods.jei.JEI.addItem(ironHammer);
ironHammer.addTooltip(format.darkRed("最初的铁锻造锤,可以在基础工作台中合成。"));
RecipeBuilder.get("basic")
.setShaped([
[<ore:ingotIron>, <ore:ingotIron>, null],
[<ore:ingotIron>, <ore:ingotIron>, <ore:stickWood>],
[<ore:ingotIron>, <ore:ingotIron>, null]])
.addTool(<ore:artisanHammers>, 10)
.addOutput(ironHammer)
.create();
val ironFile = <gregtech:meta_tool:9>.withTag({
CraftingComponents: [
{id: "gregtech:meta_item_1", Count: 1 as byte, Damage: 12033 as short},
{id: "minecraft:stick", Count: 1 as byte, Damage: 0 as short}],
"GT.ToolStats": {PrimaryMaterial: "iron", HandleMaterial: "wood"}});
mods.jei.JEI.addItem(ironFile);
ironFile.addTooltip(format.darkRed("最初的铁锉,可以在基础工作台中合成。"));
#iron file in artisan
RecipeBuilder.get("basic")
.setShaped([
[null, <ore:ingotIron>, null],
[null, <ore:ingotIron>, null],
[null, <ore:stickWood>, null]])
.addTool(<ore:artisanHammers>, 10)
.addOutput(ironFile)
.create();
#Remove rubber smelting recipe
furnace.remove(<metaitem:rubber_drop>);
#galium dust
mods.botania.ManaInfusion.addAlchemy(<ore:dustTinyGallium>.firstItem, <ore:dustBauxite>.firstItem, 5000);
#Mozanite with Lutetium
#revert quantum and improved stars/eyes to randon
chemical_bath.findRecipe(384, [<minecraft:nether_star>], [<liquid:plutonium> * 1152]).remove();
chemical_bath.findRecipe(384, [<minecraft:ender_eye>], [<liquid:plutonium> * 288]).remove();
chemical_bath.recipeBuilder()
.inputs(<minecraft:nether_star>)
.fluidInputs([<liquid:radon> * 1152])
.outputs(<metaitem:quantumstar>)
.duration(1920)
.EUt(384)
.buildAndRegister();
chemical_bath.recipeBuilder()
.inputs(<minecraft:ender_eye>)
.fluidInputs([<liquid:radon> * 288])
.outputs(<metaitem:quantumeye>)
.duration(480)
.EUt(384)
.buildAndRegister();
spinnyGoFast.recipeBuilder()
.inputs(<ore:crushedPurifiedMonazite>)
.outputs(<ore:crushedCentrifugedMonazite>.firstItem)
.chancedOutput(<ore:dustSmallLutetium>.firstItem, 2500, 500)
.chancedOutput(<ore:dustTinyNeodymium>.firstItem*3, 10000, 1500)
.duration(1160)
.EUt(60)
.buildAndRegister();
#alternate glue recipe
spinnyGoFast.recipeBuilder()
.fluidInputs([<liquid:sap> * 100])
.fluidOutputs([<liquid:glue> * 100])
.chancedOutput(<thermalfoundation:material:832>, 500, 150)
.duration(300)
.EUt(8)
.buildAndRegister();
#radon from egg
chemReactor.recipeBuilder()
.inputs(<ore:enrichedEggRadon>*32)
.fluidOutputs([<liquid:radon> * 50])
.duration(800)
.EUt(480)
.buildAndRegister();
#Alternate Vynl chloride
chemReactor.recipeBuilder()
.fluidInputs([<liquid:plastic> * 1000, <liquid:chlorine> * 1000])
.fluidOutputs([<liquid:polyvinyl_chloride> * 1000])
.duration(320)
.EUt(30)
.buildAndRegister();
#new Glycol production
chemReactor.recipeBuilder()
.inputs(<ore:dustTinySodiumHydroxide>)
.fluidInputs([<liquid:water> * 500, <liquid:fish_oil> * 500])
.fluidOutputs([<liquid:glycerol> * 1000])
.duration(600)
.EUt(30)
.buildAndRegister();
chemReactor.recipeBuilder()
.inputs(<ore:dustTinySodiumHydroxide>)
.fluidInputs([<liquid:water> * 500, <liquid:seed_oil> * 500])
.fluidOutputs([<liquid:glycerol> * 1000])
.duration(600)
.EUt(30)
.buildAndRegister();
#Infused NitroDiesel
chemReactor.recipeBuilder()
.inputs(<ore:dustTinyLithium>)
.fluidInputs([<liquid:nitro_fuel> * 10000, <liquid:astralsorcery.liquidstarlight> * 2000])
.fluidOutputs([<liquid:infused_nitrofuel> * 10000])
.duration(80)
.EUt(120)
.buildAndRegister();
#Naquadriatic Fuel - BIGBOI JUICE
chemReactor.recipeBuilder()
.inputs(<thaumcraft:alumentum>)
.fluidInputs([<liquid:infused_nitrofuel> * 3000, <liquid:naquadah_enriched> * 1000])
.fluidOutputs([<liquid:naquadriaticfuel> * 3000])
.duration(400)
.EUt(2176)
.buildAndRegister();
#Potassium Nitrate
chemical_bath.recipeBuilder()
.inputs(<ore:dustPotassium>)
.fluidInputs([<liquid:nitric_acid> * 144])
.outputs(<ore:dustNiter>.firstItem)
.duration(160)
.EUt(18)
.buildAndRegister();
#Lithium Chloride
chemReactor.recipeBuilder()
.fluidInputs([<liquid:liquidlithium> * 100, <liquid:chlorine> * 100])
.fluidOutputs([<liquid:lithiumchloride> * 200])
.duration(20)
.EUt(16)
.buildAndRegister();
#Lithium
chemReactor.recipeBuilder()
.inputs(<ore:dustPotassium>)
.fluidInputs([<liquid:lithiumchloride> * 1000])
.fluidOutputs([<liquid:potassiumchloride> * 500])
.outputs(<ore:dustLithium>.firstItem)
.duration(250)
.EUt(16)
.buildAndRegister();
#Less efficient Lithium
spinnyGoFast.recipeBuilder()
.fluidInputs([<liquid:liquidlithium> * 100])
.outputs(<ore:dustTinyLithium>.firstItem)
.duration(60)
.EUt(16)
.buildAndRegister();
#vitrified sand
spinnyGoFast.recipeBuilder()
.inputs(<ore:sandVitrified>)
.chancedOutput(<bloodmagic:item_demon_crystal>, 10000, 2000)
.chancedOutput(<bloodmagic:item_demon_crystal:1>, 10000, 2000)
.chancedOutput(<bloodmagic:item_demon_crystal:2>, 10000, 2000)
.chancedOutput(<bloodmagic:item_demon_crystal:3>, 10000, 2000)
.chancedOutput(<bloodmagic:item_demon_crystal:4>, 10000, 2000)
.fluidOutputs([<liquid:rawlatticite> * 100])
.duration(60)
.EUt(480)
.buildAndRegister();
#recover potassium
electrolyzer.recipeBuilder()
.fluidInputs([<liquid:potassiumchloride> * 1000])
.fluidOutputs([<liquid:chlorine> * 1000])
.outputs(<ore:dustPotassium>.firstItem)
.duration(850)
.EUt(16)
.buildAndRegister();
#rubber from resin
chemReactor.recipeBuilder()
.inputs(<ore:dustSulfur>)
.fluidInputs([<liquid:resin> * 100])
.fluidOutputs([<liquid:rubber> * 1296])
.duration(600)
.EUt(16)
.buildAndRegister();
extractor.findRecipe(307200, [<minecraft:egg>], []).remove();
#menril crystals
extractor.recipeBuilder()
.inputs(<integrateddynamics:menril_log>)
.outputs(<ore:crystalMenril>.firstItem*4)
.duration(20)
.EUt(8)
.buildAndRegister();
#menril crystals from egg
compressor.recipeBuilder()
.inputs(<contenttweaker:menril_enriched_egg>)
.outputs(<ore:crystalMenril>.firstItem)
.duration(5)
.EUt(8)
.buildAndRegister();
//Ferrite
mixer.findRecipe(8, [<ore:dustIron>.firstItem *4, <ore:dustNickel>.firstItem, <ore:dustZinc>.firstItem], []).remove();
mixer.recipeBuilder()
.inputs(<ore:dustZinc>.firstItem, <ore:dustInvar>.firstItem)
.outputs(<ore:dustFerriteMixture>.firstItem * 6)
.duration(30)
.EUt(8)
.buildAndRegister();
#ender shards
mixer.recipeBuilder()
.inputs(<extrautils2:endershard>, <projecte:item.pe_covalence_dust>*4)
.fluidInputs([<liquid:mana_fluid> * 500])
.outputs(<lteleporters:endercrystal>)
.duration(80)
.EUt(16)
.buildAndRegister();
#Salis mundis
mixer.recipeBuilder()
.inputs(<ore:visCrystals>, <projecte:item.pe_covalence_dust>*8)
.fluidInputs([<liquid:mana_fluid> * 250])
.outputs(<thaumcraft:salis_mundus>)
.duration(100)
.EUt(16)
.buildAndRegister();
#Illumination Powder
mixer.recipeBuilder()
.inputs(<ore:dustGlass>*4,<thaumcraft:salis_mundus>,<projecte:item.pe_covalence_dust:1>*4)
.fluidInputs([<liquid:astralsorcery.liquidstarlight> * 500])
.outputs(<astralsorcery:itemusabledust>*8)
.duration(100)
.EUt(68)
.buildAndRegister();
#Nocturnal Powder
mixer.recipeBuilder()
.inputs(<ore:dyeBlack>,<ore:gemLapis>, <ore:coal>*2,<astralsorcery:itemusabledust>)
.fluidInputs([<liquid:liquidnightmares> * 500])
.outputs(<astralsorcery:itemusabledust:1>*4)
.duration(100)
.EUt(272)
.buildAndRegister();
#Star Metal Ore
mixer.recipeBuilder()
.inputs(<astralsorcery:blockcustomore>, <thermalfoundation:material:1028>, <actuallyadditions:item_crystal_empowered:3>, <enderio:item_material:75>)
.fluidInputs([<liquid:osmium> * 1296])
.outputs(<astralsorcery:blockcustomore:1>*4)
.duration(100)
.EUt(272)
.buildAndRegister();
#Vinteum fusion
fusionReactor.recipeBuilder()
.fluidInputs([<liquid:starmetal> * 8, <liquid:blue_vitriol_water_solution>*8])
.fluidOutputs(<liquid:moltenvinteum> * 144)
.duration(32)
.EUt(30720)
.property("eu_to_start", 140000)
.buildAndRegister();
#Void Seed
mixer.recipeBuilder()
.inputs(<enderutilities:enderpart:10>, <ore:dustQuartzBlack>*9, <quark:black_ash>, <ore:cropNetherWart>*4)
.fluidInputs([<liquid:liquidnightmares> * 500])
.outputs(<thaumcraft:void_seed>*4)
.duration(120)
.EUt(320)
.buildAndRegister();
#stemcells
mixer.recipeBuilder()
.inputs(<harvestcraft:soymilkitem>,<minecraft:egg>,<minecraft:sugar>*2, <enderio:item_material:75>)
.fluidInputs([<liquid:lifeessence> * 1000])
.outputs(<metaitem:stemcells>)
.duration(800)
.EUt(320)
.buildAndRegister();
#iron hammer head
recipes.remove(<ore:toolHeadHammerIron>.firstItem);
recipes.addShaped(<ore:toolHeadHammerIron>.firstItem,[
[<ore:ingotiron>,<ore:ingotiron>,null],
[<ore:ingotiron>,<ore:ingotiron>,craftingToolHardHammer],
[<ore:ingotiron>,<ore:ingotiron>,null]]);
#Multi-Smelter
recipes.remove(<meta_tile_entity:gregtech:multi_furnace>);
recipes.addShaped(<meta_tile_entity:gregtech:multi_furnace>, [
[<meta_tile_entity:gregtech:electric_furnace.lv>, <gregtech:metal_casing:2>, <meta_tile_entity:gregtech:electric_furnace.lv>],
[<ore:circuitHigh>, <gregtech:metal_casing:2>, <ore:circuitHigh>],
[<ore:cableGtSingleAnnealedCopper>, <ore:circuitHigh>, <ore:cableGtSingleAnnealedCopper>]]);
#remove primitive blast furnace recipes
for recipe in RecipeMaps.getPrimitiveBlastFurnaceRecipes() {
recipe.remove();
}
//remove Primitive blast furnace block
mods.jei.JEI.removeAndHide(<gregtech:machine:510>);
#Primitive blast bricks
recipes.remove(<gregtech:metal_casing:1>);
RecipeBuilder.get("basic")
.setShaped([
[<metaitem:brick.fireclay>, <metaitem:brick.fireclay>, null],
[<metaitem:brick.fireclay>, <metaitem:brick.fireclay>, null],
[null, null, null]])
.setFluid(<liquid:creosote>*50)
.addTool(<ore:artisanHammers>, 10)
.addOutput( <gregtech:metal_casing:1>)
.create();
#Rocket Fuel Removal (no ammonia chain)
chemReactor.findRecipe(388,
[integratedCircuit.withTag({Configuration: 1})],
[<liquid:oxygen> * 500, <liquid:hydrogen> * 3000, <liquid:nitrogen_dioxide> * 1000]).remove();
mixer.findRecipe(960,
[],
[<liquid:oxygen> * 1000, <liquid:dimethylhidrazine> * 1000]).remove();
mixer.findRecipe(16,
[],
[<liquid:oxygen> * 1000, <liquid:dimethylhidrazine> * 1000]).remove();
mixer.findRecipe(960,
[],
[<liquid:dinitrogen_tetroxide> * 1000, <liquid:dimethylhidrazine> * 1000]).remove();
mixer.findRecipe(960,
[],
[<liquid:dinitrogen_tetroxide> * 1000, <liquid:dimethylhidrazine> * 1000]).remove();
chemReactor.findRecipe(388000,
[<gregtech:meta_item_1:32766>.withTag({Configuration: 1})],
[<liquid:oxygen> * 500, <liquid:hydrogen> * 3000, <liquid:nitrogen_dioxide> * 1000]).remove();
chemReactor.recipeBuilder()
.fluidInputs([<liquid:cryogenicoxygen> * 1000, <liquid:cryogenichydrogen> * 1000])
.fluidOutputs([<liquid:rocket_fuel> * 1000])
.duration(660)
.EUt(120)
.buildAndRegister();
#Removing Methane from Apples
//spinnyGoFast.findRecipe(5, [<minecraft:apple>], []).remove();
#remove redundant GT coke brick
recipes.removeByRecipeName("gtadditions:coke_brick");
mods.jei.JEI.hide(<metaitem:compressed.coke.clay>);
mods.jei.JEI.hide(<gtadditions:ga_multiblock_casing>);
#New chloroform recipe
chemReactor.recipeBuilder()
.inputs(<ore:dustCarbon>)
.fluidInputs([<liquid:hydrochloric_acid> * 1000])
.fluidOutputs([<liquid:chloroform> * 1000])
.duration(120)
.EUt(30)
.buildAndRegister();
#Salt
spinnyGoFast.recipeBuilder()
.fluidInputs([<liquid:brine> * 1000])
.fluidOutputs([<liquid:salt_water> * 1000, <liquid:liquidlithium> * 100])
.duration(200)
.EUt(18)
.buildAndRegister();
mods.gregtech.recipe.RecipeMap.getByName("fluid_solidifier").recipeBuilder()
.fluidInputs([<liquid:brine> * 144])
.notConsumable(<metaitem:shape.mold.ball>)
.outputs(<ore:dustSalt>.firstItem)
.duration(10)
.EUt(16)
.buildAndRegister();
#neutronium
fusionReactor.findRecipe(19660800,
[],
[<liquid:americium> * 16, <liquid:naquadria> * 16]).remove();
fusionReactor.recipeBuilder()
.fluidInputs([<liquid:americium> * 16, <liquid:naquadria>*16])
.fluidOutputs(<liquid:neutronium> * 2)
.duration(200)
.EUt(61440)
.property("eu_to_start", 1000000)
.buildAndRegister();
#Max Rotor holder recipe
recipes.remove(<gregtech:machine:819>);
recipes.addShaped(<gregtech:machine:819>,
[[<ore:wireGtHexSuperconductor>, <draconicevolution:draconic_core>, <ore:wireGtHexSuperconductor>],
[<ore:wireGtHexSuperconductor>, <ore:gearHsss>, <ore:wireGtHexSuperconductor>],
[<ore:wireGtHexSuperconductor>, <ore:wireGtHexSuperconductor>, <ore:wireGtHexSuperconductor>]]);
#Steam Alloy Smelter
recipes.remove(<gregtech:machine:17>);
recipes.addShaped(<gregtech:machine:17>, [
[<ore:pipeSmallBronze>, <ore:pipeSmallBronze>, <ore:pipeSmallBronze>],
[<minecraft:brick_block>, <gregtech:machine_casing:11>, <minecraft:brick_block>],
[<ore:pipeSmallBronze>, <ore:pipeSmallBronze>, <ore:pipeSmallBronze>]]);
#Steam Alloy Smelter - High Pressure
recipes.remove(<gregtech:machine:18>);
recipes.addShaped(<gregtech:machine:18>, [
[<ore:pipeSmallSteel>, <ore:pipeSmallSteel>, <ore:pipeSmallSteel>],
[<minecraft:brick_block>, <gregtech:machine_casing:13>, <minecraft:brick_block>],
[<ore:pipeSmallSteel>, <ore:pipeSmallSteel>, <ore:pipeSmallSteel>]]);
#Steam Coal Boiler
recipes.remove(<gregtech:machine:1>);
recipes.addShaped(<gregtech:machine:1>, [
[<ore:plateBronze>, <ore:plateBronze>, <ore:plateBronze>],
[<ore:plateBronze>, craftingToolHardHammer, <ore:plateBronze>],
[<minecraft:brick_block>, <minecraft:brick_block>, <minecraft:brick_block> ]]);
#Steam Coal Boiler - High Pressure
recipes.remove(<gregtech:machine:2>);
recipes.addShaped(<gregtech:machine:2>, [
[<ore:plateSteel>, <ore:plateSteel>, <ore:plateSteel>],
[<ore:plateSteel>, craftingToolHardHammer, <ore:plateSteel>],
[<minecraft:brick_block>, <minecraft:brick_block>, <minecraft:brick_block>]]);
#Steam Furnace
recipes.remove(<gregtech:machine:15>);
recipes.addShaped(<gregtech:machine:15>,[
[<ore:pipeSmallBronze>, <ore:pipeSmallBronze>, <ore:pipeSmallBronze>],
[<ore:pipeSmallBronze>, <gregtech:machine_casing:11>, <ore:pipeSmallBronze>],
[<ore:pipeSmallBronze>, <minecraft:brick_block>, <ore:pipeSmallBronze>]]);
#Steam Furnace - High Pressure
recipes.remove(<gregtech:machine:16>);
recipes.addShaped(<gregtech:machine:16>,[
[<ore:pipeSmallSteel>, <ore:pipeSmallSteel>, <ore:pipeSmallSteel>],
[<ore:pipeSmallSteel>, <gregtech:machine_casing:13>, <ore:pipeSmallSteel>],
[<ore:pipeSmallSteel>, <minecraft:brick_block>, <ore:pipeSmallSteel>]]);
#steel boiler fix
recipes.remove(<gregtech:machine_casing:13>);
recipes.addShaped(<gregtech:machine_casing:13>,
[[<ore:plateSteel>, <ore:plateSteel>, <ore:plateSteel>],
[<ore:plateBrass>, craftingToolHardHammer, <ore:plateBrass>],
[<minecraft:brick_block>, <minecraft:brick_block>, <minecraft:brick_block>]]);
#new coke oven hatch recipe
recipes.remove(<meta_tile_entity:gregtech:coke_oven_hatch>);
recipes.addShaped(<meta_tile_entity:gregtech:coke_oven_hatch>, [
[null, null, null],
[<minecraft:bucket>, <gregtech:metal_casing:8>, <minecraft:bucket>],
[null, null, null]]);
#coke brick mining levels
var cokeOven = <gregtech:machine:526> as IBlock;
cokeOven.definition.setHarvestLevel("pickaxe", 1);
var cokeOvenCasing = <gregtech:metal_casing:8> as IBlock;
cokeOvenCasing.definition.setHarvestLevel("pickaxe", 1);
var cokeOvenInterface = <gregtech:machine:527> as IBlock;
cokeOvenInterface.definition.setHarvestLevel("pickaxe", 1);
#Steel Ingot
<ore:ingotSteel>.firstItem.addTooltip(format.darkRed("可以通过在炼狱熔炉或炼狱窑炉里熔炼粗钢锭获得。"));
// findRecipe(long voltage, IItemHandlerModifiable inputs, IMultipleTankHandler/List<FluidStack> fluidInputs)
RecipeMap.getByName("blast_furnace").findRecipe(120, [<ore:ingotIron>.firstItem], [<liquid:oxygen> * 1000]).remove();
RecipeMap.getByName("blast_furnace").recipeBuilder()
.inputs([<ore:ingotIron>.firstItem, <ore:dustTinyCarbon>.firstItem | <ore:dustTinyCoal>.firstItem])
.fluidInputs(<liquid:oxygen> * 1000)
.outputs([<ore:ingotSteel>.firstItem, <ore:dustSmallDarkAsh>.firstItem])
.duration(500)
.EUt(120)
.buildAndRegister();
RecipeMap.getByName("blast_furnace").findRecipe(120, [<ore:ingotPigIron>.firstItem], [<liquid:oxygen> * 1000]).remove();
RecipeMap.getByName("blast_furnace").recipeBuilder()
.inputs([<ore:ingotPigIron>.firstItem, <ore:dustTinyCarbon>.firstItem | <ore:dustTinyCoal>.firstItem])
.fluidInputs(<liquid:oxygen> * 1000)
.outputs([<ore:ingotSteel>.firstItem, <ore:dustSmallDarkAsh>.firstItem])
.duration(100)
.EUt(120)
.buildAndRegister();
RecipeMap.getByName("blast_furnace").findRecipe(120, [<ore:ingotWroughtIron>.firstItem], [<liquid:oxygen> * 1000]).remove();
RecipeMap.getByName("blast_furnace").recipeBuilder()
.inputs([<ore:ingotWroughtIron>.firstItem, <ore:dustTinyCarbon>.firstItem | <ore:dustTinyCoal>.firstItem])
.fluidInputs(<liquid:oxygen> * 1000)
.outputs([<ore:ingotSteel>.firstItem, <ore:dustSmallDarkAsh>.firstItem])
.duration(100)
.EUt(120)
.buildAndRegister();
#gravistar
autoclave.findRecipe(3686400, [<minecraft:nether_star>], [<liquid:neutronium> * 288]).remove();
RecipeMap.getByName("blast_furnace").recipeBuilder()
.inputs([<ore:ingotCosmicNeutronium>, <ore:dustNetherStar>])
.fluidInputs(<liquid:helium> * 2000)
.outputs([<metaitem:gravistar>])
.duration(500)
.property("temperature", 7200)
.EUt(480)
.buildAndRegister();
#Tanks
mods.jei.JEI.removeAndHide(<gregtech:machine:811>);
mods.jei.JEI.removeAndHide(<gregtech:machine:812>);
mods.jei.JEI.removeAndHide(<gregtech:machine:813>);
mods.jei.JEI.removeAndHide(<gregtech:machine:814>);
mods.jei.JEI.removeAndHide(<gregtech:machine:815>);
mods.jei.JEI.removeAndHide(<gregtech:machine:816>);
#Vacuum Freezer
recipes.remove(<gregtech:machine:512>);
recipes.addShaped(<gregtech:machine:512>, [
[<metaitem:electric.pump.hv>,<metaitem:electric.pump.hv>,<metaitem:electric.pump.hv>],
[<ore:alloyUltimate>,<gregtech:metal_casing:3>,<ore:alloyUltimate>],
[<ore:cableGtSingleGold>,<ore:alloyUltimate>,<ore:cableGtSingleGold>]]);
#wood gear
recipes.remove(<ore:gearWood>.firstItem);
recipes.addShaped(<ore:gearWood>.firstItem, [
[null,<ore:stickWood>,null],
[<ore:stickWood>,null,<ore:stickWood>],
[null,<ore:stickWood>,null]]);
/////////////////////////////////////////////////////
#Furnace Removals
var gtFurnaceRemovals as string[][IIngredient] = {
<ore:coal> : ["Coal"],
<ore:dustChromite> : ["Chromite"],
<ore:dustGlauconite> : ["Glauconite"],
<ore:dustGalena> : ["Galena"],
<ore:dustGrossular> : ["Grossular"],
<ore:dustIlmenite> : ["Ilmenite"],
<ore:dustLepidolite> : ["Lepidolite"],
<ore:dustPhosphor> : ["Phosphor"],
<ore:dustRedstone> : ["Redstone"],
<ore:dustScheelite> : ["Scheelite"],
<ore:dustSpessartine> : ["Spessartine"],
<ore:dustSoapstone> : ["Soapstone"],
<ore:dustSpodumene> : ["Spodumene"],
<ore:dustSulfur> : ["Sulfur"],
<ore:dustTalc> : ["Talc"],
<ore:dustTantalite> : ["Tantalite"],
<ore:dustTennantite> : ["Tennantite"],
<ore:dustTungstate> : ["Tungstate"],
<ore:dustUraninite> : ["Uraninite"],
<ore:dustVanadiumMagnetite> : ["VanadiumMagnetite"],
<ore:ingotAntimony> : ["Stibnite"],
<ore:ingotBeryllium> : ["Beryllium"],
<ore:ingotBismuth> : ["Bismuth"],
<ore:ingotCobalt> : ["Cobalt"],
<ore:ingotCopper> : [
"Copper",
"Tetrahedrite",
"Malachite",
"Chalcopyrite",
"Chalcocite",
"Tenorite",
"Bornite",
"Cuprite"
],
<ore:ingotGold>: ["Gold"],
<ore:ingotGraphite> : ["Graphite"],
<ore:ingotIron> : [
"Iron",
"YellowLimonite",
"Pyrite",
"BandedIron",
"Magnetite",
"BrownLimonite"
],
<ore:ingotLithium> : ["Lithium"],
<ore:ingotMolybdenum> : ["Molybdenum"],
<ore:ingotNickel> : [
"Garnierite",
"Nickel",
"Pentlandite"
],
<ore:ingotPlatinum> : [
"Platinum",
"Cooperite"
],
<ore:ingotLead> : ["Lead"],
<ore:ingotMagnesium> : ["Magnesite"],
<ore:ingotManganese>: ["Pyrolusite"],
<ore:ingotSilver> : ["Silver"],
<ore:ingotTin> : [
"Tin",
"Cassiterite",
"CassiteriteSand",
],
<ore:ingotThorium> : ["Thorium"],
<ore:ingotUranium235> : ["Uranium235"],
<ore:ingotUranium> : ["Uranium"],
<ore:ingotZinc> : ["Sphalerite", "Zinc"],
<ore:gemAerInfused> : ["AerInfused"],
<ore:gemAlmandine> : ["Almandine"],
<ore:gemAmethyst> : ["Amethyst"],
<ore:gemApatite> : ["Apatite"],
<ore:gemAquaInfused> : ["AquaInfused"],
<ore:gemCertusQuartz>: ["CertusQuartz"],
<ore:gemCinnabar> : ["Cinnabar"],
<ore:gemDiamond> : ["Diamond"],
<ore:gemEmerald> : ["Emerald"],
<ore:gemEntropyInfused> : ["EntropyInfused"],
<ore:gemGarnetRed> : ["GarnetRed"],
<ore:gemIgnisInfused> : ["IgnisInfused"],
<ore:gemLapis> : ["Lapis"],
<ore:gemLignite> : ["Lignite"],
<ore:gemOpal> : ["Opal"],
<ore:gemMonazite> : ["Monazite"],
<ore:gemOlivine> : ["Olivine"],
<ore:gemOrdoInfused> : ["OrdoInfused"],
<ore:gemQuartzite> : ["Quarzite"],
<ore:gemRuby> : ["Ruby"],
<ore:gemRutile> : ["Rutile"],
<ore:gemSapphire> : ["Sapphire"],
<ore:gemSodalite> : ["Sodalite"],
<ore:gemTerraInfused> : ["TerraInfused"],
<ore:gemGreenSapphire> : ["GreenSapphire"],
<ore:gemGarnetRed> : ["GarnetRed"],
<ore:gemTopaz> : ["Topaz"],
<ore:gemJasper> : ["Jasper"]
};
for furnaceOutput, furnaceInputs in gtFurnaceRemovals {
for i in furnaceInputs {
furnace.remove(furnaceOutput, oreDict["ore" +i]);
furnace.remove(furnaceOutput, oreDict["oreBasalt" +i]);
furnace.remove(furnaceOutput, oreDict["oreBlackgranite" +i]);
furnace.remove(furnaceOutput, oreDict["oreEndstone" +i]);
furnace.remove(furnaceOutput, oreDict["oreGravel" +i]);
furnace.remove(furnaceOutput, oreDict["oreMarble" +i]);
furnace.remove(furnaceOutput, oreDict["oreNetherrack" +i]);
furnace.remove(furnaceOutput, oreDict["oreRedgranite" +i]);
furnace.remove(furnaceOutput, oreDict["oreSand" +i]);
}
}
#flawed gemShapecraft removal
var gemDisable as IItemStack[]= [
<ore:gemFlawedAlmandine>.firstItem,
<ore:gemFlawedBlueTopaz>.firstItem,
<ore:gemFlawedCertusQuartz>.firstItem,
<ore:gemFlawedRuby>.firstItem,
<ore:gemFlawedSapphire>.firstItem,
<ore:gemFlawedSodalite>.firstItem,
<ore:gemFlawedTanzanite>.firstItem,
<ore:gemFlawedTopaz>.firstItem,
<ore:gemFlawedNetherQuartz>.firstItem,
<ore:gemFlawedQuartzite>.firstItem,
<ore:gemFlawedJasper>.firstItem,
<ore:gemFlawedGlass>.firstItem,
<ore:gemFlawedLignite>.firstItem,
<ore:gemFlawedOlivine>.firstItem,
<ore:gemFlawedOpal>.firstItem,
<ore:gemFlawedAmethyst>.firstItem,
<ore:gemFlawedLapis>.firstItem,
<ore:gemFlawedApatite>.firstItem,
<ore:gemFlawedGarnetRed>.firstItem,
<ore:gemFlawedGarnetYellow>.firstItem,
<ore:gemFlawedVinteum>.firstItem,
<ore:gemFlawedMonazite>.firstItem,
<ore:gemFlawedSkystone>.firstItem,
<ore:gemFlawedCinnabar>.firstItem,
<ore:gemFlawedCoal>.firstItem,
<ore:gemFlawedEmerald>.firstItem,
<ore:gemFlawedDiamond>.firstItem,
<ore:gemFlawedGreenSapphire>.firstItem,
<ore:gemFlawedRutile>.firstItem,
<ore:gemFlawedLazurite>.firstItem
];
for i in gemDisable {
recipes.remove(i);
}
#gem rod removal
var gemRodDisable as IItemStack[]= [
<ore:stickAlmandine>.firstItem,
<ore:stickRutile>.firstItem,
<ore:stickBlueTopaz>.firstItem,
<ore:stickVinteum>.firstItem,
<ore:stickGarnetYellow>.firstItem,
<ore:stickGarnetRed>.firstItem,
<ore:stickAmethyst>.firstItem,
<ore:stickOpal>.firstItem,
<ore:stickOlivine>.firstItem,
<ore:stickJasper>.firstItem,
<ore:stickTopaz>.firstItem,
<ore:stickTanzanite>.firstItem,
<ore:stickSapphire>.firstItem,
<ore:stickRuby>.firstItem
];
for i in gemRodDisable {
mods.jei.JEI.removeAndHide(i);
}
#gem long rod removal
var gemLongRodDisable as IItemStack[]= [
<ore:stickLongAlmandine>.firstItem,
<ore:stickLongRutile>.firstItem,
<ore:stickLongBlueTopaz>.firstItem,
<ore:stickLongVinteum>.firstItem,
<ore:stickLongGarnetYellow>.firstItem,
<ore:stickLongGarnetRed>.firstItem,
<ore:stickLongAmethyst>.firstItem,
<ore:stickLongOpal>.firstItem,
<ore:stickLongOlivine>.firstItem,
<ore:stickLongJasper>.firstItem,
<ore:stickLongTopaz>.firstItem,
<ore:stickLongTanzanite>.firstItem,
<ore:stickLongSapphire>.firstItem,
<ore:stickLongRuby>.firstItem
];
for i in gemLongRodDisable {
mods.jei.JEI.removeAndHide(i);
}
#gem Bolt removal
var gemBoltDisable as IItemStack[]= [
<ore:boltAlmandine>.firstItem,
<ore:boltRutile>.firstItem,
<ore:boltBlueTopaz>.firstItem,
<ore:boltVinteum>.firstItem,
<ore:boltGarnetYellow>.firstItem,
<ore:boltGarnetRed>.firstItem,
<ore:boltAmethyst>.firstItem,
<ore:boltOpal>.firstItem,
<ore:boltOlivine>.firstItem,
<ore:boltJasper>.firstItem,
<ore:boltTopaz>.firstItem,
<ore:boltTanzanite>.firstItem,
<ore:boltSapphire>.firstItem,
<ore:boltRuby>.firstItem
];
for i in gemBoltDisable {
mods.jei.JEI.removeAndHide(i);
}
#Starter Cables being Added to Assembler
var carpetCableFixSingle as IOreDictEntry[IOreDictEntry] = {
<ore:wireGtSingleTin> : <ore:cableGtSingleTin>,
<ore:wireGtSingleRedAlloy> : <ore:cableGtSingleRedAlloy>,
<ore:wireGtSingleCobalt> : <ore:cableGtSingleCobalt>,
<ore:wireGtSingleSolderingAlloy> : <ore:cableGtSingleSolderingAlloy>,
<ore:wireGtSingleZinc> : <ore:cableGtSingleZinc>,
<ore:wireGtSingleLead> : <ore:cableGtSingleLead>
};
for input, output in carpetCableFixSingle {
assembler.recipeBuilder()
.inputs(input.firstItem)
.property("circuit", 24)
.fluidInputs(<liquid:rubber> * 144)
.outputs(output.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
}
var carpetCableFixDouble as IOreDictEntry[IOreDictEntry] = {
<ore:wireGtDoubleTin> : <ore:cableGtDoubleTin>,
<ore:wireGtDoubleRedAlloy> : <ore:cableGtDoubleRedAlloy>,
<ore:wireGtDoubleCobalt> : <ore:cableGtDoubleCobalt>,
<ore:wireGtDoubleSolderingAlloy> : <ore:cableGtDoubleSolderingAlloy>,
<ore:wireGtDoubleZinc> : <ore:cableGtDoubleZinc>,
<ore:wireGtDoubleLead> : <ore:cableGtDoubleLead>
};
for input, output in carpetCableFixDouble {
assembler.recipeBuilder()
.inputs(input.firstItem)
.fluidInputs(<liquid:rubber> * 288)
.property("circuit", 24)
.outputs(output.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
}
var carpetCableFixQuadruple as IOreDictEntry[IOreDictEntry] = {
<ore:wireGtQuadrupleTin> : <ore:cableGtQuadrupleTin>,
<ore:wireGtQuadrupleRedAlloy>: <ore:cableGtQuadrupleRedAlloy>,
<ore:wireGtQuadrupleCobalt> : <ore:cableGtQuadrupleCobalt>,
<ore:wireGtQuadrupleSolderingAlloy> : <ore:cableGtQuadrupleSolderingAlloy>,
<ore:wireGtQuadrupleZinc> : <ore:cableGtQuadrupleZinc>,
<ore:wireGtQuadrupleLead> : <ore:cableGtQuadrupleLead>
};
for input, output in carpetCableFixQuadruple {
assembler.recipeBuilder()
.inputs(input.firstItem)
.fluidInputs(<liquid:rubber> * 576)
.property("circuit", 24)
.outputs(output.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
}
var carpetCableFixOctal as IOreDictEntry[IOreDictEntry] = {
<ore:wireGtOctalTin> : <ore:cableGtOctalTin>,
<ore:wireGtOctalRedAlloy> : <ore:cableGtOctalRedAlloy>,
<ore:wireGtOctalCobalt> : <ore:cableGtOctalCobalt>,
<ore:wireGtOctalSolderingAlloy> : <ore:cableGtOctalSolderingAlloy>,
<ore:wireGtOctalZinc> : <ore:cableGtOctalZinc>,
<ore:wireGtOctalLead> : <ore:cableGtOctalLead>
};
for input, output in carpetCableFixOctal {
assembler.recipeBuilder()
.inputs(input.firstItem)
.fluidInputs(<liquid:rubber> * 1152)
.property("circuit", 24)
.outputs(output.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
}
var carpetCableFixHex as IOreDictEntry[IOreDictEntry] = {
<ore:wireGtHexTin> : <ore:cableGtHexTin>,
<ore:wireGtHexRedAlloy> : <ore:cableGtHexRedAlloy>,
<ore:wireGtHexCobalt> : <ore:cableGtHexCobalt>,
<ore:wireGtHexSolderingAlloy> : <ore:cableGtHexSolderingAlloy>,
<ore:wireGtHexZinc> : <ore:cableGtHexZinc>,
<ore:wireGtHexLead> : <ore:cableGtHexLead>
};
for input, output in carpetCableFixHex {
assembler.recipeBuilder()
.inputs(input.firstItem)
.fluidInputs(<liquid:rubber> * 2304)
.property("circuit", 24)
.outputs(output.firstItem)
.duration(150)
.EUt(8)
.buildAndRegister();
}
#uranium processing
chemReactor.recipeBuilder()
.inputs(<ore:dustUranium235>)
.fluidInputs([<liquid:hydrofluoric_acid> * 60])
.fluidOutputs([<liquid:uraniumhexafluoride> * 2000])
.duration(120)
.EUt(480)
.buildAndRegister();
#remove small dust to nugget casting
<ore:nuggetCobalt>.remove(<tconstruct:nuggets>);
furnace.remove(<ore:nuggetCobalt>.firstItem, <ore:dustTinyCobalt>.firstItem);
mods.tconstruct.Casting.removeTableRecipe(<ore:nuggetOsmium>.firstItem);
#Uranium from Thorium transmutation
mods.astralsorcery.LightTransmutation.addTransmutation(<ore:oreThorium>.firstItem, <gregtech:ore_uranium_0>, 50);
#super conductor cable covered
assembler.recipeBuilder()
.inputs(<ore:wireGtSingleSuperconductor>, <ore:wireFineOsmium>)
.fluidInputs([<liquid:polytetrafluoroethylene> * 144])
.notConsumable(<metaitem:circuit.integrated>.withTag({Configuration: 24}))
.outputs(<ore:cableGtSingleSuperconductor>.firstItem)
.duration(120)
.EUt(480)
.buildAndRegister();
#Better chest recipe
assembler.recipeBuilder()
.inputs(<ore:plankWood>*32)
.notConsumable(<metaitem:circuit.integrated>.withTag({Configuration: 1}))
.outputs(<minecraft:chest>*4)
.duration(50)
.EUt(18)
.buildAndRegister();
#Iron rod crafted
recipes.remove(<ore:stickIron>.firstItem);
recipes.addShaped(<ore:stickIron>.firstItem,
[[craftingToolFile, null, null],
[null, <ore:ingotIron>, null],
[null, null, null]]);
#smelt to flawed quartzite
furnace.addRecipe(<ore:gemFlawedQuartzite>.firstItem, <ore:oreQuartzite>);
#Gold rod crafted
recipes.remove(<ore:stickGold>.firstItem);
recipes.addShaped(<ore:stickGold>.firstItem,
[[craftingToolFile, null, null],
[null, <ore:ingotGold>, null],
[null, null, null]]);
#Cracker Recipes Re-Add
var hydrogenCrackerMap as ILiquidStack[ILiquidStack] = {
<liquid:butadiene> : <liquid:hydrocracked_butadiene>,
<liquid:butene> : <liquid:hydrocracked_butene>,
<liquid:gas> : <liquid:hydrocracked_gas>,
<liquid:heavy_fuel> : <liquid:hydrocracked_heavy_fuel>,
<liquid:naphtha> : <liquid:hydrocracked_naphtha>,
<liquid:butane> : <liquid:hydrocracked_butane>,
<liquid:light_fuel> : <liquid:hydrocracked_light_fuel>,
<liquid:propane> : <liquid:hydrocracked_propane>,
<liquid:propene> : <liquid:hydrocracked_propene>,
<liquid:ethylene> : <liquid:hydrocracked_ethylene>,
<liquid:ethane> : <liquid:hydrocracked_ethane>
};
for gas, gasCracked in hydrogenCrackerMap {
cracker.recipeBuilder()
.fluidInputs([<liquid:hydrogen> * 2000, gas * 1000])
.fluidOutputs(gasCracked * 1000)
.duration(40)
.EUt(120)
.buildAndRegister();
}
var steamCrackerMap as ILiquidStack[ILiquidStack] = {
<liquid:butadiene> : <liquid:steamcracked_butadiene>,
<liquid:butene> : <liquid:steamcracked_butene>,
<liquid:gas> : <liquid:steamcracked_gas>,
<liquid:heavy_fuel> : <liquid:cracked_heavy_fuel>,
<liquid:naphtha> : <liquid:steamcracked_naphtha>,
<liquid:butane> : <liquid:steamcracked_butane>,
<liquid:light_fuel> : <liquid:cracked_light_fuel>,
<liquid:propane> : <liquid:steamcracked_propane>,
<liquid:propene> : <liquid:steamcracked_propene>,
<liquid:ethylene> : <liquid:steamcracked_ethylene>,
<liquid:ethane> : <liquid:steamcracked_ethane>
};
for gas, gasCracked in steamCrackerMap {
cracker.recipeBuilder()
.fluidInputs([<liquid:steam> * 2000, gas * 1000])
.fluidOutputs(gasCracked * 1000)
.duration(40)
.EUt(120)
.buildAndRegister();
}
#high tier circuits
#Neuro CPU
//assembly_line.findRecipe(80000, [<ore:foilSiliconRubber>.firstItem * 64, <metaitem:stemcells> * 8, <metaitem:component.glass.tube> * 8,
// <ore:plateGold>.firstItem * 8, <ore:plateStainlessSteel>.firstItem * 4, <metaitem:board.wetware>],
// [<liquid:sterilized_growth_medium> * 250, <liquid:uumatter> * 100, <liquid:water> * 250, <liquid:lava> * 1000])
// .remove();
assembly_line.recipeBuilder()
.inputs([<ore:foilSiliconRubber>.firstItem * 64, <waterstrainer:super_worm>, <metaitem:component.glass.tube> * 8,
<ore:plateGold>.firstItem * 8, <ore:plateStainlessSteel>.firstItem * 4, <metaitem:board.wetware>])
.fluidInputs([<liquid:sterilized_growth_medium> * 250, <liquid:positive_matter> * 50, <liquid:neutral_matter> * 50])
.outputs([<metaitem:processor.neuro>])
.duration(200)
.EUt(30720)
.buildAndRegister();
#Enderchicken Soul
val enderChickenSoul = <draconicevolution:mob_soul>.withTag({EntityName: "mightyenderchicken:ent_enderchicken"});
mods.jei.JEI.addItem(enderChickenSoul);
assembly_line.recipeBuilder()
.inputs([<roost:chicken>.withTag({Growth: 10, Chicken: "contenttweaker:nightmarechicken", Gain: 10, Strength: 10}), <metaitem:stemcells>*8, <deepmoblearning:glitch_heart>*4, <draconicevolution:dragon_heart>, <gregtech:meta_item_1:32725>*4, ])
.fluidInputs([<liquid:sterilized_growth_medium> * 250, <liquid:draconium> * 288, <liquid:uumatter> * 1000 ])
.outputs([enderChickenSoul])
.duration(600)
.EUt(30720)
.buildAndRegister();
#Wetware Mainframe
assembly_line.findRecipe(600000000, [<ore:foilSiliconRubber>.firstItem * 64,
<metaitem:component.smd.capacitor> * 32,
<metaitem:component.smd.resistor> * 32,
<metaitem:component.smd.transistor> * 32,
<metaitem:component.smd.diode> * 32,
<metaitem:plate.random_access_memory> * 16,
<ore:wireGtDoubleSuperconductor>.firstItem * 16,
<metaitem:circuit.wetware_super_computer> * 8,
<ore:frameGtTritanium>.firstItem * 4,
<metaitem:component.small_coil>*4],
[<liquid:soldering_alloy> * 2880, <liquid:water> * 10000])
.remove();
assembly_line.recipeBuilder()
.inputs(
<ore:foilSiliconRubber>.firstItem * 64,
<metaitem:component.smd.capacitor> * 32,
<metaitem:component.smd.resistor> * 32,
<metaitem:component.smd.transistor> * 36,
<metaitem:component.smd.diode> * 32,
<metaitem:plate.random_access_memory> * 16,
<ore:wireGtDoubleSuperconductor>.firstItem * 16,
<metaitem:circuit.wetware_super_computer> * 8,
<ore:frameGtTritanium>.firstItem * 4
)
.fluidInputs([<liquid:soldering_alloy> * 2880, <liquid:water> * 10000])
.outputs([<metaitem:circuit.wetware_mainframe>])
.duration(2000)
.EUt(300000)
.buildAndRegister();
# Wetware supercomputer - <gregtech:meta_item_2:32500> - <metaitem:circuit.wetware_super_computer>
assembler.findRecipe(13760000, [<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.smd.diode>*4,
<metaitem:plate.nor_memory_chip> *4, <metaitem:plate.random_access_memory>*4, <ore:circuitUltimate>.firstItem*3, <metaitem:board.wetware>*2], [<liquid:tin> * 288]).remove();
assembler.findRecipe(13760000, [<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.smd.diode>*4,
<metaitem:plate.nor_memory_chip> *4, <metaitem:plate.random_access_memory>*4, <ore:circuitUltimate>.firstItem*3, <metaitem:board.wetware>*2], [<liquid:soldering_alloy> * 144]).remove();
assembly_line.recipeBuilder()
.inputs(<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.smd.diode>*4,
<metaitem:plate.nor_memory_chip> *4, <metaitem:plate.random_access_memory>*4, <ore:circuitUltimate>.firstItem*3, <metaitem:processor.neuro>*2)
.outputs(<metaitem:circuit.wetware_super_computer>)
.fluidInputs([<liquid:tin> * 288])
.duration(400)
.EUt(34400)
.buildAndRegister();
assembly_line.recipeBuilder()
.inputs(<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.smd.diode>*4,
<metaitem:plate.nor_memory_chip> *4, <metaitem:plate.random_access_memory>*4, <ore:circuitUltimate>.firstItem*3, <metaitem:processor.neuro>*2)
.outputs(<metaitem:circuit.wetware_super_computer>)
.fluidInputs([<liquid:soldering_alloy> * 144])
.duration(400)
.EUt(34400)
.buildAndRegister();
#Wetware assembly - <gregtech:meta_item_2:32499> - <metaitem:circuit.wetware_assembly> - <ore:circuitUltimate>
assembler.findRecipe(13760000, [<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.small_coil>*4, <metaitem:component.smd.capacitor>*4,
<metaitem:plate.random_access_memory>*4, <metaitem:circuit.wetware_processor>*2, <metaitem:board.wetware>], [<liquid:tin> * 288]).remove();
assembler.findRecipe(13760000, [<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.small_coil>*4, <metaitem:component.smd.capacitor>*4,
<metaitem:plate.random_access_memory>*4, <metaitem:circuit.wetware_processor>*2, <metaitem:board.wetware>], [<liquid:soldering_alloy> * 144]).remove();
assembly_line.recipeBuilder()
.inputs(<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.small_coil>*4, <metaitem:component.smd.capacitor>*4,
<metaitem:plate.random_access_memory>*4, <metaitem:circuit.wetware_processor>*2, <metaitem:processor.neuro>)
.outputs(<metaitem:circuit.wetware_assembly>)
.fluidInputs([<liquid:soldering_alloy> * 144])
.duration(400)
.EUt(34400)
.buildAndRegister();
assembly_line.recipeBuilder()
.inputs(<ore:wireFineYttriumBariumCuprate>.firstItem *6, <metaitem:component.small_coil>*4, <metaitem:component.smd.capacitor>*4,
<metaitem:plate.random_access_memory>*4, <metaitem:circuit.wetware_processor>*2, <metaitem:processor.neuro>)
.outputs(<metaitem:circuit.wetware_assembly>)
.fluidInputs([<liquid:tin> * 288])
.duration(400)
.EUt(34400)
.buildAndRegister();
#wetware processor - <gregtech:meta_item_2:32498> - <ore:circuitMaster>
assembly_line.recipeBuilder()
.inputs(<metaitem:component.smd.capacitor>*2,<metaitem:component.smd.transistor>*2, <metaitem:component.smd.diode>, <ore:wireFineYttriumBariumCuprate>.firstItem *2, <metaitem:processor.neuro>,
<metaitem:crystal.central_processing_unit>, <metaitem:plate.nano_central_processing_unit>)
.outputs(<metaitem:circuit.wetware_processor>)
.fluidInputs([<liquid:tin> * 288])
.duration(200)
.EUt(30720)
.buildAndRegister();
assembly_line.recipeBuilder()
.inputs(<metaitem:component.smd.capacitor>*2,<metaitem:component.smd.transistor>*2, <metaitem:component.smd.diode>, <ore:wireFineYttriumBariumCuprate>.firstItem *2, <metaitem:processor.neuro>,
<metaitem:crystal.central_processing_unit>, <metaitem:plate.nano_central_processing_unit>)
.outputs(<metaitem:circuit.wetware_processor>)
.fluidInputs([<liquid:soldering_alloy> * 144])
.duration(200)
.EUt(30720)
.buildAndRegister();
#uranium dust from thorium
mods.botania.ManaInfusion.addAlchemy(<ore:dustSmallUranium>.firstItem, <ore:dustThorium>, 500);
#Wooden form
RecipeBuilder.get("basic")
.setShapeless([<ore:slabWood>])
.addTool(<ore:toolSaw>, 5)
.addOutput(<metaitem:wooden_form.empty> * 2)
.create();
cutting_saw.recipeBuilder()
.inputs([<ore:slabWood>])
.fluidInputs([<liquid:water> * 5])
.outputs([<metaitem:wooden_form.empty> * 2])
.EUt(8)
.duration(400)
.buildAndRegister();
#add basalt to chisel group
mods.chisel.Carving.addVariation("basalt", <gregtech:mineral:14>);
mods.chisel.Carving.addVariation("basalt", <gregtech:mineral:7>);
mods.chisel.Carving.addVariation("basalt", <gregtech:mineral:3>);
mods.chisel.Carving.addVariation("basalt", <gregtech:mineral:2>);
mods.chisel.Carving.addVariation("basalt", <gregtech:mineral:15>);
#damascus steel dust
recipes.addShapeless(<ore:dustDamascusSteel>.firstItem * 4, [<ore:dustIron>,<ore:dustSteel>,<ore:dustSteel>,<ore:dustSteel>]);
#rotor stack size
<ore:rotorChrome>.firstItem.maxStackSize = 64;
<ore:rotorBronze>.firstItem.maxStackSize = 64;
<ore:rotorIridium>.firstItem.maxStackSize = 64;
<ore:rotorDarmstadtium>.firstItem.maxStackSize = 64;
<ore:rotorOsmium>.firstItem.maxStackSize = 64;
<ore:rotorTin>.firstItem.maxStackSize = 64;
<ore:rotorTitanium>.firstItem.maxStackSize = 64;
<ore:rotorSteel>.firstItem.maxStackSize = 64;
<ore:rotorTungstenSteel>.firstItem.maxStackSize = 64;
<ore:rotorSteelMagnetic>.firstItem.maxStackSize = 64;
<ore:rotorHssg>.firstItem.maxStackSize = 64;
<ore:rotorEnderium>.firstItem.maxStackSize = 64;
<ore:rotorDraconium>.firstItem.maxStackSize = 64;
<ore:rotorNeutronium>.firstItem.maxStackSize = 64;
<ore:rotorStainlessSteel>.firstItem.maxStackSize = 64;
<ore:rotorHsse>.firstItem.maxStackSize = 64;
#higher tier superconductor cabling
recipes.addShapeless(<ore:cableGtHexSuperconductor>.firstItem, [<ore:cableGtOctalSuperconductor>,<ore:cableGtOctalSuperconductor>]);
recipes.addShapeless(<ore:cableGtOctalSuperconductor>.firstItem, [<ore:cableGtQuadrupleSuperconductor>,<ore:cableGtQuadrupleSuperconductor>]);
recipes.addShapeless(<ore:cableGtQuadrupleSuperconductor>.firstItem, [<ore:cableGtDoubleSuperconductor>,<ore:cableGtDoubleSuperconductor>]);
recipes.addShapeless(<ore:cableGtDoubleSuperconductor>.firstItem, [<ore:cableGtSingleSuperconductor>,<ore:cableGtSingleSuperconductor>]);
#bluesteel
recipes.addShapeless(<ore:cableGtHexBluesteel>.firstItem, [<ore:cableGtOctalBluesteel>,<ore:cableGtOctalBluesteel>]);
recipes.addShapeless(<ore:cableGtOctalBluesteel>.firstItem, [<ore:cableGtQuadrupleBluesteel>,<ore:cableGtQuadrupleBluesteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleBluesteel>.firstItem, [<ore:cableGtDoubleBluesteel>,<ore:cableGtDoubleBluesteel>]);
recipes.addShapeless(<ore:cableGtDoubleBluesteel>.firstItem, [<ore:cableGtSingleBluesteel>,<ore:cableGtSingleBluesteel>]);
#manasteel
recipes.addShapeless(<ore:cableGtHexManasteel>.firstItem, [<ore:cableGtOctalManasteel>,<ore:cableGtOctalManasteel>]);
recipes.addShapeless(<ore:cableGtOctalManasteel>.firstItem, [<ore:cableGtQuadrupleManasteel>,<ore:cableGtQuadrupleManasteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleManasteel>.firstItem, [<ore:cableGtDoubleManasteel>,<ore:cableGtDoubleManasteel>]);
recipes.addShapeless(<ore:cableGtDoubleManasteel>.firstItem, [<ore:cableGtSingleManasteel>,<ore:cableGtSingleManasteel>]);
#signalum
recipes.addShapeless(<ore:cableGtHexSignalum>.firstItem, [<ore:cableGtOctalSignalum>,<ore:cableGtOctalSignalum>]);
recipes.addShapeless(<ore:cableGtOctalSignalum>.firstItem, [<ore:cableGtQuadrupleSignalum>,<ore:cableGtQuadrupleSignalum>]);
recipes.addShapeless(<ore:cableGtQuadrupleSignalum>.firstItem, [<ore:cableGtDoubleSignalum>,<ore:cableGtDoubleSignalum>]);
recipes.addShapeless(<ore:cableGtDoubleSignalum>.firstItem, [<ore:cableGtSingleSignalum>,<ore:cableGtSingleSignalum>]);
#enderium
recipes.addShapeless(<ore:cableGtHexEnderium>.firstItem, [<ore:cableGtOctalEnderium>,<ore:cableGtOctalEnderium>]);
recipes.addShapeless(<ore:cableGtOctalEnderium>.firstItem, [<ore:cableGtQuadrupleEnderium>,<ore:cableGtQuadrupleEnderium>]);
recipes.addShapeless(<ore:cableGtQuadrupleEnderium>.firstItem, [<ore:cableGtDoubleEnderium>,<ore:cableGtDoubleEnderium>]);
recipes.addShapeless(<ore:cableGtDoubleEnderium>.firstItem, [<ore:cableGtSingleEnderium>,<ore:cableGtSingleEnderium>]);
#Stellar Alloy
recipes.addShapeless(<ore:cableGtHexStellarAlloy>.firstItem, [<ore:cableGtOctalStellarAlloy>,<ore:cableGtOctalStellarAlloy>]);
recipes.addShapeless(<ore:cableGtOctalStellarAlloy>.firstItem, [<ore:cableGtQuadrupleStellarAlloy>,<ore:cableGtQuadrupleStellarAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleStellarAlloy>.firstItem, [<ore:cableGtDoubleStellarAlloy>,<ore:cableGtDoubleStellarAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleStellarAlloy>.firstItem, [<ore:cableGtSingleStellarAlloy>,<ore:cableGtSingleStellarAlloy>]);
#Terrasteel
recipes.addShapeless(<ore:cableGtHexTerrasteel>.firstItem, [<ore:cableGtOctalTerrasteel>,<ore:cableGtOctalTerrasteel>]);
recipes.addShapeless(<ore:cableGtOctalTerrasteel>.firstItem, [<ore:cableGtQuadrupleTerrasteel>,<ore:cableGtQuadrupleTerrasteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleTerrasteel>.firstItem, [<ore:cableGtDoubleTerrasteel>,<ore:cableGtDoubleTerrasteel>]);
recipes.addShapeless(<ore:cableGtDoubleTerrasteel>.firstItem, [<ore:cableGtSingleTerrasteel>,<ore:cableGtSingleTerrasteel>]);
#lossless cable uncrafting
recipes.addShapeless(<ore:cableGtOctalSuperconductor>.firstItem *2, [<ore:cableGtHexSuperconductor>]);
recipes.addShapeless(<ore:cableGtQuadrupleSuperconductor>.firstItem *2, [<ore:cableGtOctalSuperconductor>]);
recipes.addShapeless(<ore:cableGtDoubleSuperconductor>.firstItem *2, [<ore:cableGtQuadrupleSuperconductor>]);
recipes.addShapeless(<ore:cableGtSingleSuperconductor>.firstItem *2, [<ore:cableGtDoubleSuperconductor>]);
#bluesteel
recipes.addShapeless(<ore:cableGtOctalBluesteel>.firstItem *2, [<ore:cableGtHexBluesteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleBluesteel>.firstItem *2, [<ore:cableGtOctalBluesteel>]);
recipes.addShapeless(<ore:cableGtDoubleBluesteel>.firstItem *2, [<ore:cableGtQuadrupleBluesteel>]);
recipes.addShapeless(<ore:cableGtSingleBluesteel>.firstItem *2, [<ore:cableGtDoubleBluesteel>]);
#manasteel
recipes.addShapeless(<ore:cableGtOctalManasteel>.firstItem *2, [<ore:cableGtHexManasteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleManasteel>.firstItem *2, [<ore:cableGtOctalManasteel>]);
recipes.addShapeless(<ore:cableGtDoubleManasteel>.firstItem *2, [<ore:cableGtQuadrupleManasteel>]);
recipes.addShapeless(<ore:cableGtSingleManasteel>.firstItem *2, [<ore:cableGtDoubleManasteel>]);
#signalum
recipes.addShapeless(<ore:cableGtOctalSignalum>.firstItem *2, [<ore:cableGtHexSignalum>]);
recipes.addShapeless(<ore:cableGtQuadrupleSignalum>.firstItem *2, [<ore:cableGtOctalSignalum>]);
recipes.addShapeless(<ore:cableGtDoubleSignalum>.firstItem *2, [<ore:cableGtQuadrupleSignalum>]);
recipes.addShapeless(<ore:cableGtSingleSignalum>.firstItem *2, [<ore:cableGtDoubleSignalum>]);
#enderium
recipes.addShapeless(<ore:cableGtOctalEnderium>.firstItem *2, [<ore:cableGtHexEnderium>]);
recipes.addShapeless(<ore:cableGtQuadrupleEnderium>.firstItem *2, [<ore:cableGtOctalEnderium>]);
recipes.addShapeless(<ore:cableGtDoubleEnderium>.firstItem *2, [<ore:cableGtQuadrupleEnderium>]);
recipes.addShapeless(<ore:cableGtSingleEnderium>.firstItem *2, [<ore:cableGtDoubleEnderium>]);
#Stellar Alloy
recipes.addShapeless(<ore:cableGtOctalStellarAlloy>.firstItem *2, [<ore:cableGtHexStellarAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleStellarAlloy>.firstItem *2, [<ore:cableGtOctalStellarAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleStellarAlloy>.firstItem *2, [<ore:cableGtQuadrupleStellarAlloy>]);
recipes.addShapeless(<ore:cableGtSingleStellarAlloy>.firstItem *2, [<ore:cableGtDoubleStellarAlloy>]);
#Terrasteel
recipes.addShapeless(<ore:cableGtOctalTerrasteel>.firstItem *2, [<ore:cableGtHexTerrasteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleTerrasteel>.firstItem *2, [<ore:cableGtOctalTerrasteel>]);
recipes.addShapeless(<ore:cableGtDoubleTerrasteel>.firstItem *2, [<ore:cableGtQuadrupleTerrasteel>]);
recipes.addShapeless(<ore:cableGtSingleTerrasteel>.firstItem *2, [<ore:cableGtDoubleTerrasteel>]);
#gtfo solar panels
recipes.remove(<metaitem:cover.solar.panel>);
recipes.addShaped(<metaitem:cover.solar.panel>, [[<ore:plateSilicon>, <ore:plateGlass>, <ore:plateSilicon>],[<ore:plateAluminium>, <contenttweaker:infinityegg>, <ore:plateAluminium>], [<ore:plateAluminium>, <ore:plateAluminium>, <ore:plateAluminium>]]);
#fix for manual cable crafting
recipes.addShapeless(<ore:cableGtHexAluminium>.firstItem, [<ore:cableGtOctalAluminium>,<ore:cableGtOctalAluminium>]);
recipes.addShapeless(<ore:cableGtOctalAluminium>.firstItem, [<ore:cableGtQuadrupleAluminium>,<ore:cableGtQuadrupleAluminium>]);
recipes.addShapeless(<ore:cableGtQuadrupleAluminium>.firstItem, [<ore:cableGtDoubleAluminium>,<ore:cableGtDoubleAluminium>]);
recipes.addShapeless(<ore:cableGtDoubleAluminium>.firstItem, [<ore:cableGtSingleAluminium>,<ore:cableGtSingleAluminium>]);
recipes.addShapeless(<ore:cableGtOctalAluminium>.firstItem *2, [<ore:cableGtHexAluminium>]);
recipes.addShapeless(<ore:cableGtQuadrupleAluminium>.firstItem *2, [<ore:cableGtOctalAluminium>]);
recipes.addShapeless(<ore:cableGtDoubleAluminium>.firstItem *2, [<ore:cableGtQuadrupleAluminium>]);
recipes.addShapeless(<ore:cableGtSingleAluminium>.firstItem *2, [<ore:cableGtDoubleAluminium>]);
recipes.addShapeless(<ore:cableGtHexAnnealedCopper>.firstItem, [<ore:cableGtOctalAnnealedCopper>,<ore:cableGtOctalAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtOctalAnnealedCopper>.firstItem, [<ore:cableGtQuadrupleAnnealedCopper>,<ore:cableGtQuadrupleAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtQuadrupleAnnealedCopper>.firstItem, [<ore:cableGtDoubleAnnealedCopper>,<ore:cableGtDoubleAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtDoubleAnnealedCopper>.firstItem, [<ore:cableGtSingleAnnealedCopper>,<ore:cableGtSingleAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtOctalAnnealedCopper>.firstItem *2, [<ore:cableGtHexAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtQuadrupleAnnealedCopper>.firstItem *2, [<ore:cableGtOctalAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtDoubleAnnealedCopper>.firstItem *2, [<ore:cableGtQuadrupleAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtSingleAnnealedCopper>.firstItem *2, [<ore:cableGtDoubleAnnealedCopper>]);
recipes.addShapeless(<ore:cableGtHexBlackSteel>.firstItem, [<ore:cableGtOctalBlackSteel>,<ore:cableGtOctalBlackSteel>]);
recipes.addShapeless(<ore:cableGtOctalBlackSteel>.firstItem, [<ore:cableGtQuadrupleBlackSteel>,<ore:cableGtQuadrupleBlackSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleBlackSteel>.firstItem, [<ore:cableGtDoubleBlackSteel>,<ore:cableGtDoubleBlackSteel>]);
recipes.addShapeless(<ore:cableGtDoubleBlackSteel>.firstItem, [<ore:cableGtSingleBlackSteel>,<ore:cableGtSingleBlackSteel>]);
recipes.addShapeless(<ore:cableGtOctalBlackSteel>.firstItem *2, [<ore:cableGtHexBlackSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleBlackSteel>.firstItem *2, [<ore:cableGtOctalBlackSteel>]);
recipes.addShapeless(<ore:cableGtDoubleBlackSteel>.firstItem *2, [<ore:cableGtQuadrupleBlackSteel>]);
recipes.addShapeless(<ore:cableGtSingleBlackSteel>.firstItem *2, [<ore:cableGtDoubleBlackSteel>]);
recipes.addShapeless(<ore:cableGtHexCobalt>.firstItem, [<ore:cableGtOctalCobalt>,<ore:cableGtOctalCobalt>]);
recipes.addShapeless(<ore:cableGtOctalCobalt>.firstItem, [<ore:cableGtQuadrupleCobalt>,<ore:cableGtQuadrupleCobalt>]);
recipes.addShapeless(<ore:cableGtQuadrupleCobalt>.firstItem, [<ore:cableGtDoubleCobalt>,<ore:cableGtDoubleCobalt>]);
recipes.addShapeless(<ore:cableGtDoubleCobalt>.firstItem, [<ore:cableGtSingleCobalt>,<ore:cableGtSingleCobalt>]);
recipes.addShapeless(<ore:cableGtOctalCobalt>.firstItem *2, [<ore:cableGtHexCobalt>]);
recipes.addShapeless(<ore:cableGtQuadrupleCobalt>.firstItem *2, [<ore:cableGtOctalCobalt>]);
recipes.addShapeless(<ore:cableGtDoubleCobalt>.firstItem *2, [<ore:cableGtQuadrupleCobalt>]);
recipes.addShapeless(<ore:cableGtSingleCobalt>.firstItem *2, [<ore:cableGtDoubleCobalt>]);
recipes.addShapeless(<ore:cableGtHexCopper>.firstItem, [<ore:cableGtOctalCopper>,<ore:cableGtOctalCopper>]);
recipes.addShapeless(<ore:cableGtOctalCopper>.firstItem, [<ore:cableGtQuadrupleCopper>,<ore:cableGtQuadrupleCopper>]);
recipes.addShapeless(<ore:cableGtQuadrupleCopper>.firstItem, [<ore:cableGtDoubleCopper>,<ore:cableGtDoubleCopper>]);
recipes.addShapeless(<ore:cableGtDoubleCopper>.firstItem, [<ore:cableGtSingleCopper>,<ore:cableGtSingleCopper>]);
recipes.addShapeless(<ore:cableGtOctalCopper>.firstItem *2, [<ore:cableGtHexCopper>]);
recipes.addShapeless(<ore:cableGtQuadrupleCopper>.firstItem *2, [<ore:cableGtOctalCopper>]);
recipes.addShapeless(<ore:cableGtDoubleCopper>.firstItem *2, [<ore:cableGtQuadrupleCopper>]);
recipes.addShapeless(<ore:cableGtSingleCopper>.firstItem *2, [<ore:cableGtDoubleCopper>]);
recipes.addShapeless(<ore:cableGtHexCupronickel>.firstItem, [<ore:cableGtOctalCupronickel>,<ore:cableGtOctalCupronickel>]);
recipes.addShapeless(<ore:cableGtOctalCupronickel>.firstItem, [<ore:cableGtQuadrupleCupronickel>,<ore:cableGtQuadrupleCupronickel>]);
recipes.addShapeless(<ore:cableGtQuadrupleCupronickel>.firstItem, [<ore:cableGtDoubleCupronickel>,<ore:cableGtDoubleCupronickel>]);
recipes.addShapeless(<ore:cableGtDoubleCupronickel>.firstItem, [<ore:cableGtSingleCupronickel>,<ore:cableGtSingleCupronickel>]);
recipes.addShapeless(<ore:cableGtOctalCupronickel>.firstItem *2, [<ore:cableGtHexCupronickel>]);
recipes.addShapeless(<ore:cableGtQuadrupleCupronickel>.firstItem *2, [<ore:cableGtOctalCupronickel>]);
recipes.addShapeless(<ore:cableGtDoubleCupronickel>.firstItem *2, [<ore:cableGtQuadrupleCupronickel>]);
recipes.addShapeless(<ore:cableGtSingleCupronickel>.firstItem *2, [<ore:cableGtDoubleCupronickel>]);
recipes.addShapeless(<ore:cableGtHexDuranium>.firstItem, [<ore:cableGtOctalDuranium>,<ore:cableGtOctalDuranium>]);
recipes.addShapeless(<ore:cableGtOctalDuranium>.firstItem, [<ore:cableGtQuadrupleDuranium>,<ore:cableGtQuadrupleDuranium>]);
recipes.addShapeless(<ore:cableGtQuadrupleDuranium>.firstItem, [<ore:cableGtDoubleDuranium>,<ore:cableGtDoubleDuranium>]);
recipes.addShapeless(<ore:cableGtDoubleDuranium>.firstItem, [<ore:cableGtSingleDuranium>,<ore:cableGtSingleDuranium>]);
recipes.addShapeless(<ore:cableGtOctalDuranium>.firstItem *2, [<ore:cableGtHexDuranium>]);
recipes.addShapeless(<ore:cableGtQuadrupleDuranium>.firstItem *2, [<ore:cableGtOctalDuranium>]);
recipes.addShapeless(<ore:cableGtDoubleDuranium>.firstItem *2, [<ore:cableGtQuadrupleDuranium>]);
recipes.addShapeless(<ore:cableGtSingleDuranium>.firstItem *2, [<ore:cableGtDoubleDuranium>]);
recipes.addShapeless(<ore:cableGtHexElectrum>.firstItem, [<ore:cableGtOctalElectrum>,<ore:cableGtOctalElectrum>]);
recipes.addShapeless(<ore:cableGtOctalElectrum>.firstItem, [<ore:cableGtQuadrupleElectrum>,<ore:cableGtQuadrupleElectrum>]);
recipes.addShapeless(<ore:cableGtQuadrupleElectrum>.firstItem, [<ore:cableGtDoubleElectrum>,<ore:cableGtDoubleElectrum>]);
recipes.addShapeless(<ore:cableGtDoubleElectrum>.firstItem, [<ore:cableGtSingleElectrum>,<ore:cableGtSingleElectrum>]);
recipes.addShapeless(<ore:cableGtOctalElectrum>.firstItem *2, [<ore:cableGtHexElectrum>]);
recipes.addShapeless(<ore:cableGtQuadrupleElectrum>.firstItem *2, [<ore:cableGtOctalElectrum>]);
recipes.addShapeless(<ore:cableGtDoubleElectrum>.firstItem *2, [<ore:cableGtQuadrupleElectrum>]);
recipes.addShapeless(<ore:cableGtSingleElectrum>.firstItem *2, [<ore:cableGtDoubleElectrum>]);
recipes.addShapeless(<ore:cableGtHex Gold>.firstItem, [<ore:cableGtOctal Gold>,<ore:cableGtOctal Gold>]);
recipes.addShapeless(<ore:cableGtOctal Gold>.firstItem, [<ore:cableGtQuadruple Gold>,<ore:cableGtQuadruple Gold>]);
recipes.addShapeless(<ore:cableGtQuadruple Gold>.firstItem, [<ore:cableGtDouble Gold>,<ore:cableGtDouble Gold>]);
recipes.addShapeless(<ore:cableGtDouble Gold>.firstItem, [<ore:cableGtSingle Gold>,<ore:cableGtSingle Gold>]);
recipes.addShapeless(<ore:cableGtOctal Gold>.firstItem *2, [<ore:cableGtHex Gold>]);
recipes.addShapeless(<ore:cableGtQuadruple Gold>.firstItem *2, [<ore:cableGtOctal Gold>]);
recipes.addShapeless(<ore:cableGtDouble Gold>.firstItem *2, [<ore:cableGtQuadruple Gold>]);
recipes.addShapeless(<ore:cableGtSingle Gold>.firstItem *2, [<ore:cableGtDouble Gold>]);
recipes.addShapeless(<ore:cableGtHexGraphene>.firstItem, [<ore:cableGtOctalGraphene>,<ore:cableGtOctalGraphene>]);
recipes.addShapeless(<ore:cableGtOctalGraphene>.firstItem, [<ore:cableGtQuadrupleGraphene>,<ore:cableGtQuadrupleGraphene>]);
recipes.addShapeless(<ore:cableGtQuadrupleGraphene>.firstItem, [<ore:cableGtDoubleGraphene>,<ore:cableGtDoubleGraphene>]);
recipes.addShapeless(<ore:cableGtDoubleGraphene>.firstItem, [<ore:cableGtSingleGraphene>,<ore:cableGtSingleGraphene>]);
recipes.addShapeless(<ore:cableGtOctalGraphene>.firstItem *2, [<ore:cableGtHexGraphene>]);
recipes.addShapeless(<ore:cableGtQuadrupleGraphene>.firstItem *2, [<ore:cableGtOctalGraphene>]);
recipes.addShapeless(<ore:cableGtDoubleGraphene>.firstItem *2, [<ore:cableGtQuadrupleGraphene>]);
recipes.addShapeless(<ore:cableGtSingleGraphene>.firstItem *2, [<ore:cableGtDoubleGraphene>]);
recipes.addShapeless(<ore:cableGtHexHssg>.firstItem, [<ore:cableGtOctalHssg>,<ore:cableGtOctalHssg>]);
recipes.addShapeless(<ore:cableGtOctalHssg>.firstItem, [<ore:cableGtQuadrupleHssg>,<ore:cableGtQuadrupleHssg>]);
recipes.addShapeless(<ore:cableGtQuadrupleHssg>.firstItem, [<ore:cableGtDoubleHssg>,<ore:cableGtDoubleHssg>]);
recipes.addShapeless(<ore:cableGtDoubleHssg>.firstItem, [<ore:cableGtSingleHssg>,<ore:cableGtSingleHssg>]);
recipes.addShapeless(<ore:cableGtOctalHssg>.firstItem *2, [<ore:cableGtHexHssg>]);
recipes.addShapeless(<ore:cableGtQuadrupleHssg>.firstItem *2, [<ore:cableGtOctalHssg>]);
recipes.addShapeless(<ore:cableGtDoubleHssg>.firstItem *2, [<ore:cableGtQuadrupleHssg>]);
recipes.addShapeless(<ore:cableGtSingleHssg>.firstItem *2, [<ore:cableGtDoubleHssg>]);
recipes.addShapeless(<ore:cableGtHexIron>.firstItem, [<ore:cableGtOctalIron>,<ore:cableGtOctalIron>]);
recipes.addShapeless(<ore:cableGtOctalIron>.firstItem, [<ore:cableGtQuadrupleIron>,<ore:cableGtQuadrupleIron>]);
recipes.addShapeless(<ore:cableGtQuadrupleIron>.firstItem, [<ore:cableGtDoubleIron>,<ore:cableGtDoubleIron>]);
recipes.addShapeless(<ore:cableGtDoubleIron>.firstItem, [<ore:cableGtSingleIron>,<ore:cableGtSingleIron>]);
recipes.addShapeless(<ore:cableGtOctalIron>.firstItem *2, [<ore:cableGtHexIron>]);
recipes.addShapeless(<ore:cableGtQuadrupleIron>.firstItem *2, [<ore:cableGtOctalIron>]);
recipes.addShapeless(<ore:cableGtDoubleIron>.firstItem *2, [<ore:cableGtQuadrupleIron>]);
recipes.addShapeless(<ore:cableGtSingleIron>.firstItem *2, [<ore:cableGtDoubleIron>]);
recipes.addShapeless(<ore:cableGtHexKanthal>.firstItem, [<ore:cableGtOctalKanthal>,<ore:cableGtOctalKanthal>]);
recipes.addShapeless(<ore:cableGtOctalKanthal>.firstItem, [<ore:cableGtQuadrupleKanthal>,<ore:cableGtQuadrupleKanthal>]);
recipes.addShapeless(<ore:cableGtQuadrupleKanthal>.firstItem, [<ore:cableGtDoubleKanthal>,<ore:cableGtDoubleKanthal>]);
recipes.addShapeless(<ore:cableGtDoubleKanthal>.firstItem, [<ore:cableGtSingleKanthal>,<ore:cableGtSingleKanthal>]);
recipes.addShapeless(<ore:cableGtOctalKanthal>.firstItem *2, [<ore:cableGtHexKanthal>]);
recipes.addShapeless(<ore:cableGtQuadrupleKanthal>.firstItem *2, [<ore:cableGtOctalKanthal>]);
recipes.addShapeless(<ore:cableGtDoubleKanthal>.firstItem *2, [<ore:cableGtQuadrupleKanthal>]);
recipes.addShapeless(<ore:cableGtSingleKanthal>.firstItem *2, [<ore:cableGtDoubleKanthal>]);
recipes.addShapeless(<ore:cableGtHexLead>.firstItem, [<ore:cableGtOctalLead>,<ore:cableGtOctalLead>]);
recipes.addShapeless(<ore:cableGtOctalLead>.firstItem, [<ore:cableGtQuadrupleLead>,<ore:cableGtQuadrupleLead>]);
recipes.addShapeless(<ore:cableGtQuadrupleLead>.firstItem, [<ore:cableGtDoubleLead>,<ore:cableGtDoubleLead>]);
recipes.addShapeless(<ore:cableGtDoubleLead>.firstItem, [<ore:cableGtSingleLead>,<ore:cableGtSingleLead>]);
recipes.addShapeless(<ore:cableGtOctalLead>.firstItem *2, [<ore:cableGtHexLead>]);
recipes.addShapeless(<ore:cableGtQuadrupleLead>.firstItem *2, [<ore:cableGtOctalLead>]);
recipes.addShapeless(<ore:cableGtDoubleLead>.firstItem *2, [<ore:cableGtQuadrupleLead>]);
recipes.addShapeless(<ore:cableGtSingleLead>.firstItem *2, [<ore:cableGtDoubleLead>]);
recipes.addShapeless(<ore:cableGtHexNaquadah>.firstItem, [<ore:cableGtOctalNaquadah>,<ore:cableGtOctalNaquadah>]);
recipes.addShapeless(<ore:cableGtOctalNaquadah>.firstItem, [<ore:cableGtQuadrupleNaquadah>,<ore:cableGtQuadrupleNaquadah>]);
recipes.addShapeless(<ore:cableGtQuadrupleNaquadah>.firstItem, [<ore:cableGtDoubleNaquadah>,<ore:cableGtDoubleNaquadah>]);
recipes.addShapeless(<ore:cableGtDoubleNaquadah>.firstItem, [<ore:cableGtSingleNaquadah>,<ore:cableGtSingleNaquadah>]);
recipes.addShapeless(<ore:cableGtOctalNaquadah>.firstItem *2, [<ore:cableGtHexNaquadah>]);
recipes.addShapeless(<ore:cableGtQuadrupleNaquadah>.firstItem *2, [<ore:cableGtOctalNaquadah>]);
recipes.addShapeless(<ore:cableGtDoubleNaquadah>.firstItem *2, [<ore:cableGtQuadrupleNaquadah>]);
recipes.addShapeless(<ore:cableGtSingleNaquadah>.firstItem *2, [<ore:cableGtDoubleNaquadah>]);
recipes.addShapeless(<ore:cableGtHexNaquadahAlloy>.firstItem, [<ore:cableGtOctalNaquadahAlloy>,<ore:cableGtOctalNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtOctalNaquadahAlloy>.firstItem, [<ore:cableGtQuadrupleNaquadahAlloy>,<ore:cableGtQuadrupleNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleNaquadahAlloy>.firstItem, [<ore:cableGtDoubleNaquadahAlloy>,<ore:cableGtDoubleNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleNaquadahAlloy>.firstItem, [<ore:cableGtSingleNaquadahAlloy>,<ore:cableGtSingleNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtOctalNaquadahAlloy>.firstItem *2, [<ore:cableGtHexNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleNaquadahAlloy>.firstItem *2, [<ore:cableGtOctalNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleNaquadahAlloy>.firstItem *2, [<ore:cableGtQuadrupleNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtSingleNaquadahAlloy>.firstItem *2, [<ore:cableGtDoubleNaquadahAlloy>]);
recipes.addShapeless(<ore:cableGtHexNichrome>.firstItem, [<ore:cableGtOctalNichrome>,<ore:cableGtOctalNichrome>]);
recipes.addShapeless(<ore:cableGtOctalNichrome>.firstItem, [<ore:cableGtQuadrupleNichrome>,<ore:cableGtQuadrupleNichrome>]);
recipes.addShapeless(<ore:cableGtQuadrupleNichrome>.firstItem, [<ore:cableGtDoubleNichrome>,<ore:cableGtDoubleNichrome>]);
recipes.addShapeless(<ore:cableGtDoubleNichrome>.firstItem, [<ore:cableGtSingleNichrome>,<ore:cableGtSingleNichrome>]);
recipes.addShapeless(<ore:cableGtOctalNichrome>.firstItem *2, [<ore:cableGtHexNichrome>]);
recipes.addShapeless(<ore:cableGtQuadrupleNichrome>.firstItem *2, [<ore:cableGtOctalNichrome>]);
recipes.addShapeless(<ore:cableGtDoubleNichrome>.firstItem *2, [<ore:cableGtQuadrupleNichrome>]);
recipes.addShapeless(<ore:cableGtSingleNichrome>.firstItem *2, [<ore:cableGtDoubleNichrome>]);
recipes.addShapeless(<ore:cableGtHexNickel>.firstItem, [<ore:cableGtOctalNickel>,<ore:cableGtOctalNickel>]);
recipes.addShapeless(<ore:cableGtOctalNickel>.firstItem, [<ore:cableGtQuadrupleNickel>,<ore:cableGtQuadrupleNickel>]);
recipes.addShapeless(<ore:cableGtQuadrupleNickel>.firstItem, [<ore:cableGtDoubleNickel>,<ore:cableGtDoubleNickel>]);
recipes.addShapeless(<ore:cableGtDoubleNickel>.firstItem, [<ore:cableGtSingleNickel>,<ore:cableGtSingleNickel>]);
recipes.addShapeless(<ore:cableGtOctalNickel>.firstItem *2, [<ore:cableGtHexNickel>]);
recipes.addShapeless(<ore:cableGtQuadrupleNickel>.firstItem *2, [<ore:cableGtOctalNickel>]);
recipes.addShapeless(<ore:cableGtDoubleNickel>.firstItem *2, [<ore:cableGtQuadrupleNickel>]);
recipes.addShapeless(<ore:cableGtSingleNickel>.firstItem *2, [<ore:cableGtDoubleNickel>]);
recipes.addShapeless(<ore:cableGtHexNiobiumTitanium>.firstItem, [<ore:cableGtOctalNiobiumTitanium>,<ore:cableGtOctalNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtOctalNiobiumTitanium>.firstItem, [<ore:cableGtQuadrupleNiobiumTitanium>,<ore:cableGtQuadrupleNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtQuadrupleNiobiumTitanium>.firstItem, [<ore:cableGtDoubleNiobiumTitanium>,<ore:cableGtDoubleNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtDoubleNiobiumTitanium>.firstItem, [<ore:cableGtSingleNiobiumTitanium>,<ore:cableGtSingleNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtOctalNiobiumTitanium>.firstItem *2, [<ore:cableGtHexNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtQuadrupleNiobiumTitanium>.firstItem *2, [<ore:cableGtOctalNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtDoubleNiobiumTitanium>.firstItem *2, [<ore:cableGtQuadrupleNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtSingleNiobiumTitanium>.firstItem *2, [<ore:cableGtDoubleNiobiumTitanium>]);
recipes.addShapeless(<ore:cableGtHexOsmium>.firstItem, [<ore:cableGtOctalOsmium>,<ore:cableGtOctalOsmium>]);
recipes.addShapeless(<ore:cableGtOctalOsmium>.firstItem, [<ore:cableGtQuadrupleOsmium>,<ore:cableGtQuadrupleOsmium>]);
recipes.addShapeless(<ore:cableGtQuadrupleOsmium>.firstItem, [<ore:cableGtDoubleOsmium>,<ore:cableGtDoubleOsmium>]);
recipes.addShapeless(<ore:cableGtDoubleOsmium>.firstItem, [<ore:cableGtSingleOsmium>,<ore:cableGtSingleOsmium>]);
recipes.addShapeless(<ore:cableGtOctalOsmium>.firstItem *2, [<ore:cableGtHexOsmium>]);
recipes.addShapeless(<ore:cableGtQuadrupleOsmium>.firstItem *2, [<ore:cableGtOctalOsmium>]);
recipes.addShapeless(<ore:cableGtDoubleOsmium>.firstItem *2, [<ore:cableGtQuadrupleOsmium>]);
recipes.addShapeless(<ore:cableGtSingleOsmium>.firstItem *2, [<ore:cableGtDoubleOsmium>]);
recipes.addShapeless(<ore:cableGtHexPlatinum>.firstItem, [<ore:cableGtOctalPlatinum>,<ore:cableGtOctalPlatinum>]);
recipes.addShapeless(<ore:cableGtOctalPlatinum>.firstItem, [<ore:cableGtQuadruplePlatinum>,<ore:cableGtQuadruplePlatinum>]);
recipes.addShapeless(<ore:cableGtQuadruplePlatinum>.firstItem, [<ore:cableGtDoublePlatinum>,<ore:cableGtDoublePlatinum>]);
recipes.addShapeless(<ore:cableGtDoublePlatinum>.firstItem, [<ore:cableGtSinglePlatinum>,<ore:cableGtSinglePlatinum>]);
recipes.addShapeless(<ore:cableGtOctalPlatinum>.firstItem *2, [<ore:cableGtHexPlatinum>]);
recipes.addShapeless(<ore:cableGtQuadruplePlatinum>.firstItem *2, [<ore:cableGtOctalPlatinum>]);
recipes.addShapeless(<ore:cableGtDoublePlatinum>.firstItem *2, [<ore:cableGtQuadruplePlatinum>]);
recipes.addShapeless(<ore:cableGtSinglePlatinum>.firstItem *2, [<ore:cableGtDoublePlatinum>]);
recipes.addShapeless(<ore:cableGtHexRedAlloy>.firstItem, [<ore:cableGtOctalRedAlloy>,<ore:cableGtOctalRedAlloy>]);
recipes.addShapeless(<ore:cableGtOctalRedAlloy>.firstItem, [<ore:cableGtQuadrupleRedAlloy>,<ore:cableGtQuadrupleRedAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleRedAlloy>.firstItem, [<ore:cableGtDoubleRedAlloy>,<ore:cableGtDoubleRedAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleRedAlloy>.firstItem, [<ore:cableGtSingleRedAlloy>,<ore:cableGtSingleRedAlloy>]);
recipes.addShapeless(<ore:cableGtOctalRedAlloy>.firstItem *2, [<ore:cableGtHexRedAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleRedAlloy>.firstItem *2, [<ore:cableGtOctalRedAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleRedAlloy>.firstItem *2, [<ore:cableGtQuadrupleRedAlloy>]);
recipes.addShapeless(<ore:cableGtSingleRedAlloy>.firstItem *2, [<ore:cableGtDoubleRedAlloy>]);
recipes.addShapeless(<ore:cableGtHexSilver>.firstItem, [<ore:cableGtOctalSilver>,<ore:cableGtOctalSilver>]);
recipes.addShapeless(<ore:cableGtOctalSilver>.firstItem, [<ore:cableGtQuadrupleSilver>,<ore:cableGtQuadrupleSilver>]);
recipes.addShapeless(<ore:cableGtQuadrupleSilver>.firstItem, [<ore:cableGtDoubleSilver>,<ore:cableGtDoubleSilver>]);
recipes.addShapeless(<ore:cableGtDoubleSilver>.firstItem, [<ore:cableGtSingleSilver>,<ore:cableGtSingleSilver>]);
recipes.addShapeless(<ore:cableGtOctalSilver>.firstItem *2, [<ore:cableGtHexSilver>]);
recipes.addShapeless(<ore:cableGtQuadrupleSilver>.firstItem *2, [<ore:cableGtOctalSilver>]);
recipes.addShapeless(<ore:cableGtDoubleSilver>.firstItem *2, [<ore:cableGtQuadrupleSilver>]);
recipes.addShapeless(<ore:cableGtSingleSilver>.firstItem *2, [<ore:cableGtDoubleSilver>]);
recipes.addShapeless(<ore:cableGtHexSolderingAlloy>.firstItem, [<ore:cableGtOctalSolderingAlloy>,<ore:cableGtOctalSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtOctalSolderingAlloy>.firstItem, [<ore:cableGtQuadrupleSolderingAlloy>,<ore:cableGtQuadrupleSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleSolderingAlloy>.firstItem, [<ore:cableGtDoubleSolderingAlloy>,<ore:cableGtDoubleSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleSolderingAlloy>.firstItem, [<ore:cableGtSingleSolderingAlloy>,<ore:cableGtSingleSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtOctalSolderingAlloy>.firstItem *2, [<ore:cableGtHexSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtQuadrupleSolderingAlloy>.firstItem *2, [<ore:cableGtOctalSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtDoubleSolderingAlloy>.firstItem *2, [<ore:cableGtQuadrupleSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtSingleSolderingAlloy>.firstItem *2, [<ore:cableGtDoubleSolderingAlloy>]);
recipes.addShapeless(<ore:cableGtHexSteel>.firstItem, [<ore:cableGtOctalSteel>,<ore:cableGtOctalSteel>]);
recipes.addShapeless(<ore:cableGtOctalSteel>.firstItem, [<ore:cableGtQuadrupleSteel>,<ore:cableGtQuadrupleSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleSteel>.firstItem, [<ore:cableGtDoubleSteel>,<ore:cableGtDoubleSteel>]);
recipes.addShapeless(<ore:cableGtDoubleSteel>.firstItem, [<ore:cableGtSingleSteel>,<ore:cableGtSingleSteel>]);
recipes.addShapeless(<ore:cableGtOctalSteel>.firstItem *2, [<ore:cableGtHexSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleSteel>.firstItem *2, [<ore:cableGtOctalSteel>]);
recipes.addShapeless(<ore:cableGtDoubleSteel>.firstItem *2, [<ore:cableGtQuadrupleSteel>]);
recipes.addShapeless(<ore:cableGtSingleSteel>.firstItem *2, [<ore:cableGtDoubleSteel>]);
recipes.addShapeless(<ore:cableGtHexSuperconductor>.firstItem, [<ore:cableGtOctalSuperconductor>,<ore:cableGtOctalSuperconductor>]);
recipes.addShapeless(<ore:cableGtOctalSuperconductor>.firstItem, [<ore:cableGtQuadrupleSuperconductor>,<ore:cableGtQuadrupleSuperconductor>]);
recipes.addShapeless(<ore:cableGtQuadrupleSuperconductor>.firstItem, [<ore:cableGtDoubleSuperconductor>,<ore:cableGtDoubleSuperconductor>]);
recipes.addShapeless(<ore:cableGtDoubleSuperconductor>.firstItem, [<ore:cableGtSingleSuperconductor>,<ore:cableGtSingleSuperconductor>]);
recipes.addShapeless(<ore:cableGtOctalSuperconductor>.firstItem *2, [<ore:cableGtHexSuperconductor>]);
recipes.addShapeless(<ore:cableGtQuadrupleSuperconductor>.firstItem *2, [<ore:cableGtOctalSuperconductor>]);
recipes.addShapeless(<ore:cableGtDoubleSuperconductor>.firstItem *2, [<ore:cableGtQuadrupleSuperconductor>]);
recipes.addShapeless(<ore:cableGtSingleSuperconductor>.firstItem *2, [<ore:cableGtDoubleSuperconductor>]);
recipes.addShapeless(<ore:cableGtHexTin>.firstItem, [<ore:cableGtOctalTin>,<ore:cableGtOctalTin>]);
recipes.addShapeless(<ore:cableGtOctalTin>.firstItem, [<ore:cableGtQuadrupleTin>,<ore:cableGtQuadrupleTin>]);
recipes.addShapeless(<ore:cableGtQuadrupleTin>.firstItem, [<ore:cableGtDoubleTin>,<ore:cableGtDoubleTin>]);
recipes.addShapeless(<ore:cableGtDoubleTin>.firstItem, [<ore:cableGtSingleTin>,<ore:cableGtSingleTin>]);
recipes.addShapeless(<ore:cableGtOctalTin>.firstItem *2, [<ore:cableGtHexTin>]);
recipes.addShapeless(<ore:cableGtQuadrupleTin>.firstItem *2, [<ore:cableGtOctalTin>]);
recipes.addShapeless(<ore:cableGtDoubleTin>.firstItem *2, [<ore:cableGtQuadrupleTin>]);
recipes.addShapeless(<ore:cableGtSingleTin>.firstItem *2, [<ore:cableGtDoubleTin>]);
recipes.addShapeless(<ore:cableGtHexTitanium>.firstItem, [<ore:cableGtOctalTitanium>,<ore:cableGtOctalTitanium>]);
recipes.addShapeless(<ore:cableGtOctalTitanium>.firstItem, [<ore:cableGtQuadrupleTitanium>,<ore:cableGtQuadrupleTitanium>]);
recipes.addShapeless(<ore:cableGtQuadrupleTitanium>.firstItem, [<ore:cableGtDoubleTitanium>,<ore:cableGtDoubleTitanium>]);
recipes.addShapeless(<ore:cableGtDoubleTitanium>.firstItem, [<ore:cableGtSingleTitanium>,<ore:cableGtSingleTitanium>]);
recipes.addShapeless(<ore:cableGtOctalTitanium>.firstItem *2, [<ore:cableGtHexTitanium>]);
recipes.addShapeless(<ore:cableGtQuadrupleTitanium>.firstItem *2, [<ore:cableGtOctalTitanium>]);
recipes.addShapeless(<ore:cableGtDoubleTitanium>.firstItem *2, [<ore:cableGtQuadrupleTitanium>]);
recipes.addShapeless(<ore:cableGtSingleTitanium>.firstItem *2, [<ore:cableGtDoubleTitanium>]);
recipes.addShapeless(<ore:cableGtHexTungsten>.firstItem, [<ore:cableGtOctalTungsten>,<ore:cableGtOctalTungsten>]);
recipes.addShapeless(<ore:cableGtOctalTungsten>.firstItem, [<ore:cableGtQuadrupleTungsten>,<ore:cableGtQuadrupleTungsten>]);
recipes.addShapeless(<ore:cableGtQuadrupleTungsten>.firstItem, [<ore:cableGtDoubleTungsten>,<ore:cableGtDoubleTungsten>]);
recipes.addShapeless(<ore:cableGtDoubleTungsten>.firstItem, [<ore:cableGtSingleTungsten>,<ore:cableGtSingleTungsten>]);
recipes.addShapeless(<ore:cableGtOctalTungsten>.firstItem *2, [<ore:cableGtHexTungsten>]);
recipes.addShapeless(<ore:cableGtQuadrupleTungsten>.firstItem *2, [<ore:cableGtOctalTungsten>]);
recipes.addShapeless(<ore:cableGtDoubleTungsten>.firstItem *2, [<ore:cableGtQuadrupleTungsten>]);
recipes.addShapeless(<ore:cableGtSingleTungsten>.firstItem *2, [<ore:cableGtDoubleTungsten>]);
recipes.addShapeless(<ore:cableGtHexTungstenSteel>.firstItem, [<ore:cableGtOctalTungstenSteel>,<ore:cableGtOctalTungstenSteel>]);
recipes.addShapeless(<ore:cableGtOctalTungstenSteel>.firstItem, [<ore:cableGtQuadrupleTungstenSteel>,<ore:cableGtQuadrupleTungstenSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleTungstenSteel>.firstItem, [<ore:cableGtDoubleTungstenSteel>,<ore:cableGtDoubleTungstenSteel>]);
recipes.addShapeless(<ore:cableGtDoubleTungstenSteel>.firstItem, [<ore:cableGtSingleTungstenSteel>,<ore:cableGtSingleTungstenSteel>]);
recipes.addShapeless(<ore:cableGtOctalTungstenSteel>.firstItem *2, [<ore:cableGtHexTungstenSteel>]);
recipes.addShapeless(<ore:cableGtQuadrupleTungstenSteel>.firstItem *2, [<ore:cableGtOctalTungstenSteel>]);
recipes.addShapeless(<ore:cableGtDoubleTungstenSteel>.firstItem *2, [<ore:cableGtQuadrupleTungstenSteel>]);
recipes.addShapeless(<ore:cableGtSingleTungstenSteel>.firstItem *2, [<ore:cableGtDoubleTungstenSteel>]);
recipes.addShapeless(<ore:cableGtHexVanadiumGallium>.firstItem, [<ore:cableGtOctalVanadiumGallium>,<ore:cableGtOctalVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtOctalVanadiumGallium>.firstItem, [<ore:cableGtQuadrupleVanadiumGallium>,<ore:cableGtQuadrupleVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtQuadrupleVanadiumGallium>.firstItem, [<ore:cableGtDoubleVanadiumGallium>,<ore:cableGtDoubleVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtDoubleVanadiumGallium>.firstItem, [<ore:cableGtSingleVanadiumGallium>,<ore:cableGtSingleVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtOctalVanadiumGallium>.firstItem *2, [<ore:cableGtHexVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtQuadrupleVanadiumGallium>.firstItem *2, [<ore:cableGtOctalVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtDoubleVanadiumGallium>.firstItem *2, [<ore:cableGtQuadrupleVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtSingleVanadiumGallium>.firstItem *2, [<ore:cableGtDoubleVanadiumGallium>]);
recipes.addShapeless(<ore:cableGtHexYttriumBariumCuprate>.firstItem, [<ore:cableGtOctalYttriumBariumCuprate>,<ore:cableGtOctalYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtOctalYttriumBariumCuprate>.firstItem, [<ore:cableGtQuadrupleYttriumBariumCuprate>,<ore:cableGtQuadrupleYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtQuadrupleYttriumBariumCuprate>.firstItem, [<ore:cableGtDoubleYttriumBariumCuprate>,<ore:cableGtDoubleYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtDoubleYttriumBariumCuprate>.firstItem, [<ore:cableGtSingleYttriumBariumCuprate>,<ore:cableGtSingleYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtOctalYttriumBariumCuprate>.firstItem *2, [<ore:cableGtHexYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtQuadrupleYttriumBariumCuprate>.firstItem *2, [<ore:cableGtOctalYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtDoubleYttriumBariumCuprate>.firstItem *2, [<ore:cableGtQuadrupleYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtSingleYttriumBariumCuprate>.firstItem *2, [<ore:cableGtDoubleYttriumBariumCuprate>]);
recipes.addShapeless(<ore:cableGtHexZinc>.firstItem, [<ore:cableGtOctalZinc>,<ore:cableGtOctalZinc>]);
recipes.addShapeless(<ore:cableGtOctalZinc>.firstItem, [<ore:cableGtQuadrupleZinc>,<ore:cableGtQuadrupleZinc>]);
recipes.addShapeless(<ore:cableGtQuadrupleZinc>.firstItem, [<ore:cableGtDoubleZinc>,<ore:cableGtDoubleZinc>]);
recipes.addShapeless(<ore:cableGtDoubleZinc>.firstItem, [<ore:cableGtSingleZinc>,<ore:cableGtSingleZinc>]);
recipes.addShapeless(<ore:cableGtOctalZinc>.firstItem *2, [<ore:cableGtHexZinc>]);
recipes.addShapeless(<ore:cableGtQuadrupleZinc>.firstItem *2, [<ore:cableGtOctalZinc>]);
recipes.addShapeless(<ore:cableGtDoubleZinc>.firstItem *2, [<ore:cableGtQuadrupleZinc>]);
recipes.addShapeless(<ore:cableGtSingleZinc>.firstItem *2, [<ore:cableGtDoubleZinc>]);
//Small Gear Via Extruder
recipes.addShaped(<contenttweaker:smallgearextrudershape>, [
[<metaitem:shape.empty>,null,null],
[null,<gregtech:meta_tool:13>,null],
[null,null,null]]);
extruder.recipeBuilder().inputs([<ore:ingotSteel>]).notConsumable(<contenttweaker:smallgearextrudershape>).outputs([<ore:gearSmallSteel>.firstItem]).duration(130).EUt(64).buildAndRegister();
//steel small gear
extruder.recipeBuilder().inputs([<ore:ingotAluminium>]).notConsumable(<contenttweaker:smallgearextrudershape>).outputs([<ore:gearSmallAluminium>.firstItem]).duration(130).EUt(64).buildAndRegister();
//aluminium small gear
extruder.recipeBuilder().inputs([<ore:ingotStainlessSteel>]).notConsumable(<contenttweaker:smallgearextrudershape>).outputs([<ore:gearSmallStainlessSteel>.firstItem]).duration(130).EUt(64).buildAndRegister();
//stainless steel small gear
extruder.recipeBuilder().inputs([<ore:ingotTitanium>]).notConsumable(<contenttweaker:smallgearextrudershape>).outputs([<ore:gearSmallTitanium>.firstItem]).duration(130).EUt(64).buildAndRegister();
//titanium small gear
extruder.recipeBuilder().inputs([<ore:ingotTungstenSteel>]).notConsumable(<contenttweaker:smallgearextrudershape>).outputs([<ore:gearSmallTungstenSteel>.firstItem]).duration(130).EUt(64).buildAndRegister(); //tungstensteel small gear
#Custom hot ingot handling with cryotheum
var hotIngotMap as IOreDictEntry[IOreDictEntry] = {
<ore:ingotHotErbium>:<ore:ingotErbium>,
<ore:ingotHotBlackBronze>:<ore:ingotBlackBronze>,
<ore:ingotHotNaquadahEnriched>:<ore:ingotNaquadahEnriched>,
<ore:ingotHotNaquadahAlloy>:<ore:ingotNaquadahAlloy>,
<ore:ingotHotYttriumBariumCuprate>:<ore:ingotYttriumBariumCuprate>,
<ore:ingotHotOsmiridium>:<ore:ingotOsmiridium>,
<ore:ingotHotYttrium>:<ore:ingotYttrium>,
<ore:ingotHotVanadiumGallium>:<ore:ingotVanadiumGallium>,
<ore:ingotHotVanadium>:<ore:ingotVanadium>,
<ore:ingotHotUltimet>:<ore:ingotUltimet>,
<ore:ingotHotTungstenSteel>:<ore:ingotTungstenSteel>,
<ore:ingotHotHssg>:<ore:ingotHssg>,
<ore:ingotHotHsse>:<ore:ingotHsse>,
<ore:ingotHotScandium>:<ore:ingotScandium>,
<ore:ingotHotHsss>:<ore:ingotHsss>,
<ore:ingotHotNiobiumTitanium>:<ore:ingotNiobiumTitanium>,
<ore:ingotHotNiobiumNitride>:<ore:ingotNiobiumNitride>,
<ore:ingotHotLutetium>:<ore:ingotLutetium>,
<ore:ingotHotIridium>:<ore:ingotIridium>,
<ore:ingotHotKanthal>:<ore:ingotKanthal>,
<ore:ingotHotNaquadah>:<ore:ingotNaquadah>,
<ore:ingotHotNaquadria>:<ore:ingotNaquadria>,
<ore:ingotHotTungsten>:<ore:ingotTungsten>,
<ore:ingotHotThulium>:<ore:ingotThulium>,
<ore:ingotHotTitanium>:<ore:ingotTitanium>,
<ore:ingotHotNichrome>:<ore:ingotNichrome>,
<ore:ingotHotTungstenCarbide>:<ore:ingotTungstenCarbide>,
<ore:ingotHotNiobium>:<ore:ingotNiobium>
};
for hotIngot, ingot in hotIngotMap {
mods.thermalexpansion.Transposer.addFillRecipe(ingot.firstItem, hotIngot.firstItem, <liquid:cryotheum> * 10, 10000) ;
}
//Manual non oredict entries
mods.thermalexpansion.Transposer.addFillRecipe(<gregtech:meta_item_1:10800>, <ore:ingotHotEnderium>.firstItem, <liquid:cryotheum> * 10, 10000) ;
mods.thermalexpansion.Transposer.addFillRecipe(<gregtech:meta_item_1:10047>, <ore:ingotHotOsmium>.firstItem, <liquid:cryotheum> * 10, 10000) ;
#retiering field generators
recipes.remove(<metaitem:field.generator.lv>);
recipes.remove(<metaitem:field.generator.mv>);
recipes.remove(<metaitem:field.generator.hv>);
#LV field generator
assembler.recipeBuilder()
.inputs(<ore:circuitLow>*4, <ore:dustEnderPearl>, <ore:wireGtSingleBluesteel>*4)
.outputs(<metaitem:field.generator.lv>)
.duration(1800)
.EUt(30)
.buildAndRegister();
#MV field generator
assembler.recipeBuilder()
.inputs(<ore:circuitGood>*4, <ore:dustEnderEye>, <ore:wireGtDoubleSignalum>*4)
.outputs(<metaitem:field.generator.mv>)
.duration(1800)
.EUt(120)
.buildAndRegister();
#HV field generator
assembler.recipeBuilder()
.inputs(<ore:circuitLow>*4, <metaitem:quantumeye>, <ore:wireGtQuadrupleEnderium>*4)
.outputs(<metaitem:field.generator.hv>)
.duration(1800)
.EUt(480)
.buildAndRegister();
#Magic energy absorber moved to EV Tier
recipes.remove(<gregtech:machine:493>);
recipes.addShaped(<gregtech:machine:493>, [[<gregtech:meta_item_1:32613>, <gregtech:meta_item_1:32673>, <gregtech:meta_item_1:32613>],[<gregtech:meta_item_1:32692>, <gregtech:machine:504>, <gregtech:meta_item_1:32692>], [<gregtech:meta_item_1:32613>, <gregtech:meta_item_1:32673>, <gregtech:meta_item_1:32613>]]);
print("----------------Gregtech End-------------------");
| 0 | 0.870184 | 1 | 0.870184 | game-dev | MEDIA | 0.99062 | game-dev | 0.829194 | 1 | 0.829194 |
MadDeCoDeR/Classic-RBDOOM-3-BFG | 8,102 | neo/idlib/math/Vector.cpp | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "precompiled.h"
idVec2 vec2_origin( 0.0f, 0.0f );
idVec3 vec3_origin( 0.0f, 0.0f, 0.0f );
idVec4 vec4_origin( 0.0f, 0.0f, 0.0f, 0.0f );
idVec5 vec5_origin( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f );
idVec6 vec6_origin( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f );
idVec6 vec6_infinity( idMath::INFINITY, idMath::INFINITY, idMath::INFINITY, idMath::INFINITY, idMath::INFINITY, idMath::INFINITY );
//===============================================================
//
// idVec2
//
//===============================================================
/*
=============
idVec2::ToString
=============
*/
const char* idVec2::ToString( int precision ) const
{
return idStr::FloatArrayToString( ToFloatPtr(), GetDimension(), precision );
}
/*
=============
Lerp
Linearly inperpolates one vector to another.
=============
*/
void idVec2::Lerp( const idVec2& v1, const idVec2& v2, const float l )
{
if( l <= 0.0f )
{
( *this ) = v1;
}
else if( l >= 1.0f )
{
( *this ) = v2;
}
else
{
( *this ) = v1 + l * ( v2 - v1 );
}
}
//===============================================================
//
// idVec3
//
//===============================================================
/*
=============
idVec3::ToYaw
=============
*/
float idVec3::ToYaw() const
{
float yaw;
if( ( y == 0.0f ) && ( x == 0.0f ) )
{
yaw = 0.0f;
}
else
{
yaw = RAD2DEG( atan2( y, x ) );
if( yaw < 0.0f )
{
yaw += 360.0f;
}
}
return yaw;
}
/*
=============
idVec3::ToPitch
=============
*/
float idVec3::ToPitch() const
{
float forward;
float pitch;
if( ( x == 0.0f ) && ( y == 0.0f ) )
{
if( z > 0.0f )
{
pitch = 90.0f;
}
else
{
pitch = 270.0f;
}
}
else
{
forward = ( float )idMath::Sqrt( x * x + y * y );
pitch = RAD2DEG( atan2( z, forward ) );
if( pitch < 0.0f )
{
pitch += 360.0f;
}
}
return pitch;
}
/*
=============
idVec3::ToAngles
=============
*/
idAngles idVec3::ToAngles() const
{
float forward;
float yaw;
float pitch;
if( ( x == 0.0f ) && ( y == 0.0f ) )
{
yaw = 0.0f;
if( z > 0.0f )
{
pitch = 90.0f;
}
else
{
pitch = 270.0f;
}
}
else
{
yaw = RAD2DEG( atan2( y, x ) );
if( yaw < 0.0f )
{
yaw += 360.0f;
}
forward = ( float )idMath::Sqrt( x * x + y * y );
pitch = RAD2DEG( atan2( z, forward ) );
if( pitch < 0.0f )
{
pitch += 360.0f;
}
}
return idAngles( -pitch, yaw, 0.0f );
}
/*
=============
idVec3::ToPolar
=============
*/
idPolar3 idVec3::ToPolar() const
{
float forward;
float yaw;
float pitch;
if( ( x == 0.0f ) && ( y == 0.0f ) )
{
yaw = 0.0f;
if( z > 0.0f )
{
pitch = 90.0f;
}
else
{
pitch = 270.0f;
}
}
else
{
yaw = RAD2DEG( atan2( y, x ) );
if( yaw < 0.0f )
{
yaw += 360.0f;
}
forward = ( float )idMath::Sqrt( x * x + y * y );
pitch = RAD2DEG( atan2( z, forward ) );
if( pitch < 0.0f )
{
pitch += 360.0f;
}
}
return idPolar3( idMath::Sqrt( x * x + y * y + z * z ), yaw, -pitch );
}
/*
=============
idVec3::ToMat3
=============
*/
idMat3 idVec3::ToMat3() const
{
idMat3 mat;
float d;
mat[0] = *this;
d = x * x + y * y;
if( !d )
{
mat[1][0] = 1.0f;
mat[1][1] = 0.0f;
mat[1][2] = 0.0f;
}
else
{
d = idMath::InvSqrt( d );
mat[1][0] = -y * d;
mat[1][1] = x * d;
mat[1][2] = 0.0f;
}
mat[2] = Cross( mat[1] );
return mat;
}
/*
=============
idVec3::ToString
=============
*/
const char* idVec3::ToString( int precision ) const
{
return idStr::FloatArrayToString( ToFloatPtr(), GetDimension(), precision );
}
/*
=============
Lerp
Linearly inperpolates one vector to another.
=============
*/
void idVec3::Lerp( const idVec3& v1, const idVec3& v2, const float l )
{
if( l <= 0.0f )
{
( *this ) = v1;
}
else if( l >= 1.0f )
{
( *this ) = v2;
}
else
{
( *this ) = v1 + l * ( v2 - v1 );
}
}
/*
=============
SLerp
Spherical linear interpolation from v1 to v2.
Vectors are expected to be normalized.
=============
*/
#define LERP_DELTA 1e-6
void idVec3::SLerp( const idVec3& v1, const idVec3& v2, const float t )
{
float omega, cosom, sinom, scale0, scale1;
if( t <= 0.0f )
{
( *this ) = v1;
return;
}
else if( t >= 1.0f )
{
( *this ) = v2;
return;
}
cosom = v1 * v2;
if( ( 1.0f - cosom ) > LERP_DELTA )
{
omega = acos( cosom );
sinom = sin( omega );
scale0 = sin( ( 1.0f - t ) * omega ) / sinom;
scale1 = sin( t * omega ) / sinom;
}
else
{
scale0 = 1.0f - t;
scale1 = t;
}
( *this ) = ( v1 * scale0 + v2 * scale1 );
}
/*
=============
ProjectSelfOntoSphere
Projects the z component onto a sphere.
=============
*/
void idVec3::ProjectSelfOntoSphere( const float radius )
{
float rsqr = radius * radius;
float len = Length();
if( len < rsqr * 0.5f )
{
z = sqrt( rsqr - len );
}
else
{
z = rsqr / ( 2.0f * sqrt( len ) );
}
}
//===============================================================
//
// idVec4
//
//===============================================================
/*
=============
idVec4::ToString
=============
*/
const char* idVec4::ToString( int precision ) const
{
return idStr::FloatArrayToString( ToFloatPtr(), GetDimension(), precision );
}
/*
=============
Lerp
Linearly inperpolates one vector to another.
=============
*/
void idVec4::Lerp( const idVec4& v1, const idVec4& v2, const float l )
{
if( l <= 0.0f )
{
( *this ) = v1;
}
else if( l >= 1.0f )
{
( *this ) = v2;
}
else
{
( *this ) = v1 + l * ( v2 - v1 );
}
}
//===============================================================
//
// idVec5
//
//===============================================================
/*
=============
idVec5::ToString
=============
*/
const char* idVec5::ToString( int precision ) const
{
return idStr::FloatArrayToString( ToFloatPtr(), GetDimension(), precision );
}
/*
=============
idVec5::Lerp
=============
*/
void idVec5::Lerp( const idVec5& v1, const idVec5& v2, const float l )
{
if( l <= 0.0f )
{
( *this ) = v1;
}
else if( l >= 1.0f )
{
( *this ) = v2;
}
else
{
x = v1.x + l * ( v2.x - v1.x );
y = v1.y + l * ( v2.y - v1.y );
z = v1.z + l * ( v2.z - v1.z );
s = v1.s + l * ( v2.s - v1.s );
t = v1.t + l * ( v2.t - v1.t );
}
}
//===============================================================
//
// idVec6
//
//===============================================================
/*
=============
idVec6::ToString
=============
*/
const char* idVec6::ToString( int precision ) const
{
return idStr::FloatArrayToString( ToFloatPtr(), GetDimension(), precision );
}
| 0 | 0.863525 | 1 | 0.863525 | game-dev | MEDIA | 0.741788 | game-dev | 0.900801 | 1 | 0.900801 |
CraftJarvis/JARVIS-1 | 5,943 | jarvis/stark_tech/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/RewardForItemBase.java | // --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------
package com.microsoft.Malmo.MissionHandlers;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import com.microsoft.Malmo.MalmoMod;
import com.microsoft.Malmo.MalmoMod.MalmoMessageType;
import com.microsoft.Malmo.Schemas.BlockOrItemSpec;
import com.microsoft.Malmo.Schemas.BlockOrItemSpecWithReward;
import com.microsoft.Malmo.Schemas.DrawItem;
import com.microsoft.Malmo.Schemas.Variation;
import com.microsoft.Malmo.Utils.MinecraftTypeHelper;
public abstract class RewardForItemBase extends RewardBase
{
List<ItemRewardMatcher> rewardMatchers = new ArrayList<ItemRewardMatcher>();
public static class ItemMatcher
{
List<String> allowedItemTypes = new ArrayList<String>();
BlockOrItemSpec matchSpec;
ItemMatcher(BlockOrItemSpec spec)
{
this.matchSpec = spec;
for (String itemType : spec.getType())
{
Item item = MinecraftTypeHelper.ParseItemType(itemType, true);
if (item != null)
this.allowedItemTypes.add(item.getUnlocalizedName());
}
}
boolean matches(ItemStack stack)
{
String item = stack.getItem().getUnlocalizedName();
if (item.equals("log") || item.equals("log2")){
if (!this.allowedItemTypes.contains("log") && !this.allowedItemTypes.contains("log2"))
return false;
}
else if (!this.allowedItemTypes.contains(item))
return false;
// Our item type matches, but we may need to compare block attributes too:
DrawItem di = MinecraftTypeHelper.getDrawItemFromItemStack(stack);
if (this.matchSpec.getColour() != null && !this.matchSpec.getColour().isEmpty()) // We have a colour list, so check colour matches:
{
if (di.getColour() == null)
return false; // The item we are matching against has no colour attribute.
if (!this.matchSpec.getColour().contains(di.getColour()))
return false; // The item we are matching against is the wrong colour.
}
if (this.matchSpec.getVariant() != null && !this.matchSpec.getVariant().isEmpty()) // We have a variant list, so check variant matches@:
{
if (di.getVariant() == null)
return false; // The item we are matching against has no variant attribute.
for (Variation v : this.matchSpec.getVariant())
{
if (v.getValue().equals(di.getVariant().getValue()))
return true;
}
return false; // The item we are matching against is the wrong variant.
}
return true;
}
}
public class ItemRewardMatcher extends ItemMatcher
{
float reward;
String distribution;
ItemRewardMatcher(BlockOrItemSpecWithReward spec)
{
super(spec);
this.reward = spec.getReward().floatValue();
this.distribution = spec.getDistribution();
}
float reward()
{
return this.reward;
}
String distribution()
{
return this.distribution;
}
}
protected void addItemSpecToRewardStructure(BlockOrItemSpecWithReward is)
{
this.rewardMatchers.add(new ItemRewardMatcher(is));
}
protected void accumulateReward(int dimension, ItemStack stack)
{
for (ItemRewardMatcher matcher : this.rewardMatchers)
{
if (matcher.matches(stack))
{
addAndShareCachedReward(dimension, stack.getCount() * matcher.reward(), matcher.distribution());
}
}
}
protected static void sendItemStackToClient(EntityPlayerMP player, MalmoMessageType message, ItemStack is)
{
ByteBuf buf = Unpooled.buffer();
ByteBufUtils.writeItemStack(buf, is);
byte[] bytes = new byte[buf.readableBytes()];
buf.getBytes(0, bytes);
String data = DatatypeConverter.printBase64Binary(bytes);
MalmoMod.MalmoMessage msg = new MalmoMod.MalmoMessage(message, data);
MalmoMod.network.sendTo(msg, player);
}
}
| 0 | 0.803921 | 1 | 0.803921 | game-dev | MEDIA | 0.775733 | game-dev | 0.901423 | 1 | 0.901423 |
age-series/ElectricalAge | 7,863 | src/main/java/mods/eln/sixnode/lampsocket/LampSocketRender.java | package mods.eln.sixnode.lampsocket;
import mods.eln.cable.CableRenderDescriptor;
import mods.eln.item.LampDescriptor;
import mods.eln.item.LampDescriptor.Type;
import mods.eln.misc.*;
import mods.eln.node.six.SixNodeDescriptor;
import mods.eln.node.six.SixNodeElementInventory;
import mods.eln.node.six.SixNodeElementRender;
import mods.eln.node.six.SixNodeEntity;
import mods.eln.sixnode.electricalcable.ElectricalCableDescriptor;
import mods.eln.sound.SoundCommand;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.world.EnumSkyBlock;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class LampSocketRender extends SixNodeElementRender {
LampSocketDescriptor lampSocketDescriptor = null;
LampSocketDescriptor descriptor;
SixNodeElementInventory inventory = new SixNodeElementInventory(2, 64, this);
boolean grounded = true;
public boolean poweredByLampSupply;
float pertuVy = 0, pertuPy = 0;
float pertuVz = 0, pertuPz = 0;
float weatherAlphaZ = 0, weatherAlphaY = 0;
List entityList = new ArrayList();
float entityTimout = 0;
public String channel;
LampDescriptor lampDescriptor = null;
float alphaZ;
byte light, oldLight = -1;
int paintColor = 15;
public boolean isConnectedToLampSupply;
ElectricalCableDescriptor cable;
public LampSocketRender(SixNodeEntity tileEntity, Direction side, SixNodeDescriptor descriptor) {
super(tileEntity, side, descriptor);
this.descriptor = (LampSocketDescriptor) descriptor;
lampSocketDescriptor = (LampSocketDescriptor) descriptor;
}
@Nullable
@Override
public GuiScreen newGuiDraw(@NotNull Direction side, @NotNull EntityPlayer player) {
return new LampSocketGuiDraw(player, inventory, this);
}
@Override
public IInventory getInventory() {
return inventory;
}
@Override
public void draw() {
super.draw(); //Colored cable only
GL11.glRotatef(descriptor.initialRotateDeg, 1.f, 0.f, 0.f);
descriptor.render.draw(this, UtilsClient.distanceFromClientPlayer(this.getTileEntity()));
}
@Override
public void refresh(float deltaT) {
if (descriptor.render instanceof LampSocketSuspendedObjRender) {
float dt = deltaT;
entityTimout -= dt;
if (entityTimout < 0) {
entityList = getTileEntity().getWorldObj().getEntitiesWithinAABB(Entity.class, new Coordinate(getTileEntity().xCoord, getTileEntity().yCoord - 2, getTileEntity().zCoord, getTileEntity().getWorldObj()).getAxisAlignedBB(2));
entityTimout = 0.1f;
}
for (Object o : entityList) {
Entity e = (Entity) o;
float eFactor = 0;
if (e instanceof EntityArrow)
eFactor = 1f;
if (e instanceof EntityLivingBase)
eFactor = 4f;
if (eFactor == 0)
continue;
pertuVz += e.motionX * eFactor * dt;
pertuVy += e.motionZ * eFactor * dt;
}
if (getTileEntity().getWorldObj().getSavedLightValue(EnumSkyBlock.Sky, getTileEntity().xCoord, getTileEntity().yCoord, getTileEntity().zCoord) > 3) {
float weather = (float) UtilsClient.getWeather(getTileEntity().getWorldObj()) * 0.9f + 0.1f;
// TODO: Reduce swinging of lamps to some degree?
weatherAlphaY += (0.4 - Math.random()) * dt * Math.PI / 0.2 * weather;
weatherAlphaZ += (0.4 - Math.random()) * dt * Math.PI / 0.2 * weather;
if (weatherAlphaY > 2 * Math.PI)
weatherAlphaY -= 2 * Math.PI;
if (weatherAlphaZ > 2 * Math.PI)
weatherAlphaZ -= 2 * Math.PI;
pertuVy += Math.random() * Math.sin(weatherAlphaY) * weather * weather * dt * 3;
pertuVz += Math.random() * Math.cos(weatherAlphaY) * weather * weather * dt * 3;
pertuVy += 0.4 * dt * weather * Math.signum(pertuVy) * Math.random();
pertuVz += 0.4 * dt * weather * Math.signum(pertuVz) * Math.random();
}
pertuVy -= pertuPy / 10 * dt;
pertuVy *= (1 - 0.2 * dt);
pertuPy += pertuVy;
pertuVz -= pertuPz / 10 * dt;
pertuVz *= (1 - 0.2 * dt);
pertuPz += pertuVz;
}
}
void setLight(byte newLight) {
light = newLight;
if (lampDescriptor != null && lampDescriptor.type == Type.ECO && oldLight != -1 && oldLight < 9 && light >= 9) {
float rand = (float) Math.random();
if (rand > 0.1f)
play(new SoundCommand("eln:neon_lamp").mulVolume(0.7f, 1.0f + (rand / 6.0f)).smallRange());
else
play(new SoundCommand("eln:NEON_LFNOISE").mulVolume(0.2f, 1f).verySmallRange());
}
oldLight = light;
}
@Override
public void publishUnserialize(DataInputStream stream) {
super.publishUnserialize(stream);
try {
Byte b;
b = stream.readByte();
grounded = (b & (1 << 6)) != 0;
ItemStack lampStack = Utils.unserialiseItemStack(stream);
lampDescriptor = (LampDescriptor) Utils.getItemObject(lampStack);
alphaZ = stream.readFloat();
ItemStack itemStack = Utils.unserialiseItemStack(stream);
if (itemStack != null ) {
cable = (ElectricalCableDescriptor) ElectricalCableDescriptor.getDescriptor(itemStack, ElectricalCableDescriptor.class);
}
poweredByLampSupply = stream.readBoolean();
channel = stream.readUTF();
isConnectedToLampSupply = stream.readBoolean();
setLight(stream.readByte());
paintColor = stream.readByte();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void serverPacketUnserialize(DataInputStream stream) throws IOException {
super.serverPacketUnserialize(stream);
setLight(stream.readByte());
}
public boolean getGrounded() {
return grounded;
}
public void setGrounded(boolean grounded) {
this.grounded = grounded;
}
@Nullable
@Override
public CableRenderDescriptor getCableRender(@NotNull LRDU lrdu) {
if (cable == null
|| (lrdu == front && !descriptor.cableFront)
|| (lrdu == front.left() && !descriptor.cableLeft)
|| (lrdu == front.right() && !descriptor.cableRight)
|| (lrdu == front.inverse() && !descriptor.cableBack))
return null;
return cable.render;
}
public void clientSetGrounded(boolean value) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream stream = new DataOutputStream(bos);
preparePacketForServer(stream);
stream.writeByte(LampSocketElement.setGroundedId);
stream.writeByte(value ? 1 : 0);
sendPacketToServer(bos);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean cameraDrawOptimisation() {
return descriptor.cameraOpt;
}
}
| 0 | 0.896206 | 1 | 0.896206 | game-dev | MEDIA | 0.801231 | game-dev,graphics-rendering | 0.979156 | 1 | 0.979156 |
SPC-Some-Polish-Coders/PopHead | 14,006 | src/ECS/Systems/debugVisualization.cpp | #include "pch.hpp"
#include "debugVisualization.hpp"
#include "ECS/Components/physicsComponents.hpp"
#include "ECS/Components/objectsComponents.hpp"
#include "ECS/Components/graphicsComponents.hpp"
#include "ECS/Components/debugComponents.hpp"
#include "ECS/Components/charactersComponents.hpp"
#include "ECS/entityUtil.hpp"
#include "platforms.hpp"
#include "Renderer/renderer.hpp"
extern bool debugWindowOpen;
namespace ph::system {
static bool
enableDebugVisualization = true,
collision,
velocityChangingArea,
pushingArea,
lightWalls,
indoorOutdoorBlend,
collisionDenialAreas,
lightWallDenialAreas,
collisionAndLightWallDenialAreas,
hintArea, hintAreaDetail = true,
cameraRoom, cameraRoomCenter = true,
puzzleGridRoads, puzzleGridRoadsPos = true, puzzleGridRoadsChunks,
pits, pitChunks,
movingPlatformBodies, onPlatformCircles,
movingPlatformPathBodies,
tileBounds,
mapChunkBounds,
spatialPartitionBounds, simRegion;
using namespace component;
void DebugVisualization::update(float dt)
{
PH_PROFILE_FUNCTION();
if(debugWindowOpen && ImGui::BeginTabItem("debug visualization"))
{
ImGui::Columns(2);
ImGui::Checkbox("enable debug visualization", &enableDebugVisualization);
ImGui::Checkbox("collisions", &collision);
ImGui::Checkbox("velocity changing areas", &velocityChangingArea);
ImGui::Checkbox("pushing areas", &pushingArea);
ImGui::Checkbox("light walls", &lightWalls);
ImGui::Checkbox("indoor outdoor blend areas", &indoorOutdoorBlend);
ImGui::Checkbox("collision denial areas", &collisionDenialAreas);
ImGui::Checkbox("light wall denial areas", &lightWallDenialAreas);
ImGui::Checkbox("collision and light wall denial areas", &collisionAndLightWallDenialAreas);
ImGui::NextColumn();
ImGui::Checkbox("hint area", &hintArea);
if(hintArea)
ImGui::Checkbox("hint area detail", &hintAreaDetail);
ImGui::Checkbox("camera room", &cameraRoom);
if(cameraRoom)
ImGui::Checkbox("camera room center", &cameraRoomCenter);
ImGui::Checkbox("puzzle grid roads", &puzzleGridRoads);
if(puzzleGridRoads)
{
ImGui::Checkbox("puzzle grid roads pos", &puzzleGridRoadsPos);
ImGui::Checkbox("puzzle grid roads chunks", &puzzleGridRoadsChunks);
}
ImGui::Checkbox("pits", &pits);
if(pits)
ImGui::Checkbox("pit chunks", &pitChunks);
ImGui::Checkbox("moving platform bodies", &movingPlatformBodies);
if(movingPlatformBodies)
ImGui::Checkbox("on platform circles", &onPlatformCircles);
ImGui::Checkbox("moving platform path bodies", &movingPlatformPathBodies);
ImGui::Checkbox("tile bounds", &tileBounds);
ImGui::Checkbox("map chunk bounds", &mapChunkBounds);
ImGui::Checkbox("spatial partition bounds", &spatialPartitionBounds);
if(spatialPartitionBounds)
ImGui::Checkbox("sim region", &simRegion);
ImGui::Columns(1);
ImGui::EndTabItem();
}
if(!enableDebugVisualization) return;
if(collision)
{
// render static collision bodies as dark red rectangle
mRegistry.view<StaticCollisionBody, BodyRect>(entt::exclude<BodyCircle>).each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(130, 0, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
// render multi static collision bodies as bright red rectangle or bright red circles
mRegistry.view<MultiStaticCollisionBody>().each([]
(const auto& multiCollisionBody)
{
for(auto& bodyRect : multiCollisionBody.rects)
{
Renderer::submitQuad(Null, Null, &sf::Color(255, 0, 0, 140), Null,
bodyRect, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
for(auto& circle : multiCollisionBody.circles)
{
Renderer::submitCircle(sf::Color(255, 0, 0, 140), circle.offset - Vec2(circle.radius),
circle.radius, 50, ProjectionType::gameWorld, false);
}
});
// render kinematic bodies as blue rectangle
mRegistry.view<KinematicCollisionBody, BodyRect>(entt::exclude<BodyCircle>).each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(45, 100, 150, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
// render static circle bodies as dark red circle
mRegistry.view<StaticCollisionBody, BodyRect, BodyCircle>().each([]
(auto, const auto& rect, const auto& circle)
{
Renderer::submitQuad(Null, Null, &sf::Color(130, 0, 0, 140), Null,
rect, 50, 0.f, {}, ProjectionType::gameWorld, false);
Renderer::submitCircle(sf::Color(130, 0, 0, 200), rect.pos + circle.offset - Vec2(circle.radius),
circle.radius, 50, ProjectionType::gameWorld, false);
});
// render kinematic circle bodies as blue circle
mRegistry.view<KinematicCollisionBody, BodyRect, BodyCircle>().each([]
(auto, const auto& rect, const auto& circle)
{
Renderer::submitQuad(Null, Null, &sf::Color(45, 100, 150, 40), Null,
rect, 50, 0.f, {}, ProjectionType::gameWorld, false);
Renderer::submitCircle(sf::Color(45, 100, 150, 140), rect.pos + circle.offset - Vec2(circle.radius),
circle.radius, 50, ProjectionType::gameWorld, false);
});
}
if(velocityChangingArea)
{
// render velocity changing areas as orange rectangle
mRegistry.view<AreaVelocityChangingEffect, BodyRect>().each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(255, 165, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
}
if(pushingArea)
{
// render pushing areas as yellow rectangle
mRegistry.view<PushingArea, BodyRect>().each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(255, 255, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
}
if(lightWalls)
{
// render light walls as blue rectangle
mRegistry.view<LightWall, BodyRect>().each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(40, 40, 225, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
// render chunk light walls as light blue rectangle
mRegistry.view<RenderChunk>().each([]
(const auto& chunk)
{
for(const auto wall : chunk.lightWalls)
{
Renderer::submitQuad(Null, Null, &sf::Color(60, 60, 255, 140), Null,
wall, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
});
}
if(indoorOutdoorBlend)
{
// render indoor outdoor blend areas as orange rectangle
mRegistry.view<IndoorOutdoorBlendArea, BodyRect>().each([]
(auto, const auto& body)
{
Renderer::submitQuad(Null, Null, &sf::Color(255, 165, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
}
if(collisionDenialAreas || lightWallDenialAreas || collisionAndLightWallDenialAreas)
{
// denial areas debug
mRegistry.view<DenialArea, BodyRect>().each([]
(auto denial, const auto& body)
{
if(denial.type == DenialArea::Collision && collisionDenialAreas)
{
// render collision denial areas as dark red rectangle
Renderer::submitQuad(Null, Null, &sf::Color(150, 10, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
else if(denial.type == DenialArea::LightWall && lightWallDenialAreas)
{
// render collision denial areas as dark yellow rectangle
Renderer::submitQuad(Null, Null, &sf::Color(100, 100, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
else if(denial.type == DenialArea::All && collisionAndLightWallDenialAreas)
{
// render collision and light wall denial areas as dark red rectangle
Renderer::submitQuad(Null, Null, &sf::Color(50, 20, 20, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
});
}
if(hintArea)
{
mRegistry.view<Hint, BodyRect>().each([]
(const auto& hint, const auto& body)
{
// render hint area as lime green rectangle
Renderer::submitQuad(Null, Null, &sf::Color(192, 255, 0, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
if(hintAreaDetail)
{
auto pos = body.pos;
std::string debugText = "hintName: ";
debugText += hint.hintName;
Renderer::submitText(debugText.c_str(), "LiberationMono-Bold.ttf", pos, 10, sf::Color::Black,
45, ProjectionType::gameWorld, false);
pos.y += 10.f;
debugText = "keyboard content: ";
debugText += hint.keyboardContent;
Renderer::submitText(debugText.c_str(), "LiberationMono-Bold.ttf", pos, 10, sf::Color::Black,
45, ProjectionType::gameWorld, false);
pos.y += 10.f;
debugText = "joystick content: ";
debugText += hint.joystickContent;
Renderer::submitText(debugText.c_str(), "LiberationMono-Bold.ttf", pos, 10, sf::Color::Black,
45, ProjectionType::gameWorld, false);
}
});
}
if(cameraRoom)
{
mRegistry.view<CameraRoom, BodyRect>().each([&]
(auto camRoom, const auto& body)
{
// render camera rooms as violet rectangle
Renderer::submitQuad(Null, Null, &sf::Color(130, 0, 150, 140), Null,
body, 50, 0.f, {}, ProjectionType::gameWorld, false);
if(cameraRoomCenter)
{
FloatRect centerArea = body;
centerArea.x += camRoom.edgeAreaSize * body.w;
centerArea.y += camRoom.edgeAreaSize * body.h;
centerArea.w -= camRoom.edgeAreaSize * body.w * 2.f;
centerArea.h -= camRoom.edgeAreaSize * body.h * 2.f;
Renderer::submitQuad(Null, Null, &sf::Color(255, 0, 0, 140), Null,
centerArea, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
});
}
if(puzzleGridRoads)
{
mRegistry.view<PuzzleGridRoadChunk, PuzzleGridPos>().each([&]
(auto entity, const auto& roadChunk, auto chunkRelativeGridPos)
{
for(i32 y = 0; y < 12; ++y)
{
for(i32 x = 0; x < 12; ++x)
{
if(roadChunk.tiles[y][x])
{
// render road tile as green rectangle
auto gridPos = Cast<Vec2>(chunkRelativeGridPos + Vec2i(x, y));
auto worldPos = gridPos * 16.f;
Renderer::submitQuad(Null, Null, &sf::Color(0, 200, 0, 140), Null,
worldPos, {16.f, 16.f}, 50, 0.f, {}, ProjectionType::gameWorld, false);
if(puzzleGridRoadsPos)
{
// render puzzle grid pos, x up, y down
char posText[50];
sprintf(posText, "%i", Cast<i32>(gridPos.x));
Renderer::submitTextWorldHD(posText, "LiberationMono-Bold.ttf", worldPos, 6, sf::Color::Black, 45);
sprintf(posText, "%i", Cast<i32>(gridPos.y));
worldPos.y += 4.f;
Renderer::submitTextWorldHD(posText, "LiberationMono-Bold.ttf", worldPos, 6, sf::Color::Black, 45);
}
if(puzzleGridRoadsChunks)
{
// render puzzle grid road chukns as rectangles with random color
if(auto* body = mRegistry.try_get<BodyRect>(entity))
{
auto color = mRegistry.get<DebugColor>(entity);
Renderer::submitQuad(Null, Null, &color, Null,
*body, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
}
}
}
}
});
}
if(pits)
{
mRegistry.view<PitChunk, BodyRect>().each([&]
(auto entity, const auto& pitChunk, auto chunkBody)
{
for(auto pit : pitChunk.pits)
{
// render pit as dark purple rectangle
Renderer::submitQuad(Null, Null, &sf::Color(100, 0, 100, 50), Null,
pit, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
if(pitChunks)
{
// render pit chunk as rectangle with random color
if(auto* color = mRegistry.try_get<DebugColor>(entity))
{
Renderer::submitQuad(Null, Null, color, Null,
chunkBody, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
}
});
}
if(movingPlatformBodies)
{
mRegistry.view<MovingPlatform, BodyRect>().each([&]
(auto platform, auto platformBody)
{
// render expanded moving platform body as orange rectangle
Renderer::submitQuad(Null, Null, &sf::Color(255, 165, 0, 50), Null,
platformBody, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
if(onPlatformCircles)
{
mRegistry.view<BodyRect, BodyCircle>().each([&]
(auto entity, auto body, auto circle)
{
sf::Color color;
if(mRegistry.has<IsOnPlatform>(entity))
color = sf::Color(30, 255, 30, 110); // green
else if(mRegistry.has<FallingIntoPit>(entity))
color = sf::Color(255, 30, 30, 110); // red
else
color = sf::Color(30, 30, 255, 110); // blue
// draw expanded circle of object
circle.radius += system::Platforms::sBodyCircleRadiusAdditionForPlatforms;
Renderer::submitCircle(color, body.pos + circle.offset - Vec2(circle.radius),
circle.radius, 50, ProjectionType::gameWorld, false);
});
}
}
if(movingPlatformPathBodies)
{
// render moving platform path body as lime rectangle
mRegistry.view<MovingPlatform, BodyRect>().each([&]
(auto platform, auto platformBody)
{
Renderer::submitQuad(Null, Null, &sf::Color(192, 255, 0, 50), Null,
platform.pathBody, 50, 0.f, {}, ProjectionType::gameWorld, false);
});
}
auto drawAlignBounds = [&](float alignment, float lineThickness, sf::Color lineColor)
{
FloatRect cameraBounds = getCurrentCameraBounds();
for(float x = cameraBounds.x - fmod(cameraBounds.x, alignment); x < cameraBounds.right(); x += alignment)
Renderer::submitLine(lineColor, Vec2(x, cameraBounds.y), Vec2(x, cameraBounds.bottom()), lineThickness);
for(float y = cameraBounds.y - fmod(cameraBounds.y, alignment); y < cameraBounds.bottom(); y += alignment)
Renderer::submitLine(lineColor, Vec2(cameraBounds.x, y), Vec2(cameraBounds.right(), y), lineThickness);
};
if(tileBounds)
{
drawAlignBounds(16.f, 1.f, sf::Color(255, 0, 0, 200));
}
if(mapChunkBounds)
{
drawAlignBounds(16.f * 12.f, 5.f, sf::Color(0, 0, 255, 200));
}
if(spatialPartitionBounds)
{
drawAlignBounds(16.f * 12.f * 3.f, 20.f, sf::Color(255, 255, 30, 240));
if(simRegion)
{
Renderer::submitQuad(Null, Null, &sf::Color(255, 255, 0, 50), Null,
*simRegionRect, 50, 0.f, {}, ProjectionType::gameWorld, false);
Renderer::submitQuad(Null, Null, &sf::Color(0, 255, 0, 100), Null,
*simRegionCentralPartitionRect, 50, 0.f, {}, ProjectionType::gameWorld, false);
}
}
}
}
| 0 | 0.954001 | 1 | 0.954001 | game-dev | MEDIA | 0.669924 | game-dev,graphics-rendering | 0.934771 | 1 | 0.934771 |
Greavesy1899/MafiaToolkit | 15,328 | Mafia2Libs/ResourceTypes/FileTypes/SoundSectors/SoundSector.cs | using Gibbed.IO;
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using Toolkit.Mathematics;
using Utils.Extensions;
using Utils.Helpers.Reflection;
using Utils.StringHelpers;
using Utils.VorticeUtils;
namespace ResourceTypes.Sound
{
public class PlaneConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
object result = null;
string stringValue = value as string;
if (!string.IsNullOrEmpty(stringValue))
{
float[] values = ConverterUtils.ConvertStringToFloats(stringValue, 4);
result = new Plane(values);
}
return result ?? base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
object result = null;
Plane plane = (Plane)value;
if (destinationType == typeof(string))
{
result = plane.ToString();
}
return result ?? base.ConvertTo(context, culture, value, destinationType);
}
}
[TypeConverter(typeof(PlaneConverter)), PropertyClassAllowReflection]
public class Plane
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public float W { get; set; }
public Plane() { }
public Plane(float[] Values)
{
X = Values[0];
Y = Values[1];
Z = Values[2];
W = Values[3];
}
public void ReadFromFile(MemoryStream Stream, bool bIsBigEndian)
{
X = Stream.ReadSingle(bIsBigEndian);
Y = Stream.ReadSingle(bIsBigEndian);
Z = Stream.ReadSingle(bIsBigEndian);
W = Stream.ReadSingle(bIsBigEndian);
}
public void WriteToFile(MemoryStream Stream, bool bIsBigEndian)
{
Stream.Write(X, bIsBigEndian);
Stream.Write(Y, bIsBigEndian);
Stream.Write(Z, bIsBigEndian);
Stream.Write(W, bIsBigEndian);
}
public override string ToString()
{
return string.Format("X:{0} Y:{1} Z:{2} W:{3}", X, Y, Z, W);
}
}
[PropertyClassCheckInherited, PropertyClassAllowReflection]
public class SoundSectorBase
{
public ushort[] Unk0 { get; set; }
public uint Unk1 { get; set; }
public uint Unk2 { get; set; }
public string Name { get; set; }
public short Unk3 { get; set; }
public ushort Unk4 { get; set; }
public ushort Unk5 { get; set; }
public bool bBasicSceneOnly { get; set; }
public SoundSectorBase()
{
Unk0 = new ushort[0];
Unk1 = 0;
Unk2 = 0;
Name = string.Empty;
}
public virtual void ReadSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
// Read array of ushorts, I suppsoe they reference big hash list in main file.
ushort NumCount = Stream.ReadUInt16(bIsBigEndian);
Unk0 = new ushort[NumCount];
for(ushort i = 0; i < NumCount; i++)
{
Unk0[i] = Stream.ReadUInt16(bIsBigEndian);
}
// The game requires either of these to be valid, otherwise returns null
Unk1 = Stream.ReadUInt32(bIsBigEndian);
Unk2 = Stream.ReadUInt32(bIsBigEndian);
Name = Stream.ReadString8(bIsBigEndian);
// Between here the game checks if its below 5, if it is return out early
// Continue
Unk3 = Stream.ReadInt16(bIsBigEndian);
if (Unk3 != 0xFF)
{
// TODO:
int z = 0;
}
Unk4 = Stream.ReadUInt16(bIsBigEndian);
Unk5 = Stream.ReadUInt16(bIsBigEndian);
bBasicSceneOnly = Stream.ReadBoolean();
}
public virtual void WriteSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
// Write lookup list
Stream.Write((ushort)Unk0.Length, bIsBigEndian);
foreach(ushort Value in Unk0)
{
Stream.Write(Value, bIsBigEndian);
}
Stream.Write(Unk1, bIsBigEndian);
Stream.Write(Unk2, bIsBigEndian);
Stream.WriteString8(Name, bIsBigEndian);
Stream.Write(Unk3, bIsBigEndian);
Stream.Write(Unk4, bIsBigEndian);
Stream.Write(Unk5, bIsBigEndian);
Stream.WriteByte((byte)(bBasicSceneOnly ? 1 : 0));
}
}
class SoundSectorPrimary : SoundSectorBase
{
public SoundSectorPrimary() : base() { }
}
class SoundSectorNormal : SoundSectorBase
{
public Plane[] Planes { get; set; }
public SoundSectorNormal() : base()
{
Planes = new Plane[0];
}
public override void ReadSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
// Read floats, yes, before the base class. How odd.
byte NumFloats = Stream.ReadByte8(); // Probably vector count
Planes = new Plane[NumFloats];
for (byte i = 0; i < Planes.Length; i++)
{
Plane NewPlane = new Plane();
NewPlane.ReadFromFile(Stream, bIsBigEndian);
Planes[i] = NewPlane;
}
// Read base class!
base.ReadSDS(Stream, Endianess);
}
public override void WriteSDS(MemoryStream Stream, Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
// Write planes
Stream.WriteByte((byte)Planes.Length);
foreach(Plane CurPlane in Planes)
{
CurPlane.WriteToFile(Stream, bIsBigEndian);
}
// Write base class
base.WriteSDS(Stream, Endianess);
}
}
public class PortalSphere
{
public string Name { get; set; }
public Vec3 Position { get; set; }
public float Unk0 { get; set; }
public float OpenRatio { get; set; }
public string LinkA { get; set; }
public byte Unk2 { get; set; }
public string LinkB { get; set; }
public byte Unk3 { get; set; }
public float CostFactor { get; set; }
public string EntityName { get; set; }
public byte Unk6 { get; set; }
public byte bVolumeFactorEnabled { get; set; }
public float VolumeFactor { get; set; }
public PortalSphere()
{
Name = string.Empty;
Position = new Vec3();
Unk0 = 0.0f;
OpenRatio = 0.0f;
LinkA = string.Empty;
Unk2 = 0;
LinkB = string.Empty;
Unk3 = 0;
CostFactor = 0.0f;
EntityName = string.Empty;
Unk6 = 0;
bVolumeFactorEnabled = 0;
VolumeFactor = 0.0f;
}
public void ReadSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
Name = Stream.ReadString8(bIsBigEndian);
Position.ReadFromFile(Stream, bIsBigEndian);
Unk0 = Stream.ReadSingle(bIsBigEndian);
OpenRatio = Stream.ReadSingle(bIsBigEndian);
LinkA = Stream.ReadString8(bIsBigEndian);
Unk2 = Stream.ReadByte8();
LinkB = Stream.ReadString8(bIsBigEndian);
Unk3 = Stream.ReadByte8();
CostFactor = Stream.ReadSingle(bIsBigEndian);
EntityName = Stream.ReadString8(bIsBigEndian);
Unk6 = Stream.ReadByte8();
bVolumeFactorEnabled = Stream.ReadByte8();
if((bVolumeFactorEnabled & 1) != 0) // Guarded at 0x140287126
{
byte VolumeFactorAsByte = Stream.ReadByte8();
VolumeFactor = (VolumeFactorAsByte / 255.0f);
}
}
public void WriteSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
Stream.WriteString8(Name, bIsBigEndian);
Position.WriteToFile(Stream, bIsBigEndian);
Stream.Write(Unk0, bIsBigEndian);
Stream.Write(OpenRatio, bIsBigEndian);
Stream.WriteString8(LinkA, bIsBigEndian);
Stream.WriteByte(Unk2);
Stream.WriteString8(LinkB, bIsBigEndian);
Stream.WriteByte(Unk3);
Stream.Write(CostFactor, bIsBigEndian);
Stream.WriteString8(EntityName, bIsBigEndian);
Stream.WriteByte(Unk6);
Stream.WriteByte(bVolumeFactorEnabled);
if((bVolumeFactorEnabled & 1) != 0) // Guarded at 0x140287126
{
byte VolumeFactorAsByte = (byte)(VolumeFactor * 255);
Stream.WriteByte(VolumeFactorAsByte);
}
}
}
public class SoundSectorResource
{
public string Name { get; set; }
public ulong[] Hashes { get; set; }
public SoundSectorBase[] Sectors { get; set; }
public PortalSphere[] Portals { get; set; }
public SoundSectorResource()
{
Name = string.Empty;
Hashes = new ulong[0];
Sectors = new SoundSectorBase[0];
Portals = new PortalSphere[0];
}
public SoundSectorResource(FileInfo info)
{
byte[] FileBytes = File.ReadAllBytes(info.FullName);
using(MemoryStream Stream = new MemoryStream(FileBytes))
{
ReadSDS(Stream, Gibbed.IO.Endian.Little);
XElement XMLFile = ReflectionHelpers.ConvertPropertyToXML(this);
XMLFile.Save("Output.xml");
using(MemoryStream WriteStream = new MemoryStream())
{
WriteSDS(WriteStream, Gibbed.IO.Endian.Little);
File.WriteAllBytes("Output.bin", WriteStream.ToArray());
}
}
}
public void ReadSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
Name = Stream.ReadString8(bIsBigEndian);
// Read all hashes
uint NumHashes = Stream.ReadUInt32(bIsBigEndian);
Hashes = new ulong[NumHashes];
for (uint i = 0; i < NumHashes; i++)
{
Hashes[i] = Stream.ReadUInt64(bIsBigEndian);
}
// Read Sectors
uint NumSectors = Stream.ReadUInt32(bIsBigEndian);
Sectors = new SoundSectorBase[NumSectors];
for(uint i = 0; i < NumSectors; i++)
{
byte SectorType = Stream.ReadByte8();
if(SectorType == 0)
{
SoundSectorPrimary SectorPrimary = new SoundSectorPrimary();
SectorPrimary.ReadSDS(Stream, Endianess);
Sectors[i] = SectorPrimary;
}
else if(SectorType == 1)
{
SoundSectorNormal SectorNormal = new SoundSectorNormal();
SectorNormal.ReadSDS(Stream, Endianess);
Sectors[i] = SectorNormal;
}
}
// Read Portals
uint NumPortals = Stream.ReadUInt32(bIsBigEndian);
Portals = new PortalSphere[NumPortals];
for (uint i = 0; i < NumPortals; i++)
{
byte PortalType = Stream.ReadByte8();
if(PortalType == 0)
{
PortalSphere Portal = new PortalSphere();
Portal.ReadSDS(Stream, Endianess);
Portals[i] = Portal;
}
else
{
int z = 0;
}
}
}
public void WriteSDS(MemoryStream Stream, Gibbed.IO.Endian Endianess)
{
bool bIsBigEndian = (Endianess == Gibbed.IO.Endian.Big);
Stream.WriteString8(Name, bIsBigEndian);
// Write hashes
Stream.Write(Hashes.Length, bIsBigEndian);
foreach (ulong Hash in Hashes)
{
Stream.Write(Hash, bIsBigEndian);
}
// Write Sectors
Stream.Write(Sectors.Length, bIsBigEndian);
foreach(SoundSectorBase Sector in Sectors)
{
// TODO: Could probably clean this... but it does for now
SoundSectorPrimary PrimarySector = (Sector as SoundSectorPrimary);
if(PrimarySector != null)
{
Stream.WriteByte(0);
PrimarySector.WriteSDS(Stream, Endianess);
}
SoundSectorNormal NormalSector = (Sector as SoundSectorNormal);
if (NormalSector != null)
{
Stream.WriteByte(1);
NormalSector.WriteSDS(Stream, Endianess);
}
}
// Write portals
Stream.Write(Portals.Length, bIsBigEndian);
foreach (PortalSphere Portal in Portals)
{
Stream.WriteByte(0);
Portal.WriteSDS(Stream, Endianess);
}
}
public void WriteToFile(string FileName, bool bIsBigEndian)
{
using (MemoryStream outStream = new MemoryStream())
{
WriteSDS(outStream, (bIsBigEndian ? Endian.Big : Endian.Little));
File.WriteAllBytes(FileName, outStream.ToArray());
}
}
public void ConvertToXML(string Filename)
{
XElement Root = ReflectionHelpers.ConvertPropertyToXML(this);
Root.Save(Filename);
}
public void ConvertFromXML(string Filename)
{
XElement LoadedDoc = XElement.Load(Filename);
SoundSectorResource FileContents = ReflectionHelpers.ConvertToPropertyFromXML<SoundSectorResource>(LoadedDoc);
// Copy data taken from loaded XML
Hashes = FileContents.Hashes;
Sectors = FileContents.Sectors;
Portals = FileContents.Portals;
Name = FileContents.Name;
}
}
}
| 0 | 0.869803 | 1 | 0.869803 | game-dev | MEDIA | 0.569068 | game-dev | 0.956069 | 1 | 0.956069 |
GrapheneCt/PVR_PSP2 | 2,407 | include/gpu_es4/eurasia/include4/sgxscript.h | /*!****************************************************************************
@File sgxscript.h
@Title sgx kernel services structues/functions
@Author Imagination Technologies
@date 02 / 11 / 07
@Copyright Copyright 2007 by Imagination Technologies Limited.
All rights reserved. No part of this software, either
material or conceptual may be copied or distributed,
transmitted, transcribed, stored in a retrieval system
or translated into any human or computer language in any
form by any means, electronic, mechanical, manual or
other-wise, or disclosed to third parties without the
express written permission of Imagination Technologies
Limited, Unit 8, HomePark Industrial Estate,
King's Langley, Hertfordshire, WD4 8LZ, U.K.
@Platform Generic
@Description SGX initialisation script definitions.
@DoxygenVer
Modifications :-
$Log: sgxscript.h $
*****************************************************************************/
#ifndef __SGXSCRIPT_H__
#define __SGXSCRIPT_H__
#if defined (__cplusplus)
extern "C" {
#endif
#define SGX_MAX_INIT_COMMANDS 64
#define SGX_MAX_DEINIT_COMMANDS 16
typedef enum _SGX_INIT_OPERATION
{
SGX_INIT_OP_ILLEGAL = 0,
SGX_INIT_OP_WRITE_HW_REG,
#if defined(PDUMP)
SGX_INIT_OP_PDUMP_HW_REG,
#endif
SGX_INIT_OP_HALT
} SGX_INIT_OPERATION;
typedef union _SGX_INIT_COMMAND
{
SGX_INIT_OPERATION eOp;
struct {
SGX_INIT_OPERATION eOp;
IMG_UINT32 ui32Offset;
IMG_UINT32 ui32Value;
} sWriteHWReg;
#if defined(PDUMP)
struct {
SGX_INIT_OPERATION eOp;
IMG_UINT32 ui32Offset;
IMG_UINT32 ui32Value;
} sPDumpHWReg;
#endif
#if defined(FIX_HW_BRN_22997) && defined(FIX_HW_BRN_23030) && defined(SGX_FEATURE_HOST_PORT)
struct {
SGX_INIT_OPERATION eOp;
} sWorkaroundBRN22997;
#endif
} SGX_INIT_COMMAND;
typedef struct _SGX_INIT_SCRIPTS_
{
SGX_INIT_COMMAND asInitCommandsPart1[SGX_MAX_INIT_COMMANDS];
SGX_INIT_COMMAND asInitCommandsPart2[SGX_MAX_INIT_COMMANDS];
SGX_INIT_COMMAND asDeinitCommands[SGX_MAX_DEINIT_COMMANDS];
} SGX_INIT_SCRIPTS;
#if defined(__cplusplus)
}
#endif
#endif /* __SGXSCRIPT_H__ */
/*****************************************************************************
End of file (sgxscript.h)
*****************************************************************************/
| 0 | 0.639534 | 1 | 0.639534 | game-dev | MEDIA | 0.297486 | game-dev | 0.848065 | 1 | 0.848065 |
jjbali/Extended-Experienced-PD | 2,945 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/TenguSprite.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2023 Evan Debenham
*
* Experienced Pixel Dungeon
* Copyright (C) 2019-2020 Trashbox Bobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.sprites;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.watabou.noosa.TextureFilm;
import com.watabou.utils.Callback;
public class TenguSprite extends MobSprite {
public TenguSprite() {
super();
texture( Assets.Sprites.TENGU );
TextureFilm frames = new TextureFilm( texture, 14, 16 );
idle = new Animation( 2, true );
idle.frames( frames, 0, 0, 0, 1 );
run = new Animation( 15, false );
run.frames( frames, 2, 3, 4, 5, 0 );
attack = new Animation( 15, false );
attack.frames( frames, 6, 7, 7, 0 );
zap = attack.clone();
die = new Animation( 8, false );
die.frames( frames, 8, 9, 10, 10, 10, 10, 10, 10 );
play( run.clone() );
}
@Override
public void play(Animation anim) {
if (isMoving && anim != run){
synchronized (this){
isMoving = false;
notifyAll();
}
}
super.play(anim);
}
@Override
public void move( int from, int to ) {
place( to );
play( run );
turnTo( from , to );
isMoving = true;
if (Dungeon.level.water[to]) {
GameScene.ripple( to );
}
}
@Override
public void update() {
if (paused) isMoving = false;
super.update();
}
@Override
public void attack( int cell ) {
if (!Dungeon.level.adjacent( cell, ch.pos )) {
((MissileSprite)parent.recycle( MissileSprite.class )).
reset( this, cell, new TenguShuriken(), new Callback() {
@Override
public void call() {
ch.onAttackComplete();
}
} );
zap( ch.pos );
} else {
super.attack( cell );
}
}
@Override
public void onComplete( Animation anim ) {
if (anim == run) {
synchronized (this){
isMoving = false;
idle();
notifyAll();
}
} else {
super.onComplete( anim );
}
}
public static class TenguShuriken extends Item {
{
image = ItemSpriteSheet.SHURIKEN;
}
}
}
| 0 | 0.893409 | 1 | 0.893409 | game-dev | MEDIA | 0.99497 | game-dev | 0.957109 | 1 | 0.957109 |
hypergonial/hikari-miru | 19,538 | miru/ext/menu/items.py | from __future__ import annotations
import abc
import inspect
import typing as t
import hikari
import miru
from miru.ext.menu.menu import Menu
if t.TYPE_CHECKING:
from miru.ext.menu.screen import Screen
from miru.internal.types import InteractiveButtonStylesT
__all__ = (
"InteractiveScreenItem",
"ScreenButton",
"ScreenChannelSelect",
"ScreenItem",
"ScreenLinkButton",
"ScreenMentionableSelect",
"ScreenRoleSelect",
"ScreenTextSelect",
"ScreenUserSelect",
"button",
"channel_select",
"mentionable_select",
"role_select",
"text_select",
"user_select",
)
ScreenT = t.TypeVar("ScreenT", bound="Screen")
ScreenItemT = t.TypeVar("ScreenItemT", bound="InteractiveScreenItem")
class ScreenItem(miru.abc.ViewItem, abc.ABC):
"""An abstract base for all screen items.
[`Screen`][miru.ext.menu.screen.Screen] requires instances of this class as it's items.
"""
def __init__(
self,
*,
custom_id: str | None = None,
row: int | None = None,
position: int | None = None,
disabled: bool = False,
width: int = 1,
) -> None:
super().__init__(custom_id=custom_id, row=row, width=width, position=position, disabled=disabled)
self._screen: Screen | None = None
@property
def menu(self) -> Menu:
"""The menu this item is attached to.
This will be the same as `view` if the view is a menu.
"""
if not isinstance(self.view, Menu):
raise AttributeError(f"{type(self).__name__} hasn't been attached to a menu.")
return self.view
@property
def screen(self) -> Screen:
"""The screen this item is attached to."""
if not self._screen:
raise AttributeError(f"{type(self).__name__} hasn't been attached to a screen yet.")
return self._screen
class InteractiveScreenItem(miru.abc.InteractiveViewItem, ScreenItem):
"""An abstract base for all interactive screen items."""
class ScreenLinkButton(miru.LinkButton, ScreenItem):
"""A base class for all screen link buttons."""
class ScreenButton(miru.Button, InteractiveScreenItem):
"""A base class for all screen buttons."""
class ScreenTextSelect(miru.TextSelect, InteractiveScreenItem):
"""A base class for all screen text selects."""
class ScreenUserSelect(miru.UserSelect, InteractiveScreenItem):
"""A base class for all screen user selects."""
class ScreenRoleSelect(miru.RoleSelect, InteractiveScreenItem):
"""A base class for all screen role selects."""
class ScreenChannelSelect(miru.ChannelSelect, InteractiveScreenItem):
"""A base class for all screen channel selects."""
class ScreenMentionableSelect(miru.MentionableSelect, InteractiveScreenItem):
"""A base class for all screen mentionable selects."""
class DecoratedScreenItem(t.Generic[ScreenT, ScreenItemT]):
"""A partial item made using a decorator."""
__slots__ = ("callback", "item_type", "kwargs")
def __init__(
self,
item_type: type[ScreenItemT],
callback: t.Callable[[ScreenT, miru.ViewContext, ScreenItemT], t.Coroutine[t.Any, t.Any, None]],
**kwargs: t.Any,
) -> None:
self.item_type = item_type
self.callback = callback
self.kwargs = kwargs
def build(self, screen: ScreenT) -> ScreenItemT:
"""Convert a DecoratedScreenItem into a ViewItem.
Parameters
----------
screen : ScreenT
The screen this decorated item is attached to.
Returns
-------
ScreenItemT
The converted item.
"""
item = self.item_type(**self.kwargs)
async def wrapped_callback(ctx: miru.ViewContext) -> None:
await self.callback(screen, ctx, item)
item.callback = wrapped_callback
return item
@property
def name(self) -> str:
"""The name of the callback this item decorates.
Returns
-------
str
The name of the callback.
"""
return self.callback.__name__
def __call__(self, screen: ScreenT, context: miru.ViewContext, item: ScreenItemT) -> t.Any:
return self.callback(screen, context, item)
def button(
*,
label: str | None = None,
custom_id: str | None = None,
style: InteractiveButtonStylesT = hikari.ButtonStyle.PRIMARY,
emoji: str | hikari.Emoji | None = None,
row: int | None = None,
disabled: bool = False,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenButton], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenButton],
]:
"""A decorator to transform a coroutine function into a Discord UI Button's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
label : Optional[str]
The button's label
custom_id : Optional[str]
The button's custom ID
style : hikari.ButtonStyle
The style of the button
emoji : Optional[Union[str, hikari.Emoji]]
The emoji shown on the button
row : Optional[int]
The row the button should be in, leave as None for auto-placement.
disabled : bool
A boolean determining if the button should be disabled or not
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the button. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, miru.ViewContext, ScreenButton], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenButton]]
The decorated callback coroutine function.
Raises
------
TypeError
If the decorated function is not a coroutine function.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenButton], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenButton]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@button' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenButton,
func,
label=label,
custom_id=custom_id,
style=style,
emoji=emoji,
row=row,
disabled=disabled,
autodefer=autodefer,
)
return decorator
def channel_select(
*,
channel_types: t.Sequence[hikari.ChannelType] = (hikari.ChannelType.GUILD_TEXT,),
custom_id: str | None = None,
placeholder: str | None = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: int | None = None,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenChannelSelect], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenChannelSelect],
]:
"""A decorator to transform a function into a Discord UI ChannelSelectMenu's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
channel_types : Sequence[hikari.ChannelType]
A sequence of channel types to filter the select menu by. Defaults to (hikari.ChannelType.GUILD_TEXT,).
custom_id : Optional[str]
The custom ID for the select menu. Defaults to None.
placeholder : Optional[str]
The placeholder text for the channel select menu. Defaults to None.
min_values : int
The minimum number of values that can be selected. Defaults to 1.
max_values : int
The maximum number of values that can be selected. Defaults to 1.
disabled : bool
Whether the channel select menu is disabled or not. Defaults to False.
row : Optional[int]
The row the select should be in, leave as None for auto-placement.
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the select menu. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, ScreenChannelSelect, ViewContextT], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenChannelSelect, ViewContextT]]
The decorated function.
Raises
------
TypeError
If the decorated function is not a coroutine function.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenChannelSelect], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenChannelSelect]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@channel_select' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenChannelSelect,
func,
channel_types=channel_types,
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
autodefer=autodefer,
)
return decorator
def mentionable_select(
*,
custom_id: str | None = None,
placeholder: str | None = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: int | None = None,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenMentionableSelect], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenMentionableSelect],
]:
"""A decorator to transform a function into a Discord UI MentionableSelectMenu's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
custom_id : Optional[str]
The custom ID for the select menu
placeholder : Optional[str]
The placeholder text to display when no option is selected
min_values : int
The minimum number of values that can be selected
max_values : int
The maximum number of values that can be selected
disabled : bool
Whether the mentionable select menu is disabled
row : Optional[int]
The row the select should be in, leave as None for auto-placement.
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the select menu. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, ScreenMentionableSelect, ViewContextT], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenMentionableSelect, ViewContextT]]
The decorated function.
Raises
------
TypeError
If the decorated function is not a coroutine function.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenMentionableSelect], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenMentionableSelect]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@mentionable_select' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenMentionableSelect,
func,
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
autodefer=autodefer,
)
return decorator
def role_select(
*,
custom_id: str | None = None,
placeholder: str | None = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: int | None = None,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenRoleSelect], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenRoleSelect],
]:
"""A decorator to transform a function into a Discord UI RoleSelectMenu's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
custom_id : Optional[str]
The custom ID for the select menu
placeholder : Optional[str]
The placeholder text to display when no roles are selected
min_values : int
The minimum number of roles that can be selected
max_values : int
The maximum number of roles that can be selected
disabled : bool
Whether the select menu is disabled or not
row : Optional[int]
The row number to place the select menu in
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the select menu. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, ScreenRoleSelect, ViewContextT], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenRoleSelect, ViewContextT]]
The decorated function that serves as the callback for the select menu.
Raises
------
TypeError
If the decorated function is not a coroutine function.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenRoleSelect], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenRoleSelect]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@role_select' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenRoleSelect,
func,
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
autodefer=autodefer,
)
return decorator
def text_select(
*,
options: t.Sequence[hikari.SelectMenuOption | miru.SelectOption],
custom_id: str | None = None,
placeholder: str | None = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: int | None = None,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenTextSelect], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenTextSelect],
]:
"""A decorator to transform a function into a Discord UI TextSelectMenu's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
options : Sequence[Union[hikari.SelectMenuOption, miru.SelectOption]]
The options to add to the select menu.
custom_id : Optional[str]
The custom ID for the select menu
placeholder : Optional[str]
The placeholder text to display when no options are selected
min_values : int
The minimum number of options that can be selected
max_values : int
The maximum number of options that can be selected
disabled : bool
Whether the select menu is disabled or not
row : Optional[int]
The row number to place the select menu in
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the select menu. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, ScreenTextSelect, ViewContextT], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenTextSelect, ViewContextT]]
The decorated function that serves as the callback for the select menu.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenTextSelect], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenTextSelect]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@text_select' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenTextSelect,
func,
options=options,
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
autodefer=autodefer,
)
return decorator
def user_select(
*,
custom_id: str | None = None,
placeholder: str | None = None,
min_values: int = 1,
max_values: int = 1,
disabled: bool = False,
row: int | None = None,
autodefer: bool | miru.AutodeferOptions | hikari.UndefinedType = hikari.UNDEFINED,
) -> t.Callable[
[t.Callable[[ScreenT, miru.ViewContext, ScreenUserSelect], t.Awaitable[None]]],
DecoratedScreenItem[ScreenT, ScreenUserSelect],
]:
"""A decorator to transform a function into a Discord UI UserSelectMenu's callback.
This must be inside a subclass of [`Screen`][miru.ext.menu.screen.Screen].
Parameters
----------
custom_id : Optional[str]
The custom ID for the select menu
placeholder : Optional[str]
The placeholder text to display when no users are selected
min_values : int
The minimum number of users that can be selected
max_values : int
The maximum number of users that can be selected
disabled : bool
Whether the select menu is disabled or not
row : Optional[int]
The row number to place the select menu in
autodefer : bool | AutodeferOptions | hikari.UndefinedType
The autodefer options for the select menu. If left `UNDEFINED`, the view's autodefer options will be used.
Returns
-------
Callable[[Callable[[ScreenT, ScreenUserSelect, ViewContextT], Awaitable[None]]], DecoratedScreenItem[ScreenT, ScreenUserSelect, ViewContextT]]
The decorated function that serves as the callback for the select menu.
"""
def decorator(
func: t.Callable[[ScreenT, miru.ViewContext, ScreenUserSelect], t.Awaitable[None]],
) -> DecoratedScreenItem[ScreenT, ScreenUserSelect]:
if not inspect.iscoroutinefunction(func):
raise TypeError("'@user_select' must decorate coroutine function.")
return DecoratedScreenItem(
ScreenUserSelect,
func,
custom_id=custom_id,
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
disabled=disabled,
row=row,
autodefer=autodefer,
)
return decorator
# MIT License
#
# Copyright (c) 2022-present hypergonial
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
| 0 | 0.955262 | 1 | 0.955262 | game-dev | MEDIA | 0.780957 | game-dev | 0.905396 | 1 | 0.905396 |
SonicEraZoR/Portal-Base | 25,311 | sp/src/public/chunkfile.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Implements an interface for reading and writing heirarchical
// text files of key value pairs. The format of the file is as follows:
//
// chunkname0
// {
// "key0" "value0"
// "key1" "value1"
// ...
// "keyN" "valueN"
// chunkname1
// {
// "key0" "value0"
// "key1" "value1"
// ...
// "keyN" "valueN"
// }
// }
// ...
// chunknameN
// {
// "key0" "value0"
// "key1" "value1"
// ...
// "keyN" "valueN"
// }
//
// The chunk names are not necessarily unique, nor are the key names, unless the
// parsing application requires them to be.
//
// $NoKeywords: $
//=============================================================================//
#include <fcntl.h>
#ifdef _WIN32
#include <io.h>
#endif
#include <math.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "chunkfile.h"
#include "mathlib/vector.h"
#include "mathlib/vector4d.h"
#include "tier1/strtools.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor.
//-----------------------------------------------------------------------------
CChunkHandlerMap::CChunkHandlerMap(void)
{
m_pHandlers = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor. Frees handler list.
//-----------------------------------------------------------------------------
CChunkHandlerMap::~CChunkHandlerMap(void)
{
ChunkHandlerInfoNode_t *pNode = m_pHandlers;
while (pNode != NULL)
{
ChunkHandlerInfoNode_t *pPrev = pNode;
pNode = pNode->pNext;
delete pPrev;
}
}
//-----------------------------------------------------------------------------
// Purpose: Adds a chunk handler to the handler list.
// Input : pszChunkName - Name of chunk to be handled.
// pfnHandler - Address of handler callback function.
// pData - Data to pass to the handler callback.
//-----------------------------------------------------------------------------
void CChunkHandlerMap::AddHandler(const char *pszChunkName, ChunkHandler_t pfnHandler, void *pData)
{
ChunkHandlerInfoNode_t *pNew = new ChunkHandlerInfoNode_t;
Q_strncpy(pNew->Handler.szChunkName, pszChunkName, sizeof( pNew->Handler.szChunkName ));
pNew->Handler.pfnHandler = pfnHandler;
pNew->Handler.pData = pData;
pNew->pNext = NULL;
if (m_pHandlers == NULL)
{
m_pHandlers = pNew;
}
else
{
ChunkHandlerInfoNode_t *pNode = m_pHandlers;
while (pNode->pNext != NULL)
{
pNode = pNode->pNext;
}
pNode->pNext = pNew;
}
}
//-----------------------------------------------------------------------------
// Purpose: Sets the callback for error handling within this chunk's scope.
// Input : pfnHandler -
// pData -
//-----------------------------------------------------------------------------
void CChunkHandlerMap::SetErrorHandler(ChunkErrorHandler_t pfnHandler, void *pData)
{
m_pfnErrorHandler = pfnHandler;
m_pErrorData = pData;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : ppData -
// Output : ChunkErrorHandler_t
//-----------------------------------------------------------------------------
ChunkErrorHandler_t CChunkHandlerMap::GetErrorHandler(void **ppData)
{
*ppData = m_pErrorData;
return(m_pfnErrorHandler);
}
//-----------------------------------------------------------------------------
// Purpose: Gets the handler for a given chunk name, if one has been set.
// Input : pszChunkName - Name of chunk.
// ppfnHandler - Receives the address of the callback function.
// ppData - Receives the context data for the given chunk.
// Output : Returns true if a handler was found, false if not.
//-----------------------------------------------------------------------------
ChunkHandler_t CChunkHandlerMap::GetHandler(const char *pszChunkName, void **ppData)
{
ChunkHandlerInfoNode_t *pNode = m_pHandlers;
while (pNode != NULL)
{
if (!stricmp(pNode->Handler.szChunkName, pszChunkName))
{
*ppData = pNode->Handler.pData;
return(pNode->Handler.pfnHandler);
}
pNode = pNode->pNext;
}
return(false);
}
//-----------------------------------------------------------------------------
// Purpose: Constructor. Initializes data members.
//-----------------------------------------------------------------------------
CChunkFile::CChunkFile(void)
{
m_hFile = NULL;
m_nCurrentDepth = 0;
m_szIndent[0] = '\0';
m_nHandlerStackDepth = 0;
m_DefaultChunkHandler = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor. Closes the file if it is currently open.
//-----------------------------------------------------------------------------
CChunkFile::~CChunkFile(void)
{
if (m_hFile != NULL)
{
fclose(m_hFile);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pszChunkName -
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::BeginChunk(const char *pszChunkName)
{
//
// Write the chunk name and open curly.
//
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "%s\r\n%s{", pszChunkName, m_szIndent);
ChunkFileResult_t eResult = WriteLine(szBuf);
//
// Update the indentation depth.
//
if (eResult == ChunkFile_Ok)
{
m_nCurrentDepth++;
BuildIndentString(m_szIndent, m_nCurrentDepth);
}
return(eResult);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CChunkFile::BuildIndentString(char *pszDest, int nDepth)
{
if (nDepth >= 0)
{
for (int i = 0; i < nDepth; i++)
{
pszDest[i] = '\t';
}
pszDest[nDepth] = '\0';
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::Close(void)
{
if (m_hFile != NULL)
{
fclose(m_hFile);
m_hFile = NULL;
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::EndChunk(void)
{
if (m_nCurrentDepth > 0)
{
m_nCurrentDepth--;
BuildIndentString(m_szIndent, m_nCurrentDepth);
}
WriteLine("}");
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose: Returns a string explaining the last error that occurred.
//-----------------------------------------------------------------------------
const char *CChunkFile::GetErrorText(ChunkFileResult_t eResult)
{
static char szError[MAX_KEYVALUE_LEN];
switch (eResult)
{
case ChunkFile_UnexpectedEOF:
{
Q_strncpy(szError, "unexpected end of file", sizeof( szError ) );
break;
}
case ChunkFile_UnexpectedSymbol:
{
Q_snprintf(szError, sizeof( szError ), "unexpected symbol '%s'", m_szErrorToken);
break;
}
case ChunkFile_OpenFail:
{
Q_snprintf(szError, sizeof( szError ), "%s", strerror(errno)) ;
break;
}
case ChunkFile_StringTooLong:
{
Q_strncpy(szError, "unterminated string or string too long", sizeof( szError ) );
break;
}
default:
{
Q_snprintf(szError, sizeof( szError ), "error %d", eResult);
}
}
return(m_TokenReader.Error(szError));
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : eError -
//-----------------------------------------------------------------------------
void CChunkFile::HandleError(const char *szChunkName, ChunkFileResult_t eError)
{
// UNDONE: dispatch errors to the error handler.
// - keep track of current chunkname for reporting errors
// - use the last non-NULL handler that was pushed onto the stack?
// - need a return code to determine whether to abort parsing?
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::HandleChunk(const char *szChunkName)
{
// See if the default handler wants it?
if( m_DefaultChunkHandler )
{
ChunkFileResult_t testResult = m_DefaultChunkHandler( this, m_pDefaultChunkHandlerData, szChunkName );
if( testResult == ChunkFile_Ok )
{
return ChunkFile_Ok;
}
}
//
// If there is an active handler map...
//
if (m_nHandlerStackDepth > 0)
{
CChunkHandlerMap *pHandler = m_HandlerStack[m_nHandlerStackDepth - 1];
//
// If a chunk handler was found in the handler map...
//
void *pData;
ChunkHandler_t pfnHandler = pHandler->GetHandler(szChunkName, &pData);
if (pfnHandler != NULL)
{
// Dispatch this chunk to the handler.
ChunkFileResult_t eResult = pfnHandler(this, pData);
if (eResult != ChunkFile_Ok)
{
return(eResult);
}
}
else
{
//
// No handler for this chunk. Skip to the matching close curly brace.
//
int nDepth = 1;
ChunkFileResult_t eResult;
do
{
ChunkType_t eChunkType;
char szKey[MAX_KEYVALUE_LEN];
char szValue[MAX_KEYVALUE_LEN];
while ((eResult = ReadNext(szKey, szValue, sizeof(szValue), eChunkType)) == ChunkFile_Ok)
{
if (eChunkType == ChunkType_Chunk)
{
nDepth++;
}
}
if (eResult == ChunkFile_EndOfChunk)
{
eResult = ChunkFile_Ok;
nDepth--;
}
else if (eResult == ChunkFile_EOF)
{
return(ChunkFile_UnexpectedEOF);
}
} while ((nDepth) && (eResult == ChunkFile_Ok));
}
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose: Opens the chunk file for reading or writing.
// Input : pszFileName - Path of file to open.
// eMode - ChunkFile_Read or ChunkFile_Write.
// Output : Returns ChunkFile_Ok on success, ChunkFile_Fail on failure.
// UNDONE: boolean return value?
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::Open(const char *pszFileName, ChunkFileOpenMode_t eMode)
{
if (eMode == ChunkFile_Read)
{
// UNDONE: TokenReader encapsulates file - unify reading and writing to use the same file I/O.
// UNDONE: Support in-memory parsing.
if (m_TokenReader.Open(pszFileName))
{
m_nCurrentDepth = 0;
}
else
{
return(ChunkFile_OpenFail);
}
}
else if (eMode == ChunkFile_Write)
{
m_hFile = fopen(pszFileName, "wb");
if (m_hFile == NULL)
{
return(ChunkFile_OpenFail);
}
m_nCurrentDepth = 0;
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose: Removes the topmost set of chunk handlers.
//-----------------------------------------------------------------------------
void CChunkFile::PopHandlers(void)
{
if (m_nHandlerStackDepth > 0)
{
m_nHandlerStackDepth--;
}
}
void CChunkFile::SetDefaultChunkHandler( DefaultChunkHandler_t pHandler, void *pData )
{
m_DefaultChunkHandler = pHandler;
m_pDefaultChunkHandlerData = pData;}
//-----------------------------------------------------------------------------
// Purpose: Adds a set of chunk handlers to the top of the handler stack.
// Input : pHandlerMap - Object containing the list of chunk handlers.
//-----------------------------------------------------------------------------
void CChunkFile::PushHandlers(CChunkHandlerMap *pHandlerMap)
{
if (m_nHandlerStackDepth < MAX_INDENT_DEPTH)
{
m_HandlerStack[m_nHandlerStackDepth] = pHandlerMap;
m_nHandlerStackDepth++;
}
}
//-----------------------------------------------------------------------------
// Purpose: Reads the next term from the chunk file. The type of term read is
// returned in the eChunkType parameter.
// Input : szName - Name of key or chunk.
// szValue - If eChunkType is ChunkType_Key, contains the value of the key.
// nValueSize - Size of the buffer pointed to by szValue.
// eChunkType - ChunkType_Key or ChunkType_Chunk.
// Output : Returns ChunkFile_Ok on success, an error code if a parsing error occurs.
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::ReadNext(char *szName, char *szValue, int nValueSize, ChunkType_t &eChunkType)
{
// HACK: pass in buffer sizes?
trtoken_t eTokenType = m_TokenReader.NextToken(szName, MAX_KEYVALUE_LEN);
if (eTokenType != TOKENEOF)
{
switch (eTokenType)
{
case IDENT:
case STRING:
{
char szNext[MAX_KEYVALUE_LEN];
trtoken_t eNextTokenType;
//
// Read the next token to determine what we have.
//
eNextTokenType = m_TokenReader.NextToken(szNext, sizeof(szNext));
switch (eNextTokenType)
{
case OPERATOR:
{
if (!stricmp(szNext, "{"))
{
// Beginning of new chunk.
m_nCurrentDepth++;
eChunkType = ChunkType_Chunk;
szValue[0] = '\0';
return(ChunkFile_Ok);
}
else
{
// Unexpected symbol.
Q_strncpy(m_szErrorToken, szNext, sizeof( m_szErrorToken ) );
return(ChunkFile_UnexpectedSymbol);
}
}
case STRING:
case IDENT:
{
// Key value pair.
Q_strncpy(szValue, szNext, nValueSize );
eChunkType = ChunkType_Key;
return(ChunkFile_Ok);
}
case TOKENEOF:
{
// Unexpected end of file.
return(ChunkFile_UnexpectedEOF);
}
case TOKENSTRINGTOOLONG:
{
// String too long or unterminated string.
return ChunkFile_StringTooLong;
}
}
}
case OPERATOR:
{
if (!stricmp(szName, "}"))
{
// End of current chunk.
m_nCurrentDepth--;
return(ChunkFile_EndOfChunk);
}
else
{
// Unexpected symbol.
Q_strncpy(m_szErrorToken, szName, sizeof( m_szErrorToken ) );
return(ChunkFile_UnexpectedSymbol);
}
}
case TOKENSTRINGTOOLONG:
{
return ChunkFile_StringTooLong;
}
}
}
if (m_nCurrentDepth != 0)
{
// End of file while within the scope of a chunk.
return(ChunkFile_UnexpectedEOF);
}
return(ChunkFile_EOF);
}
//-----------------------------------------------------------------------------
// Purpose: Reads the current chunk and dispatches keys and sub-chunks to the
// appropriate handler callbacks.
// Input : pfnKeyHandler - Callback for any key values in this chunk.
// pData - Data to pass to the key value callback function.
// Output : Normally returns ChunkFile_Ok or ChunkFile_EOF. Otherwise, returns
// a ChunkFile_xxx error code.
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::ReadChunk(KeyHandler_t pfnKeyHandler, void *pData)
{
//
// Read the keys and sub-chunks.
//
ChunkFileResult_t eResult;
do
{
char szName[MAX_KEYVALUE_LEN];
char szValue[MAX_KEYVALUE_LEN];
ChunkType_t eChunkType;
eResult = ReadNext(szName, szValue, sizeof(szValue), eChunkType);
if (eResult == ChunkFile_Ok)
{
if (eChunkType == ChunkType_Chunk)
{
//
// Dispatch sub-chunks to the appropriate handler.
//
eResult = HandleChunk(szName);
}
else if ((eChunkType == ChunkType_Key) && (pfnKeyHandler != NULL))
{
//
// Dispatch keys to the key value handler.
//
eResult = pfnKeyHandler(szName, szValue, pData);
}
}
} while (eResult == ChunkFile_Ok);
//
// Cover up ChunkFile_EndOfChunk results because the caller doesn't want to see them.
//
if (eResult == ChunkFile_EndOfChunk)
{
eResult = ChunkFile_Ok;
}
//
// Dispatch errors to the handler.
//
if ((eResult != ChunkFile_Ok) && (eResult != ChunkFile_EOF))
{
//HandleError("chunkname", eResult);
}
return(eResult);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pbBool -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueBool(const char *pszValue, bool &bBool)
{
int nValue = atoi(pszValue);
if (nValue > 0)
{
bBool = true;
}
else
{
bBool = false;
}
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pfFloat -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueFloat(const char *pszValue, float &flFloat)
{
flFloat = (float)atof(pszValue);
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pnInt -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueInt(const char *pszValue, int &nInt)
{
nInt = atoi(pszValue);
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// r -
// g -
// b -
// Output :
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueColor(const char *pszValue, unsigned char &chRed, unsigned char &chGreen, unsigned char &chBlue)
{
if (pszValue != NULL)
{
int r = 0;
int g = 0;
int b = 0;
if (sscanf(pszValue, "%d %d %d", &r, &g, &b) == 3)
{
chRed = r;
chGreen = g;
chBlue = b;
return(true);
}
}
return(false);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pfPoint -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValuePoint(const char *pszValue, Vector &Point)
{
if (pszValue != NULL)
{
return(sscanf(pszValue, "(%f %f %f)", &Point.x, &Point.y, &Point.z) == 3);
}
return(false);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pfVector -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueVector2(const char *pszValue, Vector2D &vec)
{
if (pszValue != NULL)
{
return ( sscanf( pszValue, "[%f %f]", &vec.x, &vec.y) == 2 );
}
return(false);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pfVector -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueVector3(const char *pszValue, Vector &vec)
{
if (pszValue != NULL)
{
return(sscanf(pszValue, "[%f %f %f]", &vec.x, &vec.y, &vec.z) == 3);
}
return(false);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszValue -
// pfVector -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CChunkFile::ReadKeyValueVector4(const char *pszValue, Vector4D &vec)
{
if( pszValue != NULL )
{
return(sscanf(pszValue, "[%f %f %f %f]", &vec[0], &vec[1], &vec[2], &vec[3]) == 4);
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszLine -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValue(const char *pszKey, const char *pszValue)
{
if ((pszKey != NULL) && (pszValue != NULL))
{
char szTemp[MAX_KEYVALUE_LEN];
Q_snprintf(szTemp, sizeof( szTemp ), "\"%s\" \"%s\"", pszKey, pszValue);
return(WriteLine(szTemp));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// bValue -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueBool(const char *pszKey, bool bValue)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"%d\"", pszKey, (int)bValue);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// nValue -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueInt(const char *pszKey, int nValue)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"%d\"", pszKey, nValue);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// fValue -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueFloat(const char *pszKey, float fValue)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"%g\"", pszKey, (double)fValue);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// r -
// g -
// b -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueColor(const char *pszKey, unsigned char r, unsigned char g, unsigned char b)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"%d %d %d\"", pszKey, (int)r, (int)g, (int)b);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// fVector -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValuePoint(const char *pszKey, const Vector &Point)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"(%g %g %g)\"", pszKey, (double)Point[0], (double)Point[1], (double)Point[2]);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueVector2(const char *pszKey, const Vector2D &vec)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf( szBuf, sizeof( szBuf ), "\"%s\" \"[%g %g]\"", pszKey, (double)vec.x, (double)vec.y );
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueVector3(const char *pszKey, const Vector &vec)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"[%g %g %g]\"", pszKey, (double)vec.x, (double)vec.y, (double)vec.z);
return(WriteLine(szBuf));
}
return(ChunkFile_Ok);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pszKey -
// fVector -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteKeyValueVector4(const char *pszKey, const Vector4D &vec)
{
if (pszKey != NULL)
{
char szBuf[MAX_KEYVALUE_LEN];
Q_snprintf(szBuf, sizeof( szBuf ), "\"%s\" \"[%g %g %g %g]\"", pszKey, (double)vec.x, (double)vec.y, (double)vec.z, (double)vec.w);
return( WriteLine( szBuf ) );
}
return( ChunkFile_Ok );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pszLine -
// Output :
//-----------------------------------------------------------------------------
ChunkFileResult_t CChunkFile::WriteLine(const char *pszLine)
{
if (pszLine != NULL)
{
//
// Write the indentation string.
//
if (m_nCurrentDepth > 0)
{
int nWritten = fwrite(m_szIndent, 1, m_nCurrentDepth, m_hFile);
if (nWritten != m_nCurrentDepth)
{
return(ChunkFile_Fail);
}
}
//
// Write the string.
//
int nLen = strlen(pszLine);
int nWritten = fwrite(pszLine, 1, nLen, m_hFile);
if (nWritten != nLen)
{
return(ChunkFile_Fail);
}
//
// Write the linefeed.
//
if (fwrite("\r\n", 1, 2, m_hFile) != 2)
{
return(ChunkFile_Fail);
}
}
return(ChunkFile_Ok);
}
| 0 | 0.954879 | 1 | 0.954879 | game-dev | MEDIA | 0.415554 | game-dev | 0.976981 | 1 | 0.976981 |
digicannon/ssbm-triples-nintendont | 56,984 | loader/source/menu.c | /*
Nintendont (Loader) - Playing Gamecubes in Wii mode on a Wii U
Copyright (C) 2013 crediar
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation version 2.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gccore.h>
#include <sys/param.h>
#include "font.h"
#include "exi.h"
#include "global.h"
#include "FPad.h"
#include "Config.h"
#include "update.h"
#include "titles.h"
#include "dip.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ogc/stm.h>
#include <ogc/consol.h>
#include <ogc/system.h>
//#include <fat.h>
#include <di/di.h>
#include "menu.h"
#include "../../common/include/CommonConfigStrings.h"
#include "ff_utf8.h"
#include "ShowGameInfo.h"
// Dark gray for grayed-out menu items.
#define DARK_GRAY 0x888888FF
// Device state.
typedef enum {
// Device is open and has GC titles in "games" directory.
DEV_OK = 0,
// Device could not be opened.
DEV_NO_OPEN = 1,
// Device was opened but has no "games" directory.
DEV_NO_GAMES = 2,
// Device was opened but "games" directory is empty.
DEV_NO_TITLES = 3,
} DevState;
static u8 devState = DEV_OK;
// Disc format colors.
const u32 DiscFormatColors[8] =
{
BLACK, // Full
0x551A00FF, // Shrunken (dark brown)
0x00551AFF, // Extracted FST
0x001A55FF, // CISO
0x551A55FF, // Multi-Game
GRAY, // undefined
GRAY, // undefined
GRAY, // undefined
};
/**
* Print information about the selected device.
*/
static void PrintDevInfo(void);
extern NIN_CFG* ncfg;
u32 Shutdown = 0;
extern char *launch_dir;
inline u32 SettingY(u32 row)
{
return 127 + 16 * row;
}
void SetShutdown(void)
{
Shutdown = 1;
}
void HandleWiiMoteEvent(s32 chan)
{
SetShutdown();
}
void HandleSTMEvent(u32 event)
{
*(vu32*)(0xCC003024) = 1;
switch(event)
{
default:
case STM_EVENT_RESET:
break;
case STM_EVENT_POWER:
SetShutdown();
break;
}
}
int compare_names(const void *a, const void *b)
{
const gameinfo *da = (const gameinfo *) a;
const gameinfo *db = (const gameinfo *) b;
int ret = strcasecmp(da->Name, db->Name);
if (ret == 0)
{
// Names are equal. Check disc number.
const uint8_t dnuma = (da->Flags & GIFLAG_DISCNUMBER_MASK);
const uint8_t dnumb = (db->Flags & GIFLAG_DISCNUMBER_MASK);
if (dnuma < dnumb)
ret = -1;
else if (dnuma > dnumb)
ret = 1;
else
ret = 0;
}
return ret;
}
/**
* Check if a disc image is valid.
* @param filename [in] Disc image filename. (ISO/GCM)
* @param discNumber [in] Disc number.
* @param gi [out] gameinfo struct to store game information if the disc is valid.
* @return True if the image is valid; false if not.
*/
static bool IsDiscImageValid(const char *filename, int discNumber, gameinfo *gi)
{
// TODO: Handle FST format (sys/boot.bin).
u8 buf[0x100]; // Disc header.
u32 BI2region_addr = 0x458; // BI2 region code address.
FIL in;
if (f_open_char(&in, filename, FA_READ|FA_OPEN_EXISTING) != FR_OK)
{
// Could not open the disc image.
return false;
}
// Read the disc header
//gprintf("(%s) ok\n", filename );
bool ret = false;
UINT read;
f_read(&in, buf, sizeof(buf), &read);
if (read != sizeof(buf))
{
// Error reading from the file.
f_close(&in);
return false;
}
// Check for CISO magic with 2 MB block size.
// NOTE: CISO block size is little-endian.
static const uint8_t CISO_MAGIC[8] = {'C','I','S','O',0x00,0x00,0x20,0x00};
if (!memcmp(buf, CISO_MAGIC, sizeof(CISO_MAGIC)) &&
!IsGCGame(buf))
{
// CISO magic is present, and GCN magic isn't.
// This is most likely a CISO image.
// Read the actual GCN header.
f_lseek(&in, 0x8000);
f_read(&in, buf, 0x100, &read);
if (read != 0x100)
{
// Error reading from the file.
f_close(&in);
return false;
}
// Adjust the BI2 region code address for CISO.
BI2region_addr = 0x8458;
gi->Flags = GIFLAG_FORMAT_CISO;
}
else
{
// Standard GameCube disc image.
// TODO: Detect Triforce images and exclude them
// from size checking?
if (in.obj.objsize == 1459978240)
{
// Full 1:1 GameCube image.
gi->Flags = GIFLAG_FORMAT_FULL;
}
else
{
// Shrunken GameCube image.
gi->Flags = GIFLAG_FORMAT_SHRUNKEN;
}
}
if (IsGCGame(buf)) // Must be GC game
{
// Read the BI2 region code.
u32 BI2region;
f_lseek(&in, BI2region_addr);
f_read(&in, &BI2region, sizeof(BI2region), &read);
if (read != sizeof(BI2region)) {
// Error reading from the file.
f_close(&in);
return false;
}
// Save the region code for later.
gi->Flags |= ((BI2region & 3) << 3);
// Save the game ID.
memcpy(gi->ID, buf, 6); //ID for EXI
gi->Flags |= (discNumber & 3) << 5;
// Save the revision number.
gi->Revision = buf[0x07];
// Check if this is a multi-game image.
// Reference: https://gbatemp.net/threads/wit-wiimms-iso-tools-gamecube-disc-support.251630/#post-3088119
const bool is_multigame = IsMultiGameDisc((const char*)buf);
if (is_multigame)
{
if (gi->Flags == GIFLAG_FORMAT_CISO)
{
// Multi-game + CISO is NOT supported.
ret = false;
}
else
{
// Multi-game disc.
char *name = (char*)malloc(65);
const char *slash_pos = strrchr(filename, '/');
snprintf(name, 65, "Multi-Game Disc (%s)", (slash_pos ? slash_pos+1 : filename));
gi->Name = name;
gi->Flags = GIFLAG_FORMAT_MULTI | GIFLAG_NAME_ALLOC;
}
}
else
{
// Check if this title is in titles.txt.
bool isTriforce;
const char *dbTitle = SearchTitles(gi->ID, &isTriforce);
if (dbTitle)
{
// Title found.
gi->Name = (char*)dbTitle;
gi->Flags &= ~GIFLAG_NAME_ALLOC;
if (isTriforce)
{
// Clear the format value if it's "shrunken",
// since Triforce titles are never the size
// of a full 1:1 GameCube disc image.
if ((gi->Flags & GIFLAG_FORMAT_MASK) == GIFLAG_FORMAT_SHRUNKEN)
{
gi->Flags &= ~GIFLAG_FORMAT_MASK;
}
}
}
if (!dbTitle)
{
// Title not found.
// Use the title from the disc header.
// Make sure the title in the header is NULL terminated.
buf[0x20+65] = 0;
gi->Name = strdup((const char*)&buf[0x20]);
gi->Flags |= GIFLAG_NAME_ALLOC;
}
}
gi->Path = strdup(filename);
ret = true;
}
f_close(&in);
return ret;
}
/**
* Get all games from the games/ directory on the selected storage device.
* On Wii, this also adds a pseudo-game for loading GameCube games from disc.
*
* @param gi [out] Array of gameinfo structs.
* @param sz [in] Maximum number of elements in gi.
* @param pGameCount [out] Number of games loaded. (Includes GCN pseudo-game for Wii.)
*
* @return DevState value:
* - DEV_OK: Device opened and has GC titles in "games/" directory.
* - DEV_NO_OPEN: Could not open the storage device.
* - DEV_NO_GAMES: No "games/" directory was found.
* - DEV_NO_TITLES: "games/" directory contains no GC titles.
*/
static DevState LoadGameList(gameinfo *gi, u32 sz, u32 *pGameCount)
{
// Create a list of games
char filename[MAXPATHLEN]; // Current filename.
u8 buf[0x100]; // Disc header.
int gamecount = 0; // Current game count.
if( isWiiVC )
{
// Pseudo game for booting a GameCube disc on Wii VC.
gi[0].ID[0] = 'D',gi[0].ID[1] = 'I',gi[0].ID[2] = 'S';
gi[0].ID[3] = 'C',gi[0].ID[4] = '0',gi[0].ID[5] = '1';
gi[0].Name = "Boot included GC Disc";
gi[0].Revision = 0;
gi[0].Flags = 0;
gi[0].Path = strdup("di:di");
gamecount++;
}
else if( !IsWiiU() )
{
// Pseudo game for booting a GameCube disc on Wii.
gi[0].ID[0] = 'D',gi[0].ID[1] = 'I',gi[0].ID[2] = 'S';
gi[0].ID[3] = 'C',gi[0].ID[4] = '0',gi[0].ID[5] = '1';
gi[0].Name = "Boot GC Disc in Drive";
gi[0].Revision = 0;
gi[0].Flags = 0;
gi[0].Path = strdup("di:di");
gamecount++;
}
DIR pdir;
snprintf(filename, sizeof(filename), "%s:/games", GetRootDevice());
if (f_opendir_char(&pdir, filename) != FR_OK)
{
// Could not open the "games" directory.
// Attempt to open the device root.
snprintf(filename, sizeof(filename), "%s:/", GetRootDevice());
if (f_opendir_char(&pdir, filename) != FR_OK)
{
// Could not open the device root.
if (pGameCount)
*pGameCount = 0;
return DEV_NO_OPEN;
}
// Device root opened.
// This means the device is usable, but it
// doesn't have a "games" directory.
f_closedir(&pdir);
if (pGameCount)
*pGameCount = gamecount;
return DEV_NO_GAMES;
}
// Process the directory.
// TODO: chdir into /games/?
FILINFO fInfo;
FIL in;
while (f_readdir(&pdir, &fInfo) == FR_OK && fInfo.fname[0] != '\0')
{
/**
* Game layout should be:
*
* ISO/GCM format:
* - /games/GAMEID/game.gcm
* - /games/GAMEID/game.iso
* - /games/GAMEID/disc2.gcm
* - /games/GAMEID/disc2.iso
* - /games/[anything].gcm
* - /games/[anything].iso
*
* CISO format:
* - /games/GAMEID/game.ciso
* - /games/GAMEID/game.cso
* - /games/GAMEID/disc2.ciso
* - /games/GAMEID/disc2.cso
* - /games/[anything].ciso
*
* FST format:
* - /games/GAMEID/sys/boot.bin plus other files
*
* NOTE: 2-disc games currently only work with the
* subdirectory layout, and the second disc must be
* named either disc2.iso or disc2.gcm.
*/
// Skip "." and "..".
// This will also skip "hidden" directories.
if (fInfo.fname[0] == '.')
continue;
if (fInfo.fattrib & AM_DIR)
{
// Subdirectory.
// Prepare the filename buffer with the directory name.
// game.iso/disc2.iso will be appended later.
// NOTE: fInfo.fname[] is UTF-16.
const char *filename_utf8 = wchar_to_char(fInfo.fname);
int fnlen = snprintf(filename, sizeof(filename), "%s:/games/%s/",
GetRootDevice(), filename_utf8);
//Test if game.iso exists and add to list
bool found = false;
static const char disc_filenames[8][16] = {
"game.ciso", "game.cso", "game.gcm", "game.iso",
"disc2.ciso", "disc2.cso", "disc2.gcm", "disc2.iso"
};
u32 i;
for (i = 0; i < 8; i++)
{
const u32 discNumber = i / 4;
// Append the disc filename.
strcpy(&filename[fnlen], disc_filenames[i]);
// Attempt to load disc information.
if (IsDiscImageValid(filename, discNumber, &gi[gamecount]))
{
// Disc image exists and is a GameCube disc.
gamecount++;
found = true;
// Next disc number.
i = (discNumber * 4) + 3;
}
}
// If none of the expected files were found,
// check for FST format.
if (!found)
{
// Read the disc header from boot.bin.
memcpy(&filename[fnlen], "sys/boot.bin", 13);
if (f_open_char(&in, filename, FA_READ|FA_OPEN_EXISTING) != FR_OK)
continue;
//gprintf("(%s) ok\n", filename );
UINT read;
f_read(&in, buf, 0x100, &read);
f_close(&in);
if (read != 0x100 || !IsGCGame(buf))
continue;
// Read the BI2.bin region code.
memcpy(&filename[fnlen], "sys/bi2.bin", 12);
if (f_open_char(&in, filename, FA_READ|FA_OPEN_EXISTING) != FR_OK)
continue;
//gprintf("(%s) ok\n", filename );
u32 BI2region;
f_lseek(&in, 0x18);
f_read(&in, &BI2region, sizeof(BI2region), &read);
f_close(&in);
if (read != sizeof(BI2region))
continue;
// Terminate the filename at the game's base directory.
filename[fnlen] = 0;
// Make sure the title in the header is NULL terminated.
buf[0x20+65] = 0;
memcpy(gi[gamecount].ID, buf, 6); //ID for EXI
gi[gamecount].Revision = 0;
// TODO: Check titles.txt?
gi[gamecount].Name = strdup((const char*)&buf[0x20]);
gi[gamecount].Flags = GIFLAG_NAME_ALLOC | GIFLAG_FORMAT_FST | ((BI2region & 3) << 3);
gi[gamecount].Path = strdup(filename);
gamecount++;
}
}
else
{
// Regular file.
// Make sure its extension is ".iso" or ".gcm".
const char *filename_utf8 = wchar_to_char(fInfo.fname);
if (IsSupportedFileExt(filename_utf8))
{
// Create the full pathname.
snprintf(filename, sizeof(filename), "%s:/games/%s",
GetRootDevice(), filename_utf8);
// Attempt to load disc information.
// (NOTE: Only disc 1 is supported right now.)
if (IsDiscImageValid(filename, 0, &gi[gamecount]))
{
// Disc image exists and is a GameCube disc.
gamecount++;
}
}
}
if (gamecount >= sz) //if array is full
break;
}
f_closedir(&pdir);
// Sort the list alphabetically.
// On Wii, the pseudo-entry for GameCube discs is always
// kept at the top.
if( gamecount && IsWiiU() && !isWiiVC )
qsort(gi, gamecount, sizeof(gameinfo), compare_names);
else if( gamecount > 1 )
qsort(&gi[1], gamecount-1, sizeof(gameinfo), compare_names);
// Save the game count.
if (pGameCount)
*pGameCount = gamecount;
if(gamecount == 0)
return DEV_NO_TITLES;
return DEV_OK;
}
// Menu selection context.
typedef struct _MenuCtx
{
u32 menuMode; // Menu mode. (0 == games; 1 == settings)
bool redraw; // If true, redraw is required.
bool selected; // If true, the user selected a game.
bool saveSettings; // If true, save settings to nincfg.bin.
// Counters for key repeat.
struct {
u32 Up;
u32 Down;
u32 Left;
u32 Right;
} held;
// Games menu.
struct {
s32 posX; // Selected game index.
s32 scrollX; // Current scrolling position.
u32 listMax; // Maximum number of games to show onscreen at once.
const gameinfo *gi; // Game information.
int gamecount; // Game count.
bool canBeBooted; // Selected game is bootable.
bool canShowInfo; // Can show information for the selected game.
} games;
// Settings menu.
struct {
u32 settingPart; // 0 == left column; 1 == right column
s32 posX; // Selected setting index.
} settings;
} MenuCtx;
/** Key repeat wrapper functions. **/
#define FPAD_WRAPPER_REPEAT(Key) \
static inline int FPAD_##Key##_Repeat(MenuCtx *ctx) \
{ \
int ret = 0; \
if (FPAD_##Key(1)) { \
ret = (ctx->held.Key == 0 || ctx->held.Key > 10); \
ctx->held.Key++; \
} else { \
ctx->held.Key = 0; \
} \
return ret; \
}
FPAD_WRAPPER_REPEAT(Up)
FPAD_WRAPPER_REPEAT(Down)
FPAD_WRAPPER_REPEAT(Left)
FPAD_WRAPPER_REPEAT(Right)
/**
* Update the Game Select menu.
* @param ctx [in] Menu context.
* @return True to exit; false to continue.
*/
static bool UpdateGameSelectMenu(MenuCtx *ctx)
{
u32 i;
bool clearCheats = false;
if(FPAD_X(0))
{
// Can we show information for the selected game?
if (ctx->games.canShowInfo)
{
// Show game information.
ShowGameInfo(&ctx->games.gi[ctx->games.posX + ctx->games.scrollX]);
ctx->redraw = true;
}
}
if (FPAD_Down_Repeat(ctx))
{
// Down: Move the cursor down by 1 entry.
// Remove the current arrow.
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X+51*6-8, MENU_POS_Y + 20*6 + ctx->games.posX * 20, " " );
// Adjust the scrolling position.
if (ctx->games.posX + 1 >= ctx->games.listMax)
{
if (ctx->games.posX + 1 + ctx->games.scrollX < ctx->games.gamecount) {
// Need to adjust the scroll position.
ctx->games.scrollX++;
} else {
// Wraparound.
ctx->games.posX = 0;
ctx->games.scrollX = 0;
}
} else {
ctx->games.posX++;
}
clearCheats = true;
ctx->redraw = true;
ctx->saveSettings = true;
}
if (FPAD_Right_Repeat(ctx))
{
// Right: Move the cursor down by 1 page.
// Remove the current arrow.
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X+51*6-8, MENU_POS_Y + 20*6 + ctx->games.posX * 20, " " );
// Adjust the scrolling position.
if (ctx->games.posX == ctx->games.listMax - 1)
{
if (ctx->games.posX + ctx->games.listMax + ctx->games.scrollX < ctx->games.gamecount) {
ctx->games.scrollX += ctx->games.listMax;
} else if (ctx->games.posX + ctx->games.scrollX != ctx->games.gamecount - 1) {
ctx->games.scrollX = ctx->games.gamecount - ctx->games.listMax;
} else {
ctx->games.posX = 0;
ctx->games.scrollX = 0;
}
} else if(ctx->games.listMax) {
ctx->games.posX = ctx->games.listMax - 1;
}
else {
ctx->games.posX = 0;
}
clearCheats = true;
ctx->redraw = true;
ctx->saveSettings = true;
}
if (FPAD_Up_Repeat(ctx))
{
// Up: Move the cursor up by 1 entry.
// Remove the current arrow.
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X+51*6-8, MENU_POS_Y + 20*6 + ctx->games.posX * 20, " " );
// Adjust the scrolling position.
if (ctx->games.posX <= 0)
{
if (ctx->games.scrollX > 0) {
ctx->games.scrollX--;
} else {
// Wraparound.
if(ctx->games.listMax) {
ctx->games.posX = ctx->games.listMax - 1;
}
else {
ctx->games.posX = 0;
}
ctx->games.scrollX = ctx->games.gamecount - ctx->games.listMax;
}
} else {
ctx->games.posX--;
}
clearCheats = true;
ctx->redraw = true;
ctx->saveSettings = true;
}
if (FPAD_Left_Repeat(ctx))
{
// Left: Move the cursor up by 1 page.
// Remove the current arrow.
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X+51*6-8, MENU_POS_Y + 20*6 + ctx->games.posX * 20, " " );
// Adjust the scrolling position.
if (ctx->games.posX == 0)
{
if (ctx->games.scrollX - (s32)ctx->games.listMax >= 0) {
ctx->games.scrollX -= ctx->games.listMax;
} else if (ctx->games.scrollX != 0) {
ctx->games.scrollX = 0;
} else {
ctx->games.scrollX = ctx->games.gamecount - ctx->games.listMax;
}
} else {
ctx->games.posX = 0;
}
clearCheats = true;
ctx->redraw = true;
ctx->saveSettings = true;
}
if (FPAD_OK(0) && ctx->games.canBeBooted)
{
// User selected a game.
ctx->selected = true;
return true;
}
if (clearCheats)
{
if ((ncfg->Config & NIN_CFG_CHEATS) && (ncfg->Config & NIN_CFG_CHEAT_PATH))
{
// If a cheat path being used, clear it because it
// can't be correct for a different game.
ncfg->Config = ncfg->Config & ~(NIN_CFG_CHEATS | NIN_CFG_CHEAT_PATH);
}
}
if (ctx->redraw)
{
// Redraw the game list.
// TODO: Only if menuMode or scrollX has changed?
// Print the color codes.
PrintFormat(DEFAULT_SIZE, DiscFormatColors[0], MENU_POS_X, MENU_POS_Y + 20*3, "Colors : 1:1");
PrintFormat(DEFAULT_SIZE, DiscFormatColors[1], MENU_POS_X+(14*10), MENU_POS_Y + 20*3, "Shrunk");
PrintFormat(DEFAULT_SIZE, DiscFormatColors[2], MENU_POS_X+(21*10), MENU_POS_Y + 20*3, "FST");
PrintFormat(DEFAULT_SIZE, DiscFormatColors[3], MENU_POS_X+(25*10), MENU_POS_Y + 20*3, "CISO");
PrintFormat(DEFAULT_SIZE, DiscFormatColors[4], MENU_POS_X+(30*10), MENU_POS_Y + 20*3, "Multi");
// Starting position.
int gamelist_y = MENU_POS_Y + 20*5 + 10;
const gameinfo *gi = &ctx->games.gi[ctx->games.scrollX];
int gamesToPrint = ctx->games.gamecount - ctx->games.scrollX;
if (gamesToPrint > ctx->games.listMax) {
gamesToPrint = ctx->games.listMax;
}
for (i = 0; i < gamesToPrint; ++i, gamelist_y += 20, gi++)
{
// FIXME: Print all 64 characters of the game name?
// Currently truncated to 50.
// Determine color based on disc format.
// NOTE: On Wii, DISC01 is GIFLAG_FORMAT_FULL.
const u32 color = DiscFormatColors[gi->Flags & GIFLAG_FORMAT_MASK];
const u8 discNumber = ((gi->Flags & GIFLAG_DISCNUMBER_MASK) >> 5);
if (discNumber == 0)
{
// Disc 1.
PrintFormat(DEFAULT_SIZE, color, MENU_POS_X, gamelist_y,
"%50.50s [%.6s]%s",
gi->Name, gi->ID,
i == ctx->games.posX ? ARROW_LEFT : " ");
}
else
{
// Disc 2 or higher.
PrintFormat(DEFAULT_SIZE, color, MENU_POS_X, gamelist_y,
"%46.46s (%d) [%.6s]%s",
gi->Name, discNumber+1, gi->ID,
i == ctx->games.posX ? ARROW_LEFT : " ");
}
}
if(ctx->games.gamecount && (ctx->games.scrollX + ctx->games.posX) >= 0
&& (ctx->games.scrollX + ctx->games.posX) < ctx->games.gamecount)
{
ctx->games.canBeBooted = true;
// Can we show information for the selected title?
if (IsWiiU() && !isWiiVC) {
// Can show information for all games on WiiU
ctx->games.canShowInfo = true;
} else {
if ((ctx->games.scrollX + ctx->games.posX) == 0) {
// Cannot show information for DISC01 on Wii and Wii VC.
ctx->games.canShowInfo = false;
} else {
// Can show information for all other games.
ctx->games.canShowInfo = true;
}
}
if (ctx->games.canShowInfo) {
// Print the selected game's filename.
const gameinfo *const gi = &ctx->games.gi[ctx->games.scrollX + ctx->games.posX];
const int len = strlen(gi->Path);
const int x = (640 - (len*10)) / 2;
const u32 color = DiscFormatColors[gi->Flags & GIFLAG_FORMAT_MASK];
PrintFormat(DEFAULT_SIZE, color, x, MENU_POS_Y + 20*4+5, "%s", gi->Path);
}
}
else
{
//invalid title selected
ctx->games.canBeBooted = false;
ctx->games.canShowInfo = false;
}
// GRRLIB rendering is done by SelectGame().
}
return false;
}
/**
* Get a description for the Settings menu.
* @param ctx [in] Menu context.
* @return Description, or NULL if none is available.
*/
static const char *const *GetSettingsDescription(const MenuCtx *ctx)
{
if (ctx->settings.settingPart == 0)
{
switch (ctx->settings.posX)
{
case NIN_CFG_BIT_CHEATS:
case NIN_CFG_BIT_DEBUGGER:
case NIN_CFG_BIT_DEBUGWAIT:
break;
case NIN_CFG_BIT_MEMCARDEMU: {
static const char *desc_mcemu[] = {
"Emulates a memory card in",
"Slot A using a .raw file.",
"",
"Disable this option if you",
"want to use a real memory",
"card on an original Wii.",
NULL
};
return desc_mcemu;
}
case NIN_CFG_BIT_CHEAT_PATH:
break;
case NIN_CFG_BIT_FORCE_WIDE: {
static const char *const desc_force_wide[] = {
"Patch games to use a 16:9",
"aspect ratio. (widescreen)",
"",
"Not all games support this",
"option. The patches will not",
"be applied to games that have",
"built-in support for 16:9;",
"use the game's options screen",
"to configure the display mode.",
NULL
};
return desc_force_wide;
}
case NIN_CFG_BIT_FORCE_PROG: {
static const char *const desc_force_prog[] = {
"Patch games to always use 480p",
"(progressive scan) output.",
"",
"Requires component cables, or",
"an HDMI cable on Wii U.",
NULL
};
return desc_force_prog;
}
case NIN_CFG_BIT_AUTO_BOOT:
break;
case NIN_CFG_BIT_REMLIMIT: {
static const char *desc_remlimit[] = {
"Disc read speed is normally",
"limited to the performance of",
"the original GameCube disc",
"drive.",
"",
"Unlocking read speed can allow",
"for faster load times, but it",
"can cause problems with games",
"that are extremely sensitive",
"to disc read timing.",
NULL
};
return desc_remlimit;
}
case NIN_CFG_BIT_OSREPORT:
break;
case NIN_CFG_BIT_USB: { // WiiU Widescreen
static const char *desc_wiiu_widescreen[] = {
"On Wii U, Nintendont sets the",
"display to 4:3, which results",
"in bars on the sides of the",
"screen. If playing a game that",
"supports widescreen, enable",
"this option to set the display",
"back to 16:9.",
"",
"This option has no effect on",
"original Wii systems.",
NULL
};
return desc_wiiu_widescreen;
}
case NIN_CFG_BIT_LED: {
static const char *desc_led[] = {
"Use the drive slot LED as a",
"disk activity indicator.",
"",
"The LED will be turned on",
"when reading from or writing",
"to the storage device.",
"",
"This option has no effect on",
"Wii U, since the Wii U does",
"not have a drive slot LED.",
NULL
};
return desc_led;
}
case NIN_CFG_BIT_LOG:
break;
case NIN_SETTINGS_MAX_PADS: {
static const char *desc_max_pads[] = {
"Set the maximum number of",
"native GameCube controller",
"ports to use on Wii.",
"",
"This should usually be kept",
"at 4 to enable all ports",
"",
"This option has no effect on",
"Wii U and Wii Family Edition",
"systems.",
NULL
};
return desc_max_pads;
}
case NIN_SETTINGS_LANGUAGE: {
static const char *desc_language[] = {
"Set the system language.",
"",
"This option is normally only",
"found on PAL GameCubes, so",
"it usually won't have an",
"effect on NTSC games.",
NULL
};
return desc_language;
}
case NIN_SETTINGS_VIDEO:
case NIN_SETTINGS_VIDEOMODE:
break;
case NIN_SETTINGS_MEMCARDBLOCKS: {
static const char *desc_memcard_blocks[] = {
"Default size for new memory",
"card images.",
"",
"NOTE: Sizes larger than 251",
"blocks are known to cause",
"issues.",
NULL
};
return desc_memcard_blocks;
}
case NIN_SETTINGS_MEMCARDMULTI: {
static const char *desc_memcard_multi[] = {
"Nintendont usually uses one",
"emulated memory card image",
"per game.",
"",
"Enabling MULTI switches this",
"to use one memory card image",
"for all USA and PAL games,",
"and one image for all JPN",
"games.",
NULL
};
return desc_memcard_multi;
}
case NIN_SETTINGS_NATIVE_SI: {
static const char *desc_native_si[] = {
"Always enabled for Triples.",
"",
"The USB adapter is instead",
"used for players 5 and 6.",
NULL
};
return desc_native_si;
}
default:
break;
}
} else /*if (ctx->settings.settingPart == 1)*/ {
switch (ctx->settings.posX)
{
case 3: {
// Triforce Arcade Mode
static const char *desc_tri_arcade[] = {
"Arcade Mode re-enables the",
"coin slot functionality of",
"Triforce games.",
"",
"To insert a coin, move the",
"C stick in any direction.",
NULL
};
return desc_tri_arcade;
}
case 4: {
// Wiimote CC Rumble
static const char *desc_cc_rumble[] = {
"Enable rumble on Wii Remotes",
"when using the Wii Classic",
"Controller or Wii Classic",
"Controller Pro.",
NULL
};
return desc_cc_rumble;
}
case 5: {
// Skip IPL
static const char *desc_skip_ipl[] = {
"Skip loading the GameCube",
"IPL, even if it's present",
"on the storage device.",
NULL
};
return desc_skip_ipl;
}
case 6: {
// BBA Emulation
static const char *desc_skip_bba[] = {
"Enable BBA Emulation in the",
"following supported titles",
"including all their regions:",
"",
"Mario Kart: Double Dash!!",
"Kirby Air Ride",
"1080 Avalanche",
"PSO Episode 1&2",
"PSO Episode III",
"Homeland",
NULL
};
return desc_skip_bba;
}
case 7: {
// BBA Network Profile
static const char *desc_skip_netprof[] = {
"Force a Network Profile",
"to use for BBA Emulation,",
"this option only works on",
"the original Wii because",
"on Wii U the profiles are",
"managed by the Wii U Menu.",
"This means you can even",
"use profiles that cannot",
"connect to the internet.",
NULL
};
return desc_skip_netprof;
}
default:
break;
}
}
// No description is available.
return NULL;
}
/**
* Update the Settings menu.
* @param ctx [in] Menu context.
* @return True to exit; false to continue.
*/
static bool UpdateSettingsMenu(MenuCtx *ctx)
{
if(FPAD_X(0))
{
// Start the updater.
UpdateNintendont();
ctx->redraw = 1;
}
if (FPAD_Down_Repeat(ctx))
{
// Down: Move the cursor down by 1 setting.
if (ctx->settings.settingPart == 0) {
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+30, SettingY(ctx->settings.posX), " " );
} else {
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+300, SettingY(ctx->settings.posX), " " );
}
ctx->settings.posX++;
if (ctx->settings.settingPart == 0)
{
// Some items are hidden if certain values aren't set.
if (((ncfg->VideoMode & NIN_VID_FORCE) == 0) &&
(ctx->settings.posX == NIN_SETTINGS_VIDEOMODE))
{
ctx->settings.posX++;
}
if ((!(ncfg->Config & NIN_CFG_MEMCARDEMU)) &&
(ctx->settings.posX == NIN_SETTINGS_MEMCARDBLOCKS))
{
ctx->settings.posX++;
}
if ((!(ncfg->Config & NIN_CFG_MEMCARDEMU)) &&
(ctx->settings.posX == NIN_SETTINGS_MEMCARDMULTI))
{
ctx->settings.posX++;
}
}
// Check for wraparound.
if ((ctx->settings.settingPart == 0 && ctx->settings.posX >= NIN_SETTINGS_LAST) ||
(ctx->settings.settingPart == 1 && ctx->settings.posX >= 9))
{
ctx->settings.posX = 0;
ctx->settings.settingPart ^= 1;
}
ctx->redraw = true;
}
else if (FPAD_Up_Repeat(ctx))
{
// Up: Move the cursor up by 1 setting.
if (ctx->settings.settingPart == 0) {
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+30, SettingY(ctx->settings.posX), " " );
} else {
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+300, SettingY(ctx->settings.posX), " " );
}
ctx->settings.posX--;
// Check for wraparound.
if (ctx->settings.posX < 0)
{
ctx->settings.settingPart ^= 1;
if (ctx->settings.settingPart == 0) {
ctx->settings.posX = NIN_SETTINGS_LAST - 1;
} else {
ctx->settings.posX = 8;
}
}
if (ctx->settings.settingPart == 0)
{
// Some items are hidden if certain values aren't set.
if ((!(ncfg->Config & NIN_CFG_MEMCARDEMU)) &&
(ctx->settings.posX == NIN_SETTINGS_MEMCARDMULTI))
{
ctx->settings.posX--;
}
if ((!(ncfg->Config & NIN_CFG_MEMCARDEMU)) &&
(ctx->settings.posX == NIN_SETTINGS_MEMCARDBLOCKS))
{
ctx->settings.posX--;
}
if (((ncfg->VideoMode & NIN_VID_FORCE) == 0) &&
(ctx->settings.posX == NIN_SETTINGS_VIDEOMODE))
{
ctx->settings.posX--;
}
}
ctx->redraw = true;
}
if (FPAD_Left_Repeat(ctx))
{
// Left: Decrement a setting. (Right column only.)
if (ctx->settings.settingPart == 1)
{
ctx->saveSettings = true;
switch (ctx->settings.posX)
{
case 0:
// Video width.
if (ncfg->VideoScale == 0) {
ncfg->VideoScale = 120;
} else {
ncfg->VideoScale -= 2;
if (ncfg->VideoScale < 40 || ncfg->VideoScale > 120) {
ncfg->VideoScale = 0; //auto
}
}
ReconfigVideo(rmode);
ctx->redraw = true;
break;
case 1:
// Screen position.
ncfg->VideoOffset--;
if (ncfg->VideoOffset < -20 || ncfg->VideoOffset > 20) {
ncfg->VideoOffset = 20;
}
ReconfigVideo(rmode);
ctx->redraw = true;
break;
default:
break;
}
}
}
else if (FPAD_Right_Repeat(ctx))
{
// Right: Increment a setting. (Right column only.)
if (ctx->settings.settingPart == 1)
{
ctx->saveSettings = true;
switch (ctx->settings.posX)
{
case 0:
// Video width.
if(ncfg->VideoScale == 0) {
ncfg->VideoScale = 40;
} else {
ncfg->VideoScale += 2;
if (ncfg->VideoScale < 40 || ncfg->VideoScale > 120) {
ncfg->VideoScale = 0; //auto
}
}
ReconfigVideo(rmode);
ctx->redraw = true;
break;
case 1:
// Screen position.
ncfg->VideoOffset++;
if (ncfg->VideoOffset < -20 || ncfg->VideoOffset > 20) {
ncfg->VideoOffset = -20;
}
ReconfigVideo(rmode);
ctx->redraw = true;
break;
default:
break;
}
}
}
if( FPAD_OK(0) )
{
// A: Adjust the setting.
if (ctx->settings.settingPart == 0)
{
// Left column.
ctx->saveSettings = true;
if (ctx->settings.posX < NIN_CFG_BIT_LAST)
{
// Standard boolean setting.
if (ctx->settings.posX == NIN_CFG_BIT_CHEATS
|| ctx->settings.posX == NIN_CFG_BIT_CHEAT_PATH) {
// Disabled by triples.
} else if (ctx->settings.posX == NIN_CFG_BIT_USB) {
// USB option is replaced with Wii U widescreen.
ncfg->Config ^= NIN_CFG_WIIU_WIDE;
} else {
ncfg->Config ^= (1 << ctx->settings.posX);
}
}
else switch (ctx->settings.posX)
{
case NIN_SETTINGS_MAX_PADS:
// Maximum native controllers.
// Not available on Wii U.
/*
ncfg->MaxPads++;
if (ncfg->MaxPads > NIN_CFG_MAXPAD) {
ncfg->MaxPads = 0;
}
*/
break;
case NIN_SETTINGS_LANGUAGE:
ncfg->Language++;
if (ncfg->Language > NIN_LAN_DUTCH) {
ncfg->Language = NIN_LAN_AUTO;
}
break;
case NIN_SETTINGS_VIDEO:
{
u32 Video = (ncfg->VideoMode & NIN_VID_MASK);
switch (Video)
{
case NIN_VID_AUTO:
Video = NIN_VID_FORCE;
break;
case NIN_VID_FORCE:
Video = NIN_VID_FORCE | NIN_VID_FORCE_DF;
break;
case NIN_VID_FORCE | NIN_VID_FORCE_DF:
Video = NIN_VID_NONE;
break;
default:
case NIN_VID_NONE:
Video = NIN_VID_AUTO;
break;
}
ncfg->VideoMode &= ~NIN_VID_MASK;
ncfg->VideoMode |= Video;
break;
}
case NIN_SETTINGS_VIDEOMODE:
{
u32 Video = (ncfg->VideoMode & NIN_VID_FORCE_MASK);
Video = Video << 1;
if (Video > NIN_VID_FORCE_MPAL) {
Video = NIN_VID_FORCE_PAL50;
}
ncfg->VideoMode &= ~NIN_VID_FORCE_MASK;
ncfg->VideoMode |= Video;
break;
}
case NIN_SETTINGS_MEMCARDBLOCKS:
ncfg->MemCardBlocks++;
if (ncfg->MemCardBlocks > MEM_CARD_MAX) {
ncfg->MemCardBlocks = 0;
}
break;
case NIN_SETTINGS_MEMCARDMULTI:
ncfg->Config ^= (NIN_CFG_MC_MULTI);
break;
case NIN_SETTINGS_NATIVE_SI:
//ncfg->Config ^= (NIN_CFG_NATIVE_SI);
break;
default:
break;
}
// Blank out the memory card options if MCEMU is disabled.
if (!(ncfg->Config & NIN_CFG_MEMCARDEMU))
{
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 50, SettingY(NIN_SETTINGS_MEMCARDBLOCKS), "%29s", "");
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 50, SettingY(NIN_SETTINGS_MEMCARDMULTI), "%29s", "");
}
ctx->redraw = true;
}
else if (ctx->settings.settingPart == 1)
{
// Right column.
switch (ctx->settings.posX) {
case 2:
// PAL50 patch.
ctx->saveSettings = true;
ncfg->VideoMode ^= (NIN_VID_PATCH_PAL50);
ctx->redraw = true;
break;
case 3:
// Triforce Arcade Mode.
/*
ctx->saveSettings = true;
ncfg->Config ^= (NIN_CFG_ARCADE_MODE);
ctx->redraw = true;
*/
break;
case 4:
// Wiimote CC Rumble
/*
ctx->saveSettings = true;
ncfg->Config ^= (NIN_CFG_CC_RUMBLE);
ctx->redraw = true;
*/
break;
case 5:
// Skip IPL
ctx->saveSettings = true;
ncfg->Config ^= (NIN_CFG_SKIP_IPL);
ctx->redraw = true;
break;
case 6:
// BBA Emulation
/*
ctx->saveSettings = true;
ncfg->Config ^= (NIN_CFG_BBA_EMU);
ctx->redraw = true;
*/
break;
case 7:
// BBA Network Profile
/*
ctx->saveSettings = true;
ncfg->NetworkProfile++;
ncfg->NetworkProfile &= 3;
ctx->redraw = true;
*/
break;
case 8:
// Wii U Gamepad Slot
ctx->saveSettings = true;
ncfg->WiiUGamepadSlot++;
if (ncfg->WiiUGamepadSlot > NIN_CFG_MAXPAD) {
ncfg->WiiUGamepadSlot = 0;
}
ctx->redraw = true;
break;
default:
break;
}
}
}
if (ctx->redraw)
{
// Redraw the settings menu.
u32 ListLoopIndex = 0;
// Standard boolean settings.
for (ListLoopIndex = 0; ListLoopIndex < NIN_CFG_BIT_LAST; ListLoopIndex++)
{
if (ListLoopIndex == NIN_CFG_BIT_USB) {
// USB option is replaced with Wii U widescreen.
PrintFormat(MENU_SIZE, (IsWiiU() ? BLACK : DARK_GRAY), MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%s", OptionStrings[ListLoopIndex], (ncfg->Config & (NIN_CFG_WIIU_WIDE)) ? "On " : "Off");
} else {
u32 item_color = BLACK;
if (IsWiiU() &&
(ListLoopIndex == NIN_CFG_BIT_DEBUGGER ||
ListLoopIndex == NIN_CFG_BIT_DEBUGWAIT ||
ListLoopIndex == NIN_CFG_BIT_LED))
{
// These options are only available on Wii.
item_color = DARK_GRAY;
}
// Options disabled by triples.
switch (ListLoopIndex) {
case NIN_CFG_BIT_CHEATS:
case NIN_CFG_BIT_CHEAT_PATH:
item_color = DARK_GRAY;
}
PrintFormat(MENU_SIZE, item_color, MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%s", OptionStrings[ListLoopIndex], (ncfg->Config & (1 << ListLoopIndex)) ? "On " : "Off" );
}
}
// Maximum number of emulated controllers.
// Not available on Wii U.
// TODO: Disable on RVL-101?
PrintFormat(MENU_SIZE, DARK_GRAY, MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%d", OptionStrings[ListLoopIndex], (ncfg->MaxPads));
ListLoopIndex++;
// Language setting.
u32 LanIndex = ncfg->Language;
if (LanIndex < NIN_LAN_FIRST || LanIndex >= NIN_LAN_LAST) {
LanIndex = NIN_LAN_LAST; //Auto
}
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%-4s", OptionStrings[ListLoopIndex], LanguageStrings[LanIndex] );
ListLoopIndex++;
// Video mode forcing.
u32 VideoModeIndex;
u32 VideoModeVal = ncfg->VideoMode & NIN_VID_MASK;
switch (VideoModeVal)
{
case NIN_VID_AUTO:
VideoModeIndex = NIN_VID_INDEX_AUTO;
break;
case NIN_VID_FORCE:
VideoModeIndex = NIN_VID_INDEX_FORCE;
break;
case NIN_VID_FORCE | NIN_VID_FORCE_DF:
VideoModeIndex = NIN_VID_INDEX_FORCE_DF;
break;
case NIN_VID_NONE:
VideoModeIndex = NIN_VID_INDEX_NONE;
break;
default:
ncfg->VideoMode &= ~NIN_VID_MASK;
ncfg->VideoMode |= NIN_VID_AUTO;
VideoModeIndex = NIN_VID_INDEX_AUTO;
break;
}
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%-18s", OptionStrings[ListLoopIndex], VideoStrings[VideoModeIndex] );
ListLoopIndex++;
if( ncfg->VideoMode & NIN_VID_FORCE )
{
// Video mode selection.
// Only available if video mode is Force or Force (Deflicker).
VideoModeVal = ncfg->VideoMode & NIN_VID_FORCE_MASK;
u32 VideoTestVal = NIN_VID_FORCE_PAL50;
for (VideoModeIndex = 0; (VideoTestVal <= NIN_VID_FORCE_MPAL) && (VideoModeVal != VideoTestVal); VideoModeIndex++) {
VideoTestVal <<= 1;
}
if ( VideoModeVal < VideoTestVal )
{
ncfg->VideoMode &= ~NIN_VID_FORCE_MASK;
ncfg->VideoMode |= NIN_VID_FORCE_NTSC;
VideoModeIndex = NIN_VID_INDEX_FORCE_NTSC;
}
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X+50, SettingY(ListLoopIndex),
"%-18s:%-5s", OptionStrings[ListLoopIndex], VideoModeStrings[VideoModeIndex] );
}
ListLoopIndex++;
// Memory card emulation.
if ((ncfg->Config & NIN_CFG_MEMCARDEMU) == NIN_CFG_MEMCARDEMU)
{
u32 MemCardBlocksVal = ncfg->MemCardBlocks;
if (MemCardBlocksVal > MEM_CARD_MAX) {
MemCardBlocksVal = 0;
}
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 50, SettingY(ListLoopIndex),
"%-18s:%-4d%s", OptionStrings[ListLoopIndex], MEM_CARD_BLOCKS(MemCardBlocksVal), MemCardBlocksVal > 2 ? "Unstable" : "");
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 50, SettingY(ListLoopIndex+1),
"%-18s:%-4s", OptionStrings[ListLoopIndex+1], (ncfg->Config & (NIN_CFG_MC_MULTI)) ? "On " : "Off");
}
ListLoopIndex+=2;
// Native controllers. (Required for GBA link; disables Bluetooth and USB HID.)
// TODO: Gray out on RVL-101?
PrintFormat(MENU_SIZE, DARK_GRAY, MENU_POS_X + 50, SettingY(ListLoopIndex),
"%-18s:%-4s", OptionStrings[ListLoopIndex],
"On");
ListLoopIndex++;
/** Right column **/
ListLoopIndex = 0; //reset on other side
// Video width.
char vidWidth[10];
if (ncfg->VideoScale < 40 || ncfg->VideoScale > 120) {
ncfg->VideoScale = 0;
snprintf(vidWidth, sizeof(vidWidth), "Auto");
} else {
snprintf(vidWidth, sizeof(vidWidth), "%i", ncfg->VideoScale + 600);
}
char vidOffset[10];
if (ncfg->VideoOffset < -20 || ncfg->VideoOffset > 20) {
ncfg->VideoOffset = 0;
}
snprintf(vidOffset, sizeof(vidOffset), "%i", ncfg->VideoOffset);
char netProfile[5];
ncfg->NetworkProfile &= 3;
if(ncfg->NetworkProfile == 0)
snprintf(netProfile, sizeof(netProfile), "Auto");
else
snprintf(netProfile, sizeof(netProfile), "%i", ncfg->NetworkProfile);
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Video Width", vidWidth);
ListLoopIndex++;
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Screen Position", vidOffset);
ListLoopIndex++;
// Patch PAL60.
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Patch PAL50", (ncfg->VideoMode & (NIN_VID_PATCH_PAL50)) ? "On " : "Off");
ListLoopIndex++;
// Triforce Arcade Mode.
PrintFormat(MENU_SIZE, DARK_GRAY, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "TRI Arcade Mode", (ncfg->Config & (NIN_CFG_ARCADE_MODE)) ? "On " : "Off");
ListLoopIndex++;
// Wiimote CC Rumble
PrintFormat(MENU_SIZE, DARK_GRAY, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Wiimote CC Rumble", (ncfg->Config & (NIN_CFG_CC_RUMBLE)) ? "On " : "Off");
ListLoopIndex++;
// Skip GameCube IPL
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Skip IPL", (ncfg->Config & (NIN_CFG_SKIP_IPL)) ? "Yes" : "No ");
ListLoopIndex++;
// BBA Emulation
PrintFormat(MENU_SIZE, DARK_GRAY, MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "BBA Emulation", (ncfg->Config & (NIN_CFG_BBA_EMU)) ? "On" : "Off");
ListLoopIndex++;
// BBA Network Profile
PrintFormat(MENU_SIZE, (IsWiiU() || !(ncfg->Config & (NIN_CFG_BBA_EMU))) ? DARK_GRAY : BLACK,
MENU_POS_X + 320, SettingY(ListLoopIndex),
"%-18s:%-4s", "Network Profile", netProfile);
ListLoopIndex++;
// Controller slot for the Wii U gamepad.
if (ncfg->WiiUGamepadSlot < NIN_CFG_MAXPAD) {
PrintFormat(MENU_SIZE, (IsWiiU() ? BLACK : DARK_GRAY), MENU_POS_X+320, SettingY(ListLoopIndex),
"%-18s:%d", "WiiU Gamepad Slot", (ncfg->WiiUGamepadSlot + 1));
} else {
PrintFormat(MENU_SIZE, (IsWiiU() ? BLACK : DARK_GRAY), MENU_POS_X+320, SettingY(ListLoopIndex),
"%-18s:%-4s", "WiiU Gamepad Slot", "None");
}
ListLoopIndex++;
// Draw the cursor.
u32 cursor_color = BLACK;
if (ctx->settings.settingPart == 0) {
if ((!IsWiiU() && ctx->settings.posX == NIN_CFG_BIT_USB) ||
(ctx->settings.posX == NIN_CFG_NATIVE_SI))
{
// Setting is not usable on this platform.
// Gray out the cursor, too.
cursor_color = DARK_GRAY;
}
PrintFormat(MENU_SIZE, cursor_color, MENU_POS_X + 30, SettingY(ctx->settings.posX), ARROW_RIGHT);
} else {
if((IsWiiU() || !(ncfg->Config & (NIN_CFG_BBA_EMU))) && ctx->settings.posX == 7)
cursor_color = DARK_GRAY;
PrintFormat(MENU_SIZE, cursor_color, MENU_POS_X + 300, SettingY(ctx->settings.posX), ARROW_RIGHT);
}
// Print a description for the selected option.
// desc contains pointers to lines, and is
// terminated with NULL.
const char *const *desc = GetSettingsDescription(ctx);
if (desc != NULL)
{
int line_num = 9;
do {
if (**desc != 0)
{
PrintFormat(MENU_SIZE, BLACK, MENU_POS_X + 300, SettingY(line_num), *desc);
}
line_num++;
} while (*(++desc) != NULL);
}
// GRRLIB rendering is done by SelectGame().
}
return false;
}
/**
* Select a game from the specified device.
* @return Bitfield indicating the user's selection:
* - 0 == go back
* - 1 == game selected
* - 2 == go back and save settings (UNUSED)
* - 3 == game selected and save settings
*/
static int SelectGame(void)
{
// Depending on how many games are on the storage device,
// this could take a while.
ShowLoadingScreen();
// Load the game list.
u32 gamecount = 0;
gameinfo gi[MAX_GAMES];
devState = LoadGameList(&gi[0], MAX_GAMES, &gamecount);
switch (devState)
{
case DEV_OK:
// Game list loaded successfully.
break;
case DEV_NO_GAMES:
// No "games" directory was found.
// The list will still be shown, since there's a
// "Boot GC Disc in Drive" option on Wii.
gprintf("WARNING: %s:/games/ was not found.\n", GetRootDevice());
break;
case DEV_NO_TITLES:
// "games" directory appears to be empty.
// The list will still be shown, since there's a
// "Boot GC Disc in Drive" option on Wii.
gprintf("WARNING: %s:/games/ contains no GC titles.\n", GetRootDevice());
break;
case DEV_NO_OPEN:
default:
{
// Could not open the device at all.
// The list won't be shown, since a storage device
// is required for various functionality, but the
// user will be able to go back to the previous menu.
const char *s_devType = (UseSD ? "SD" : "USB");
gprintf("No %s FAT device found.\n", s_devType);
break;
}
}
// Initialize the menu context.
MenuCtx ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.menuMode = 0; // Start in the games list.
ctx.redraw = true; // Redraw initially.
ctx.selected = false; // Set to TRUE if the user selected a game.
ctx.saveSettings = false;
// Initialize ctx.games.
ctx.games.listMax = gamecount;
if (ctx.games.listMax > 15) {
ctx.games.listMax = 15;
}
ctx.games.gi = gi;
ctx.games.gamecount = gamecount;
// Set the default game to the game that's currently set
// in the configuration.
u32 i;
for (i = 0; i < gamecount; ++i)
{
if (strcasecmp(strchr(gi[i].Path,':')+1, ncfg->GamePath) == 0)
{
if (i >= ctx.games.listMax) {
// Need to adjust the scroll position.
ctx.games.posX = ctx.games.listMax - 1;
ctx.games.scrollX = i - ctx.games.listMax + 1;
} else {
// Game is on the first page.
// No scroll position adjustment is required.
ctx.games.posX = i;
}
break;
}
}
while(1)
{
VIDEO_WaitVSync();
FPAD_Update();
if(Shutdown)
LoaderShutdown();
if( FPAD_Start(0) )
{
// Go back to the Device Select menu.
ctx.selected = false;
break;
}
if( FPAD_Cancel(0) )
{
// Switch menu modes.
ctx.menuMode = !ctx.menuMode;
memset(&ctx.held, 0, sizeof(ctx.held));
if (ctx.menuMode == 1)
{
// Reset the settings position.
ctx.settings.posX = 0;
ctx.settings.settingPart = 0;
}
ctx.redraw = 1;
}
bool ret = false;
if (ctx.menuMode == 0) {
// Game Select menu.
ret = UpdateGameSelectMenu(&ctx);
} else {
// Settings menu.
ret = UpdateSettingsMenu(&ctx);
}
if (ret)
{
// User has exited the menu.
break;
}
if (ctx.redraw)
{
// Redraw the header.
PrintInfo();
if (ctx.menuMode == 0)
{
// Game List menu.
PrintButtonActions("Go Back", NULL, "Settings", NULL);
// If the selected game bootable, enable "Select".
u32 color = ((ctx.games.canBeBooted) ? BLACK : DARK_GRAY);
PrintFormat(DEFAULT_SIZE, color, MENU_POS_X + 430, MENU_POS_Y + 20*1, "A : Select");
// If the selected game is not DISC01, enable "Game Info".
color = ((ctx.games.canShowInfo) ? BLACK : DARK_GRAY);
PrintFormat(DEFAULT_SIZE, color, MENU_POS_X + 430, MENU_POS_Y + 20*3, "X/1 : Game Info");
}
else
{
// Settings menu.
PrintButtonActions("Go Back", "Select", "Settings", "Update");
}
if (ctx.menuMode == 0 ||
(ctx.menuMode == 1 && devState == DEV_OK))
{
// FIXME: If devState != DEV_OK,
// the device info overlaps with the settings menu.
PrintDevInfo();
}
// Render the screen.
GRRLIB_Render();
Screenshot();
ClearScreen();
ctx.redraw = false;
}
}
if(ctx.games.canBeBooted)
{
// Save the selected game to the configuration.
u32 SelectedGame = ctx.games.posX + ctx.games.scrollX;
const char* StartChar = gi[SelectedGame].Path + 3;
if (StartChar[0] == ':') {
StartChar++;
}
strncpy(ncfg->GamePath, StartChar, sizeof(ncfg->GamePath));
ncfg->GamePath[sizeof(ncfg->GamePath)-1] = 0;
memcpy(&(ncfg->GameID), gi[SelectedGame].ID, 4);
DCFlushRange((void*)ncfg, sizeof(NIN_CFG));
}
// Free allocated memory in the game list.
for (i = 0; i < gamecount; ++i)
{
if (gi[i].Flags & GIFLAG_NAME_ALLOC)
free(gi[i].Name);
free(gi[i].Path);
}
if (!ctx.selected)
{
// No game selected.
return 0;
}
// Game is selected.
// TODO: Return an enum.
return (ctx.saveSettings ? 3 : 1);
}
/**
* Select the source device and game.
* @return TRUE to save settings; FALSE if no settings have been changed.
*/
bool SelectDevAndGame(void)
{
// Select the source device. (SD or USB)
bool SaveSettings = false;
bool redraw = true; // Need to draw the menu the first time.
while (1)
{
VIDEO_WaitVSync();
FPAD_Update();
if(Shutdown)
LoaderShutdown();
if (redraw)
{
UseSD = (ncfg->Config & NIN_CFG_USB) == 0;
PrintInfo();
PrintButtonActions("Exit", "Select", NULL, NULL);
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 53 * 6 - 8, MENU_POS_Y + 20 * 6, UseSD ? ARROW_LEFT : "");
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 53 * 6 - 8, MENU_POS_Y + 20 * 7, UseSD ? "" : ARROW_LEFT);
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 47 * 6 - 8, MENU_POS_Y + 20 * 6, " SD ");
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 47 * 6 - 8, MENU_POS_Y + 20 * 7, "USB ");
redraw = false;
// Render the screen here to prevent a blank frame
// when returning from SelectGame().
GRRLIB_Render();
ClearScreen();
}
if (FPAD_OK(0))
{
// Select a game from the specified device.
int ret = SelectGame();
if (ret & 2) SaveSettings = true;
if (ret & 1) break;
redraw = true;
}
else if (FPAD_Start(0))
{
ShowMessageScreenAndExit("Returning to loader...", 0);
}
else if (FPAD_Down(0))
{
ncfg->Config = ncfg->Config | NIN_CFG_USB;
redraw = true;
}
else if (FPAD_Up(0))
{
ncfg->Config = ncfg->Config & ~NIN_CFG_USB;
redraw = true;
}
}
return SaveSettings;
}
/**
* Show a single message screen.
* @param msg Message.
*/
void ShowMessageScreen(const char *msg)
{
const int len = strlen(msg);
const int x = (640 - (len*10)) / 2;
ClearScreen();
PrintInfo();
PrintFormat(DEFAULT_SIZE, BLACK, x, 232, "%s", msg);
GRRLIB_Render();
ClearScreen();
}
/**
* Show a single message screen and then exit to loader..
* @param msg Message.
* @param ret Return value. If non-zero, text will be printed in red.
*/
void ShowMessageScreenAndExit(const char *msg, int ret)
{
const int len = strlen(msg);
const int x = (640 - (len*10)) / 2;
const u32 color = (ret == 0 ? BLACK : MAROON);
ClearScreen();
PrintInfo();
PrintFormat(DEFAULT_SIZE, color, x, 232, "%s", msg);
ExitToLoader(ret);
}
/**
* Print Nintendont version and system hardware information.
*/
void PrintInfo(void)
{
const char *consoleType = (isWiiVC ? (IsWiiUFastCPU() ? "WiiVC 5x CPU" : "Wii VC") : (IsWiiUFastCPU() ? "WiiU 5x CPU" : (IsWiiU() ? "Wii U" : "Wii")));
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X, MENU_POS_Y + 20*0, "SSBM Triples v0.4.2");
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X, MENU_POS_Y + 20*1, "Built : " __DATE__ " " __TIME__);
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X, MENU_POS_Y + 20*2, "Firmware: %s %u.%u.%u",
consoleType, *(vu16*)0x80003140, *(vu8*)0x80003142, *(vu8*)0x80003143);
}
/**
* Print button actions.
* Call this function after PrintInfo().
*
* If any button action is NULL, that button won't be displayed.
*
* @param btn_home [in,opt] Home button action.
* @param btn_a [in,opt] A button action.
* @param btn_b [in,opt] B button action.
* @param btn_x1 [in,opt] X/1 button action.
*/
void PrintButtonActions(const char *btn_home, const char *btn_a, const char *btn_b, const char *btn_x1)
{
if (btn_home) {
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 430, MENU_POS_Y + 20*0, "Home: %s", btn_home);
}
if (btn_a) {
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 430, MENU_POS_Y + 20*1, "A : %s", btn_a);
}
if (btn_b) {
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 430, MENU_POS_Y + 20*2, "B : %s", btn_b);
}
if (btn_x1) {
PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + 430, MENU_POS_Y + 20*3, "X/1 : %s", btn_x1);
}
}
/**
* Print information about the selected device.
*/
static void PrintDevInfo(void)
{
// Device type.
const char *s_devType = (UseSD ? "SD" : "USB");
// Device state.
// NOTE: If this is showing a message, the game list
// will be moved down by 1 row, which usually isn't
// a problem, since it will either be empty or showing
// "Boot GC Disc in Drive".
switch (devState) {
case DEV_NO_OPEN:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*4,
"WARNING: %s FAT device could not be opened.", s_devType);
break;
case DEV_NO_GAMES:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*4,
"WARNING: %s:/games/ was not found.", GetRootDevice());
break;
case DEV_NO_TITLES:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*4,
"WARNING: %s:/games/ contains no GC titles.", GetRootDevice());
break;
default:
break;
}
}
void ReconfigVideo(GXRModeObj *vidmode)
{
if(ncfg->VideoScale >= 40 && ncfg->VideoScale <= 120)
vidmode->viWidth = ncfg->VideoScale + 600;
else
vidmode->viWidth = 640;
vidmode->viXOrigin = (720 - vidmode->viWidth) / 2;
if(ncfg->VideoOffset >= -20 && ncfg->VideoOffset <= 20)
{
if((vidmode->viXOrigin + ncfg->VideoOffset) < 0)
vidmode->viXOrigin = 0;
else if((vidmode->viXOrigin + ncfg->VideoOffset) > 80)
vidmode->viXOrigin = 80;
else
vidmode->viXOrigin += ncfg->VideoOffset;
}
VIDEO_Configure(vidmode);
}
/**
* Print a LoadKernel() error message.
*
* This function does NOT force a return to loader;
* that must be handled by the caller.
* Caller must also call UpdateScreen().
*
* @param iosErr IOS loading error ID.
* @param err Return value from the IOS function.
*/
void PrintLoadKernelError(LoadKernelError_t iosErr, int err)
{
ClearScreen();
PrintInfo();
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*4, "Failed to load IOS58 from NAND:");
switch (iosErr)
{
case LKERR_UNKNOWN:
default:
// TODO: Add descriptions of more LoadKernel() errors.
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "LoadKernel() error %d occurred, returning %d.", iosErr, err);
break;
case LKERR_ES_GetStoredTMDSize:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "ES_GetStoredTMDSize() returned %d.", err);
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*7, "This usually means IOS58 is not installed.");
if (IsWiiU())
{
// No IOS58 on Wii U should never happen...
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*9, "WARNING: On Wii U, a missing IOS58 may indicate");
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*10, "something is seriously wrong with the vWii setup.");
}
else
{
// TODO: Check if we're using System 4.3.
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*9, "Please update to Wii System 4.3 and try running");
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*10, "Nintendont again.");
}
break;
case LKERR_TMD_malloc:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "Unable to allocate memory for the IOS58 TMD.");
break;
case LKERR_ES_GetStoredTMD:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "ES_GetStoredTMD() returned %d.", err);
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*7, "WARNING: IOS58 may be corrupted.");
break;
case LKERR_IOS_Open_shared1_content_map:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "IOS_Open(\"/shared1/content.map\") returned %d.", err);
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*7, "This usually means Nintendont was not started with");
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*8, "AHB access permissions.");
// FIXME: Create meta.xml if it isn't there?
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*10, "Please ensure that meta.xml is present in your Nintendont");
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*11, "application directory and that it contains a line");
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*12, "with the tag <ahb_access/> .");
break;
case LKERR_IOS_Open_IOS58_kernel:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "IOS_Open(IOS58 kernel) returned %d.", err);
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*7, "WARNING: IOS58 may be corrupted.");
break;
case LKERR_IOS_Read_IOS58_kernel:
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*5, "IOS_Read(IOS58 kernel) returned %d.", err);
PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, MENU_POS_Y + 20*7, "WARNING: IOS58 may be corrupted.");
break;
}
}
| 0 | 0.909674 | 1 | 0.909674 | game-dev | MEDIA | 0.834462 | game-dev | 0.944076 | 1 | 0.944076 |
opentibiabr/otservbr-global | 1,511 | data/scripts/creaturescripts/quests/heart_of_destruction/eradicator_transform.lua | local eradicatorTransform = CreatureEvent("EradicatorTransform")
function eradicatorTransform.onThink(creature)
if not creature or not creature:isMonster() then
return false
end
if eradicatorReleaseT == true then
if eradicatorWeak == 0 then
local pos = creature:getPosition()
local health = creature:getHealth()
creature:remove()
local monster = Game.createMonster("eradicator2", pos, false, true)
monster:addHealth(-monster:getHealth() + health, COMBAT_PHYSICALDAMAGE)
Game.createMonster("spark of destruction", {x = 32304, y = 31282, z = 14}, false, true)
Game.createMonster("spark of destruction", {x = 32305, y = 31287, z = 14}, false, true)
Game.createMonster("spark of destruction", {x = 32312, y = 31287, z = 14}, false, true)
Game.createMonster("spark of destruction", {x = 32314, y = 31282, z = 14}, false, true)
eradicatorWeak = 1 -- Eradicator form
eradicatorReleaseT = false -- Release spell
areaEradicator2 = addEvent(function() eradicatorReleaseT = true end, 9000)
elseif eradicatorWeak == 1 then
local pos = creature:getPosition()
local health = creature:getHealth()
creature:remove()
local monster = Game.createMonster("eradicator", pos, false, true)
monster:addHealth(-monster:getHealth() + health, COMBAT_PHYSICALDAMAGE)
eradicatorWeak = 0
eradicatorReleaseT = false -- Release spell
areaEradicator2 = addEvent(function() eradicatorReleaseT = true end, 74000)
end
end
return true
end
eradicatorTransform:register()
| 0 | 0.769834 | 1 | 0.769834 | game-dev | MEDIA | 0.988541 | game-dev | 0.829283 | 1 | 0.829283 |
00-Evan/shattered-pixel-dungeon | 2,041 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/ui/Compass.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.ui;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.tiles.DungeonTilemap;
import com.watabou.noosa.Camera;
import com.watabou.noosa.Image;
import com.watabou.utils.PointF;
public class Compass extends Image {
private static final float RAD_2_G = 180f / 3.1415926f;
private static final float RADIUS = 12;
private int cell;
private PointF cellCenter;
private PointF lastScroll = new PointF();
public Compass( int cell ) {
super();
copy( Icons.COMPASS.get() );
origin.set( width / 2, RADIUS );
this.cell = cell;
cellCenter = DungeonTilemap.tileCenterToWorld( cell );
visible = false;
}
@Override
public void update() {
super.update();
if (cell < 0 || cell >= Dungeon.level.length()){
visible = false;
return;
}
if (!visible) {
visible = Dungeon.level.visited[cell] || Dungeon.level.mapped[cell];
}
if (visible) {
PointF scroll = Camera.main.scroll;
if (!scroll.equals( lastScroll )) {
lastScroll.set( scroll );
PointF center = Camera.main.center().offset( scroll );
angle = (float)Math.atan2( cellCenter.x - center.x, center.y - cellCenter.y ) * RAD_2_G;
}
}
}
}
| 0 | 0.736443 | 1 | 0.736443 | game-dev | MEDIA | 0.971249 | game-dev | 0.849881 | 1 | 0.849881 |
keenanwoodall/Piranha | 1,384 | Samples/DragRigidbody.cs | using UnityEngine;
public class DragRigidbody : MonoBehaviour
{
public float forceAmount;
[SerializeField] private float targetDistance;
[SerializeField] private Vector3 targetPosition;
[SerializeField] private Vector3 localHitPosition;
[SerializeField] private Rigidbody target;
private new Camera camera;
private void Start ()
{
camera = Camera.main;
}
private void Update ()
{
if (Input.GetMouseButtonDown (0))
{
var ray = camera.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit))
{
target = hit.transform.GetComponent<Rigidbody> ();
if (target != null)
{
targetDistance = (hit.point - ray.origin).magnitude;
localHitPosition = target.transform.worldToLocalMatrix.MultiplyPoint3x4 (hit.point);
}
}
}
else if (Input.GetMouseButton (0))
{
if (target == null)
return;
var ray = camera.ScreenPointToRay (Input.mousePosition);
targetPosition = ray.origin + ray.direction * targetDistance;
}
else if (Input.GetMouseButtonUp (0))
{
target = null;
}
}
private void FixedUpdate ()
{
if (target == null)
return;
var forcePosition = target.transform.localToWorldMatrix.MultiplyPoint3x4 (localHitPosition);
target.AddForceAtPosition ((targetPosition - forcePosition) * forceAmount * Time.fixedDeltaTime, forcePosition, ForceMode.Impulse);
}
} | 0 | 0.920858 | 1 | 0.920858 | game-dev | MEDIA | 0.980097 | game-dev | 0.989672 | 1 | 0.989672 |
HyperMC-Team/OpenRoxy | 1,671 | src/main/java/net/minecraft/client/gui/spectator/PlayerMenuObject.java | package net.minecraft.client.gui.spectator;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import Rename.Class358;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
public class PlayerMenuObject
implements ISpectatorMenuObject {
private final GameProfile profile;
private final ResourceLocation resourceLocation;
public PlayerMenuObject(GameProfile profileIn) {
this.profile = profileIn;
this.resourceLocation = AbstractClientPlayer.getLocationSkin(profileIn.getName());
AbstractClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName());
}
@Override
public void func_178661_a(SpectatorMenu menu) {
Minecraft.getMinecraft().getNetHandler().addToSendQueue(new Class358(this.profile.getId()));
}
@Override
public IChatComponent getSpectatorName() {
return new ChatComponentText(this.profile.getName());
}
@Override
public void func_178663_a(float p_178663_1_, int alpha) {
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
GlStateManager.color(1.0f, 1.0f, 1.0f, (float)alpha / 255.0f);
Gui.drawScaledCustomSizeModalRect(2, 2, 8.0f, 8.0f, 8, 8, 12, 12, 64.0f, 64.0f);
Gui.drawScaledCustomSizeModalRect(2, 2, 40.0f, 8.0f, 8, 8, 12, 12, 64.0f, 64.0f);
}
@Override
public boolean func_178662_A_() {
return true;
}
}
| 0 | 0.873102 | 1 | 0.873102 | game-dev | MEDIA | 0.94038 | game-dev | 0.980342 | 1 | 0.980342 |
AlexandreSajus/Quadcopter-AI | 13,705 | src/quadai/balloon.py | """
2D Quadcopter AI by Alexandre Sajus
More information at:
https://github.com/AlexandreSajus/Quadcopter-AI
This is the main game where you can compete with AI agents
Collect as many balloons within the time limit
"""
import os
from random import randrange
from math import sin, cos, pi, sqrt
import numpy as np
import pygame
from pygame.locals import *
from quadai.player import HumanPlayer, PIDPlayer, SACPlayer
def correct_path(current_path):
"""
This function is used to get the correct path to the assets folder
"""
return os.path.join(os.path.dirname(__file__), current_path)
def balloon():
"""
Runs the balloon game.
"""
# Game constants
FPS = 60
WIDTH = 800
HEIGHT = 800
# Physics constants
gravity = 0.08
# Propeller force for UP and DOWN
thruster_amplitude = 0.04
# Propeller force for LEFT and RIGHT rotations
diff_amplitude = 0.003
# By default, thruster will apply angle force of thruster_mean
thruster_mean = 0.04
mass = 1
# Length from center of mass to propeller
arm = 25
# Initialize Pygame, load sprites
FramePerSec = pygame.time.Clock()
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Loading player and target sprites
player_width = 80
player_animation_speed = 0.3
player_animation = []
for i in range(1, 5):
image = pygame.image.load(
correct_path(
os.path.join(
"assets/balloon-flat-asset-pack/png/objects/drone-sprites/drone-"
+ str(i)
+ ".png"
)
)
)
image.convert()
player_animation.append(
pygame.transform.scale(image, (player_width, int(player_width * 0.30)))
)
target_width = 30
target_animation_speed = 0.1
target_animation = []
for i in range(1, 8):
image = pygame.image.load(
correct_path(
os.path.join(
"assets/balloon-flat-asset-pack/png/balloon-sprites/red-plain/red-plain-"
+ str(i)
+ ".png"
)
)
)
image.convert()
target_animation.append(
pygame.transform.scale(image, (target_width, int(target_width * 1.73)))
)
# Loading background sprites
cloud1 = pygame.image.load(
correct_path(
os.path.join(
"assets/balloon-flat-asset-pack/png/background-elements/cloud-1.png"
)
)
)
cloud2 = pygame.image.load(
correct_path(
os.path.join(
"assets/balloon-flat-asset-pack/png/background-elements/cloud-2.png"
)
)
)
sun = pygame.image.load(
correct_path(
os.path.join(
"assets/balloon-flat-asset-pack/png/background-elements/sun.png"
)
)
)
cloud1.set_alpha(124)
(x_cloud1, y_cloud1, speed_cloud1) = (150, 200, 0.3)
cloud2.set_alpha(124)
(x_cloud2, y_cloud2, speed_cloud2) = (400, 500, -0.2)
sun.set_alpha(124)
# Loading fonts
pygame.font.init()
name_font = pygame.font.Font(correct_path("assets/fonts/Roboto-Bold.ttf"), 20)
name_hud_font = pygame.font.Font(correct_path("assets/fonts/Roboto-Bold.ttf"), 15)
time_font = pygame.font.Font(correct_path("assets/fonts/Roboto-Bold.ttf"), 30)
score_font = pygame.font.Font(correct_path("assets/fonts/Roboto-Regular.ttf"), 20)
respawn_timer_font = pygame.font.Font(
correct_path("assets/fonts/Roboto-Bold.ttf"), 90
)
respawning_font = pygame.font.Font(
correct_path("assets/fonts/Roboto-Regular.ttf"), 15
)
# Function to display info about a player
def display_info(position):
name_text = name_font.render(player.name, True, (255, 255, 255))
screen.blit(name_text, (position, 20))
target_text = score_font.render(
"Score : " + str(player.target_counter), True, (255, 255, 255)
)
screen.blit(target_text, (position, 45))
if player.dead == True:
respawning_text = respawning_font.render(
"Respawning...", True, (255, 255, 255)
)
screen.blit(respawning_text, (position, 70))
# Initialize game variables
time = 0
step = 0
time_limit = 100
respawn_timer_max = 3
players = [HumanPlayer(), PIDPlayer(), SACPlayer()]
# Generate 100 targets
targets = []
for i in range(100):
targets.append((randrange(200, 600), randrange(200, 600)))
# Game loop
while True:
pygame.event.get()
# Display background
screen.fill((131, 176, 181))
x_cloud1 += speed_cloud1
if x_cloud1 > WIDTH:
x_cloud1 = -cloud1.get_width()
screen.blit(cloud1, (x_cloud1, y_cloud1))
x_cloud2 += speed_cloud2
if x_cloud2 < -cloud2.get_width():
x_cloud2 = WIDTH
screen.blit(cloud2, (x_cloud2, y_cloud2))
screen.blit(sun, (630, -100))
time += 1 / 60
step += 1
# For each player
for player_index, player in enumerate(players):
if player.dead == False:
# Initialize accelerations
player.x_acceleration = 0
player.y_acceleration = gravity
player.angular_acceleration = 0
# Calculate propeller force in function of input
if player.name == "DQN" or player.name == "PID":
thruster_left, thruster_right = player.act(
[
targets[player.target_counter][0] - player.x_position,
player.x_speed,
targets[player.target_counter][1] - player.y_position,
player.y_speed,
player.angle,
player.angular_speed,
]
)
elif player.name == "SAC":
angle_to_up = player.angle / 180 * pi
velocity = sqrt(player.x_speed**2 + player.y_speed**2)
angle_velocity = player.angular_speed
distance_to_target = (
sqrt(
(targets[player.target_counter][0] - player.x_position) ** 2
+ (targets[player.target_counter][1] - player.y_position)
** 2
)
/ 500
)
angle_to_target = np.arctan2(
targets[player.target_counter][1] - player.y_position,
targets[player.target_counter][0] - player.x_position,
)
# Angle between the to_target vector and the velocity vector
angle_target_and_velocity = np.arctan2(
targets[player.target_counter][1] - player.y_position,
targets[player.target_counter][0] - player.x_position,
) - np.arctan2(player.y_speed, player.x_speed)
distance_to_target = (
sqrt(
(targets[player.target_counter][0] - player.x_position) ** 2
+ (targets[player.target_counter][1] - player.y_position)
** 2
)
/ 500
)
thruster_left, thruster_right = player.act(
np.array(
[
angle_to_up,
velocity,
angle_velocity,
distance_to_target,
angle_to_target,
angle_target_and_velocity,
distance_to_target,
]
).astype(np.float32)
)
else:
thruster_left, thruster_right = player.act([])
# Calculate accelerations according to Newton's laws of motion
player.x_acceleration += (
-(thruster_left + thruster_right)
* sin(player.angle * pi / 180)
/ mass
)
player.y_acceleration += (
-(thruster_left + thruster_right)
* cos(player.angle * pi / 180)
/ mass
)
player.angular_acceleration += (
arm * (thruster_right - thruster_left) / mass
)
# Calculate speed
player.x_speed += player.x_acceleration
player.y_speed += player.y_acceleration
player.angular_speed += player.angular_acceleration
# Calculate position
player.x_position += player.x_speed
player.y_position += player.y_speed
player.angle += player.angular_speed
# Calculate distance to target
dist = sqrt(
(player.x_position - targets[player.target_counter][0]) ** 2
+ (player.y_position - targets[player.target_counter][1]) ** 2
)
# If target reached, respawn target
if dist < 50:
player.target_counter += 1
# If to far, die and respawn after timer
elif dist > 1000:
player.dead = True
player.respawn_timer = respawn_timer_max
else:
# Display respawn timer
if player.name == "Human":
respawn_text = respawn_timer_font.render(
str(int(player.respawn_timer) + 1), True, (255, 255, 255)
)
respawn_text.set_alpha(124)
screen.blit(
respawn_text,
(
WIDTH / 2 - respawn_text.get_width() / 2,
HEIGHT / 2 - respawn_text.get_height() / 2,
),
)
player.respawn_timer -= 1 / 60
# Respawn
if player.respawn_timer < 0:
player.dead = False
(
player.angle,
player.angular_speed,
player.angular_acceleration,
) = (
0,
0,
0,
)
(player.x_position, player.x_speed, player.x_acceleration) = (
400,
0,
0,
)
(player.y_position, player.y_speed, player.y_acceleration) = (
400,
0,
0,
)
# Display target and player
target_sprite = target_animation[
int(step * target_animation_speed) % len(target_animation)
]
target_sprite.set_alpha(player.alpha)
screen.blit(
target_sprite,
(
targets[player.target_counter][0]
- int(target_sprite.get_width() / 2),
targets[player.target_counter][1]
- int(target_sprite.get_height() / 2),
),
)
player_sprite = player_animation[
int(step * player_animation_speed) % len(player_animation)
]
player_copy = pygame.transform.rotate(player_sprite, player.angle)
player_copy.set_alpha(player.alpha)
screen.blit(
player_copy,
(
player.x_position - int(player_copy.get_width() / 2),
player.y_position - int(player_copy.get_height() / 2),
),
)
# Display player name
name_hud_text = name_hud_font.render(player.name, True, (255, 255, 255))
screen.blit(
name_hud_text,
(
player.x_position - int(name_hud_text.get_width() / 2),
player.y_position - 30 - int(name_hud_text.get_height() / 2),
),
)
# Display player info
if player_index == 0:
display_info(20)
elif player_index == 1:
display_info(130)
elif player_index == 2:
display_info(240)
elif player_index == 3:
display_info(350)
time_text = time_font.render(
"Time : " + str(int(time_limit - time)), True, (255, 255, 255)
)
screen.blit(time_text, (670, 30))
# Ending conditions
if time > time_limit:
break
pygame.display.update()
FramePerSec.tick(FPS)
# Print scores and who won
print("")
scores = []
for player in players:
print(player.name + " collected : " + str(player.target_counter))
scores.append(player.target_counter)
winner = players[np.argmax(scores)].name
print("")
print("Winner is : " + winner + " !")
| 0 | 0.703819 | 1 | 0.703819 | game-dev | MEDIA | 0.748562 | game-dev | 0.750894 | 1 | 0.750894 |
mokkkk/MhdpColiseumDatapacksComponents | 5,571 | mhdp_monster_valk/data/mhdp_monster_valk/function/core/tick/animation/event/lance_flytackle_start/main.mcfunction | #> mhdp_monster_valk:core/tick/animation/event/lance_flytackle_start/main
#
# アニメーションイベントハンドラ 滑空突進開始
#
# @within function mhdp_monster_valk:core/tick/animation/event/tick
# 軸合わせ
execute if score @s aj.lance_flytackle_start.frame matches 1..36 run tag @n[tag=Mns.Target.Valk] add Temp.Rotate.Target
execute if score @s aj.lance_flytackle_start.frame matches 1..36 run function mhdp_monsters:core/util/other/turn_to_target_accurate
# 移動
execute if score @s aj.lance_flytackle_start.frame matches 1..12 if entity @n[tag=Mns.Target.Valk,distance=..18] at @s run tp @s ^ ^ ^-0.8
# 効果音
execute if score @s aj.lance_flytackle_start.frame matches 14..15 at @a[tag=!Ply.State.IsSilent,distance=..32] facing entity @s feet as @p run playsound minecraft:entity.phantom.death master @s ^ ^1 ^1 0.4 1.1 0.4
execute if score @s aj.lance_flytackle_start.frame matches 14..15 at @a[tag=!Ply.State.IsSilent,distance=..32] facing entity @s feet as @p run playsound minecraft:entity.phantom.death master @s ^ ^1 ^1 0.4 0.9 0.4
execute if score @s aj.lance_flytackle_start.frame matches 14..15 at @a[tag=!Ply.State.IsSilent,distance=..32] facing entity @s feet as @p run playsound minecraft:entity.phantom.death master @s ^ ^1 ^1 0.4 0.7 0.4
execute if score @s aj.lance_flytackle_start.frame matches 14 at @a[tag=!Ply.State.IsSilent,distance=..32] facing entity @s feet as @p run playsound minecraft:entity.allay.hurt master @s ^ ^1 ^1 0.4 1.5 0.4
execute if score @s aj.lance_flytackle_start.frame matches 14 at @a[tag=!Ply.State.IsSilent,distance=..32] facing entity @s feet as @p run playsound minecraft:entity.allay.hurt master @s ^ ^1 ^1 0.4 1.2 0.4
execute if score @s aj.lance_flytackle_start.frame matches 14..17 run playsound item.firecharge.use master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 2 0.5
execute if score @s aj.lance_flytackle_start.frame matches 2 run playsound block.grass.step master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 2 0.7
execute if score @s aj.lance_flytackle_start.frame matches 45 run playsound entity.breeze.shoot master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 3 0.5
execute if score @s aj.lance_flytackle_start.frame matches 45 run playsound entity.breeze.jump master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 3 0.5
execute if score @s aj.lance_flytackle_start.frame matches 45 run playsound entity.breeze.jump master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 3 0.6
execute if score @s aj.lance_flytackle_start.frame matches 43 run playsound entity.blaze.shoot master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 3 0.5
execute if score @s aj.lance_flytackle_start.frame matches 43 run playsound entity.blaze.shoot master @a[tag=!Ply.State.IsSilent] ~ ~ ~ 3 0.6
execute if score @s aj.lance_flytackle_start.frame matches 2..42 run function mhdp_monster_valk:core/tick/animation/event/lance_flytackle_start/particle
execute if score @s aj.lance_flytackle_start.frame matches 43 run function mhdp_monster_valk:core/tick/animation/event/lance_flytackle_start/particle_launch
# 演出
execute if score @s aj.lance_flytackle_start.frame matches 45 positioned ^ ^3 ^ run summon text_display ^-1 ^ ^ {Tags:["Mns.Shot.Valk","Mns.Shot.Valk.Vfx.RedFlash","Mns.Shot.Valk.Vfx.RedFlash.Long"],default_background:0b,brightness:{sky:15,block:15},text:{"text":"0","font":"vfx/valstrax"},transformation:{left_rotation:[0f,0f,0f,1f],right_rotation:[0f,0f,0f,1f],translation:[0f,0f,0f],scale:[12f,12f,12f]},background:16777215,text_opacity:255,interpolation_duration:1,teleport_duration:2,text_opacity:255,billboard:"center",alignment:"left"}
execute if score @s aj.lance_flytackle_start.frame matches 45.. run tp @n[type=text_display,tag=Mns.Shot.Valk.Vfx.RedFlash,tag=Mns.Shot.Valk.Vfx.RedFlash.Long] ^ ^3 ^
# 移動位置決定
execute if score @s aj.lance_flytackle_start.frame matches 38 positioned as @n[tag=Mns.Target.Valk] rotated ~ 0 positioned ^ ^0.5 ^ run summon area_effect_cloud ^ ^ ^ {Duration:200,DurationOnUse:0,Tags:["Mns.MovePos.Valk"]}
execute if score @s aj.lance_flytackle_start.frame matches 38 as @n[type=area_effect_cloud,tag=Mns.MovePos.Valk] at @s run function mhdp_monsters:core/util/other/on_ground
execute if score @s aj.lance_flytackle_start.frame matches 38 as @n[type=area_effect_cloud,tag=Mns.MovePos.Valk] at @s run tp @s ~ ~0.5 ~
execute if score @s aj.lance_flytackle_start.frame matches 38 as @n[type=area_effect_cloud,tag=Mns.MovePos.Valk] positioned as @s if block ^ ^ ^5 #mhdp_core:no_collision run tp @s ^ ^ ^5
execute if score @s aj.lance_flytackle_start.frame matches 38 if score @s Mns.Valk.JetCount matches 2.. as @n[type=area_effect_cloud,tag=Mns.MovePos.Valk] positioned as @s if block ^ ^ ^3 #mhdp_core:no_collision run tp @s ^ ^ ^3
execute if score @s aj.lance_flytackle_start.frame matches 38 if score @s Mns.Valk.JetCount matches 2.. as @n[type=area_effect_cloud,tag=Mns.MovePos.Valk] positioned as @s if block ^ ^ ^3 #mhdp_core:no_collision run tp @s ^ ^ ^3
# モデル演出
execute if score @s aj.lance_flytackle_start.frame matches 5 run function mhdp_monster_valk:core/util/models/ignite_start
# 接地
execute at @s if block ~ ~-0.1 ~ #mhdp_core:no_collision at @s run function mhdp_monsters:core/util/other/on_ground
execute at @s unless block ~ ~ ~ #mhdp_core:no_collision at @s run tp @s ~ ~0.1 ~ ~ ~
# 状態
execute if score @s aj.lance_flytackle_start.frame matches 43 run tag @s add Mns.State.IsFlying
# 終了
execute if score @s aj.lance_flytackle_start.frame matches 46 run function mhdp_monster_valk:core/tick/animation/event/lance_flytackle_start/end
| 0 | 0.741236 | 1 | 0.741236 | game-dev | MEDIA | 0.964619 | game-dev | 0.730048 | 1 | 0.730048 |
utopia-rise/godot-kotlin-jvm | 25,044 | kt/godot-library/godot-core-library/src/main/kotlin/godot/core/bridge/VariantArray.kt | @file:Suppress("PackageDirectoryMismatch")
package godot.core
import godot.annotation.CoreTypeHelper
import godot.common.interop.VariantConverter
import godot.internal.memory.MemoryManager
import godot.internal.memory.TransferContext
import godot.common.util.IndexedIterator
import godot.common.interop.VoidPtr
import godot.common.util.isNullable
import godot.internal.reflection.TypeManager
import kotlincompile.definitions.GodotJvmBuildConfig
import kotlin.jvm.internal.Reflection
import kotlin.reflect.KClass
@Suppress("unused", "UNCHECKED_CAST")
class VariantArray<T> : NativeCoreType, MutableCollection<T> {
internal var variantConverter: VariantConverter
@PublishedApi
internal constructor(handle: VoidPtr) : this(handle, VariantCaster.ANY)
@PublishedApi
internal constructor(handle: VoidPtr, converter: VariantConverter) {
variantConverter = if(converter == VariantParser.NIL) VariantCaster.ANY else converter
ptr = handle
MemoryManager.registerNativeCoreType(this, VariantParser.ARRAY)
}
constructor(parameterClazz: Class<*>) : this(Reflection.getOrCreateKotlinClass(parameterClazz))
@PublishedApi
internal constructor(parameterClazz: KClass<*>) {
val variantConverter = variantMapper[parameterClazz]
if (GodotJvmBuildConfig.DEBUG) {
checkNotNull(variantConverter) {
"Can't create a VariantArray with generic ${parameterClazz}."
}
}
this.variantConverter = variantConverter!!
ptr = if (variantConverter != VariantCaster.ANY) {
TransferContext.writeArguments(
VariantCaster.INT to variantConverter.id,
VariantCaster.INT to (TypeManager.engineTypeToId[parameterClazz] ?: -1),
VariantCaster.INT to (TypeManager.userTypeToId[parameterClazz] ?: -1)
)
Bridge.engine_call_constructor_typed()
} else {
Bridge.engine_call_constructor()
}
MemoryManager.registerNativeCoreType(this, VariantParser.ARRAY)
}
//########################PUBLIC###############################
//PROPERTIES
/**
* Returns the number of elements in the array.
*/
override val size: Int
get() {
Bridge.engine_call_size(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Create a shallow copy of the Array
*/
constructor(other: VariantArray<T>) {
this.variantConverter = other.variantConverter
this.ptr = other.ptr
MemoryManager.registerNativeCoreType(this, VariantParser.ARRAY)
}
//COMMON API
override fun add(element: T): Boolean {
append(element)
return true
}
override fun addAll(elements: Collection<T>): Boolean {
elements.forEach {
append(it)
}
return true
}
/**
* Clears the array. This is equivalent to using resize with a size of 0.
*/
override fun clear() {
Bridge.engine_call_clear(ptr)
}
/**
* Returns true if the array is empty.
*/
override fun isEmpty(): Boolean {
Bridge.engine_call_isEmpty(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Returns true if the array is read-only.
*/
fun isReadOnly(): Boolean {
Bridge.engine_call_isReadOnly(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Returns `true` if the array is typed. Typed arrays can only store elements of their associated type and provide
* type safety for the [get] operator.
*/
fun isTyped(): Boolean {
Bridge.engine_call_isTyped(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Returns a hashed integer value representing the array contents.
*/
fun hash(): Int {
Bridge.engine_call_hash(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Reverses the order of the elements in the array.
*/
fun invert() {
Bridge.engine_call_reverse(ptr)
}
override fun remove(element: T): Boolean {
if (has(element)) {
erase(element)
return true
}
return false
}
/**
* Removes an element from the array by index.
*/
fun removeAt(position: Int) {
TransferContext.writeArguments(VariantCaster.INT to position)
Bridge.engine_call_removeAt(ptr)
}
override fun removeAll(elements: Collection<T>): Boolean {
var ret = false
elements.forEach {
ret = remove(it) || ret
}
return ret
}
/**
* Resizes the array to contain a different number of elements.
* If the array size is smaller, elements are cleared, if bigger, new elements are null.
*/
fun resize(size: Int) {
TransferContext.writeArguments(VariantCaster.INT to size)
Bridge.engine_call_resize(ptr)
}
override fun retainAll(elements: Collection<T>): Boolean {
var ret = false
val iter = this.iterator()
while (iter.hasNext()) {
val value = iter.next()
if (value !in elements) {
iter.remove()
ret = true
}
}
return ret
}
/**
* Shuffles the array such that the items will have a random order.
* This method uses the global random number generator common to methods such as @randi.
* Call @randomize to ensure that a new seed will be used each time if you want non-reproducible shuffling.
*/
fun shuffle() {
Bridge.engine_call_shuffle(ptr)
}
/**
* Sorts the array.
*/
fun sort() {
Bridge.engine_call_sort(ptr)
}
/**
* Sorts the array using a custom method. The arguments are an object that holds the method and the name of such method.
* The custom method receives two arguments (a pair of elements from the array) and must return either true or false.
*/
fun sortCustom(obj: KtObject, func: String) {
TransferContext.writeArguments(VariantParser.OBJECT to obj, VariantParser.STRING to func)
Bridge.engine_call_sortCustom(ptr)
}
//API
/**
* Calls the provided [Callable] on each element in the array and returns `true` if the Callable returns `true` for
* all elements in the array. If the [Callable] returns `false` for one array element or more, this method returns
* `false`.
*
* The callable's method should take one Variant parameter (the current array element) and return a boolean value.
*
* See also [any], [filter], [map] and [reduce].
*
* **Note**: Unlike relying on the size of an array returned by [filter], this method will return as early as possible
* to improve performance (especially with large arrays).
*
* **Note**: For an empty array, this method always returns `true`.
*/
fun all(callable: Callable): Boolean {
TransferContext.writeArguments(VariantParser.CALLABLE to callable)
Bridge.engine_call_all(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Calls the provided [Callable] on each element in the array and returns `true` if the Callable returns `true` for
* one or more elements in the array. If the [Callable] returns `false` for all elements in the array, this method
* returns `false`.
*
* The callable's method should take one Variant parameter (the current array element) and return a boolean value.
*
* See also [all], [filter], [map] and [reduce].
*
* Note: Unlike relying on the size of an array returned by filter, this method will return as early as possible to
* improve performance (especially with large arrays).
*
* Note: For an empty array, this method always returns `false`.
*/
fun any(callable: Callable): Boolean {
TransferContext.writeArguments(VariantParser.CALLABLE to callable)
Bridge.engine_call_any(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Appends an element at the end of the array (alias of push_back).
*/
fun append(value: T) {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_append(ptr)
}
/**
* Appends another array at the end of this array.
*/
fun appendArray(array: VariantArray<T>) {
TransferContext.writeArguments(VariantParser.ARRAY to array)
Bridge.engine_call_appendArray(ptr)
}
/**
* Returns the last element of the array. Prints an error and returns `null` if the array is empty.
*/
fun back(): T {
Bridge.engine_call_back(ptr)
return TransferContext.readReturnValue(variantConverter) as T
}
/**
* Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search.
* Optionally, a before specifier can be passed.
* If false, the returned index comes after all existing entries of the value in the array.
* Note: Calling bsearch on an unsorted array results in unexpected behavior.
*/
@JvmOverloads
fun bsearch(value: T, before: Boolean = true): Int {
TransferContext.writeArguments(variantConverter to value, VariantParser.BOOL to before)
Bridge.engine_call_bsearch(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Finds the index of an existing value (or the insertion index that maintains sorting order, if the value is not yet present in the array) using binary search and a custom comparison method.
* Optionally, a before specifier can be passed.
* If false, the returned index comes after all existing entries of the value in the array.
* The custom method receives two arguments (an element from the array and the value searched for) and must return true if the first argument is less than the second, and return false otherwise.
* Note: Calling bsearch on an unsorted array results in unexpected behavior.
*/
@JvmOverloads
fun bsearchCustom(value: T, obj: KtObject, func: String, before: Boolean = true): Int {
TransferContext.writeArguments(
variantConverter to value, VariantParser.OBJECT to obj,
VariantParser.STRING to func, VariantParser.BOOL to before
)
Bridge.engine_call_bsearchCustom(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Returns the number of times an element is in the array.
*/
fun count(value: T): Int {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_count(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Returns a copy of the array.
* If deep is true, a deep copy is performed:
* all nested arrays and dictionaries are duplicated and will not be shared with the original array.
* If false, a shallow copy is made and references to the original nested arrays and dictionaries are kept, so that modifying a sub-array or dictionary in the copy will also impact those referenced in the source array.
*/
fun duplicate(deep: Boolean): VariantArray<T> {
TransferContext.writeArguments(VariantParser.BOOL to deep)
Bridge.engine_call_duplicate(ptr)
return (TransferContext.readReturnValue(VariantParser.ARRAY) as VariantArray<T>).also {
it.variantConverter = variantConverter
}
}
/**
* Removes the first occurrence of a value from the array.
*/
fun erase(value: T) {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_erase(ptr)
}
/**
* Assigns the given value to all elements in the array. This can typically be used together with [resize] to create
* an array with a given size and initialized elements.
*
* **Note**: If value is of a reference type ([Object]-derived, [VariantArray], [Dictionary], etc.) then the array is
* filled with the references to the same object, i.e. no duplicates are created.
*/
fun fill(value: T) {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_fill(ptr)
}
/**
* Calls the provided [Callable] on each element in the array and returns a new array with the elements for which
* the method returned `true`.
*
* The callable's method should take one Variant parameter (the current array element) and return a boolean value.
*
* See also [any], [all], [map] and [reduce].
*/
fun filter(callable: Callable): VariantArray<T> {
TransferContext.writeArguments(VariantParser.CALLABLE to callable)
Bridge.engine_call_filter(ptr)
return (TransferContext.readReturnValue(VariantParser.ARRAY) as VariantArray<T>).also {
it.variantConverter = variantConverter
}
}
/**
* Searches the array for a value and returns its index or -1 if not found.
* Optionally, the initial search index can be passed.
*/
fun find(what: T, from: Int): Int {
TransferContext.writeArguments(variantConverter to what, VariantCaster.INT to from)
Bridge.engine_call_find(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Returns the first element of the array, or null if the array is empty.
*/
fun front(): T? {
Bridge.engine_call_front(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Returns the [VariantParser] constant for a typed array. If the [VariantArray] is not typed, returns [VariantParser.NIL].
*/
fun getTypedBuiltin() = variantConverter.id
/**
* Returns a class name of a typed [VariantArray] of type [VariantParser.OBJECT].
*/
fun getTypedClassName(): StringName {
Bridge.engine_call_getTypedClassName(ptr)
return TransferContext.readReturnValue(VariantParser.STRING_NAME) as StringName
}
/**
* Returns the script associated with a typed array tied to a class name.
*/
fun getTypedScript(): Any {
Bridge.engine_call_getTypedScript(ptr)
return TransferContext.readReturnValue(VariantCaster.ANY) as Any
}
/**
* Returns true if the array contains the given value.
*/
fun has(value: T): Boolean {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_has(ptr)
return TransferContext.readReturnValue(VariantParser.BOOL) as Boolean
}
/**
* Inserts a new element at a given position in the array.
* The position must be valid, or at the end of the array (pos == size()).
*/
fun insert(position: Int, value: T) {
TransferContext.writeArguments(VariantCaster.INT to position, variantConverter to value)
Bridge.engine_call_insert(ptr)
}
/**
* Calls the provided [Callable] for each element in the array and returns a new array filled with values returned
* by the method.
*
* The callable's method should take one Variant parameter (the current array element) and can return any Variant.
*/
fun map(callable: Callable): VariantArray<Any?> {
TransferContext.writeArguments(VariantParser.CALLABLE to callable)
Bridge.engine_call_map(ptr)
return (TransferContext.readReturnValue(VariantParser.ARRAY) as VariantArray<Any?>).also {
it.variantConverter = VariantCaster.ANY
}
}
/**
* Returns the maximum value contained in the array if all elements are of comparable types.
* If the elements can't be compared, null is returned.
*/
fun max(): T? {
Bridge.engine_call_max(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Returns the minimum value contained in the array if all elements are of comparable types.
* If the elements can't be compared, null is returned.
*/
fun min(): T? {
Bridge.engine_call_min(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Returns a random value from the target array.
*/
fun pickRandom(): T? {
Bridge.engine_call_pickRandom(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Removes and returns the last element of the array.
* Returns null if the array is empty.
*/
fun popBack(): T? {
Bridge.engine_call_popBack(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Removes and returns the first element of the array.
* Returns null if the array is empty.
*/
fun popFront(): T? {
Bridge.engine_call_popFront(ptr)
return TransferContext.readReturnValue(variantConverter) as T?
}
/**
* Appends an element at the end of the array.
*/
fun pushBack(value: T) {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_pushBack(ptr)
}
/**
* Adds an element at the beginning of the array
*/
fun pushFront(value: T) {
TransferContext.writeArguments(variantConverter to value)
Bridge.engine_call_pushFront(ptr)
}
fun reduce(callable: Callable, accum: Any?): Any? {
TransferContext.writeArguments(VariantParser.CALLABLE to callable, VariantCaster.ANY to accum)
Bridge.engine_call_reduce(ptr)
return TransferContext.readReturnValue(VariantCaster.ANY)
}
/**
* Searches the array in reverse order.
* Optionally, a start search index can be passed.
* If negative, the start index is considered relative to the end of the array.
*/
fun rfind(what: T, from: Int): Int {
TransferContext.writeArguments(variantConverter to what, VariantCaster.INT to from)
Bridge.engine_call_rfind(ptr)
return TransferContext.readReturnValue(VariantCaster.INT) as Int
}
/**
* Returns the slice of the [VariantArray], from begin (inclusive) to end (exclusive), as a new [VariantArray].
*
* The absolute value of `begin` and `end` will be clamped to the array size, so the default value for `end makes
* it slice to the size of the array by default (i.e. `arr.slice(1)` is a shorthand for `arr.slice(1, arr.size())`).
*
* If either `begin` or `end` are negative, they will be relative to the end of the array (i.e. `arr.slice(0, -2)`
* is a shorthand for `arr.slice(0, arr.size() - 2)`).
*
* If deep is `true`, each element will be copied by value rather than by reference.
*/
fun slice(begin: Int, end: Int, step: Int, deep: Boolean): VariantArray<T> {
TransferContext.writeArguments(
VariantCaster.INT to begin, VariantCaster.INT to end,
VariantCaster.INT to step, VariantParser.BOOL to deep
)
Bridge.engine_call_slice(ptr)
return (TransferContext.readReturnValue(VariantParser.ARRAY) as VariantArray<T>).also {
it.variantConverter = variantConverter
}
}
//UTILITIES
operator fun set(idx: Int, data: T) {
TransferContext.writeArguments(VariantCaster.INT to idx, variantConverter to data)
Bridge.engine_call_operator_set(ptr)
}
@CoreTypeHelper
inline fun <R> mutate(idx: Int, block: (T) -> R): R {
val localCopy = this[idx]
val ret = block(localCopy)
this[idx] = localCopy
return ret
}
@CoreTypeHelper
inline fun mutateEach(block: (index: Int, value: T) -> Unit) {
forEachIndexed { index, value ->
block(index, value)
this[index] = value
}
}
operator fun get(idx: Int): T {
TransferContext.writeArguments(VariantCaster.INT to idx)
Bridge.engine_call_operator_get(ptr)
return TransferContext.readReturnValue(variantConverter) as T
}
operator fun plus(other: T) {
this.append(other)
}
override operator fun contains(element: T) = has(element)
override fun containsAll(elements: Collection<T>): Boolean {
elements.forEach {
if (!has(it)) return false
}
return true
}
override fun iterator(): MutableIterator<T> {
return IndexedIterator(this::size, this::get, this::removeAt)
}
/**
* WARNING: no equals function is available in the Gdnative API for this Coretype.
* This methods implementation works but is not the fastest one.
*/
override fun equals(other: Any?): Boolean {
return if (other is VariantArray<*>) {
val list1 = this.toList()
val list2 = other.toList()
list1 == list2
} else {
false
}
}
override fun hashCode(): Int {
return ptr.hashCode()
}
override fun toString(): String {
return "Array(${size})"
}
@Suppress("FunctionName")
private object Bridge {
external fun engine_call_constructor(): VoidPtr
external fun engine_call_constructor_typed(): VoidPtr
external fun engine_call_all(_handle: VoidPtr)
external fun engine_call_any(_handle: VoidPtr)
external fun engine_call_append(_handle: VoidPtr)
external fun engine_call_appendArray(_handle: VoidPtr)
external fun engine_call_back(_handle: VoidPtr)
external fun engine_call_bsearch(_handle: VoidPtr)
external fun engine_call_bsearchCustom(_handle: VoidPtr)
external fun engine_call_clear(_handle: VoidPtr)
external fun engine_call_count(_handle: VoidPtr)
external fun engine_call_duplicate(_handle: VoidPtr)
external fun engine_call_erase(_handle: VoidPtr)
external fun engine_call_fill(_handle: VoidPtr)
external fun engine_call_filter(_handle: VoidPtr)
external fun engine_call_find(_handle: VoidPtr)
external fun engine_call_front(_handle: VoidPtr)
external fun engine_call_getTypedClassName(_handle: VoidPtr)
external fun engine_call_getTypedScript(_handle: VoidPtr)
external fun engine_call_has(_handle: VoidPtr)
external fun engine_call_hash(_handle: VoidPtr)
external fun engine_call_insert(_handle: VoidPtr)
external fun engine_call_isEmpty(_handle: VoidPtr)
external fun engine_call_isReadOnly(_handle: VoidPtr)
external fun engine_call_isTyped(_handle: VoidPtr)
external fun engine_call_map(_handle: VoidPtr)
external fun engine_call_max(_handle: VoidPtr)
external fun engine_call_min(_handle: VoidPtr)
external fun engine_call_pickRandom(_handle: VoidPtr)
external fun engine_call_popAt(_handle: VoidPtr)
external fun engine_call_popBack(_handle: VoidPtr)
external fun engine_call_popFront(_handle: VoidPtr)
external fun engine_call_pushBack(_handle: VoidPtr)
external fun engine_call_pushFront(_handle: VoidPtr)
external fun engine_call_reduce(_handle: VoidPtr)
external fun engine_call_removeAt(_handle: VoidPtr)
external fun engine_call_resize(_handle: VoidPtr)
external fun engine_call_reverse(_handle: VoidPtr)
external fun engine_call_rfind(_handle: VoidPtr)
external fun engine_call_shuffle(_handle: VoidPtr)
external fun engine_call_size(_handle: VoidPtr)
external fun engine_call_slice(_handle: VoidPtr)
external fun engine_call_sort(_handle: VoidPtr)
external fun engine_call_sortCustom(_handle: VoidPtr)
external fun engine_call_operator_set(_handle: VoidPtr)
external fun engine_call_operator_get(_handle: VoidPtr)
}
companion object {
inline operator fun <reified T> invoke(): VariantArray<T> {
// The nullable check can't be inside the regular constructor because of Java
if (GodotJvmBuildConfig.DEBUG) {
if (isNullable<T>() && T::class in notNullableVariantSet) {
error("Can't create a VariantArray with generic ${T::class} as nullable.")
}
}
return VariantArray(T::class)
}
}
}
//HELPER
inline fun <reified T> variantArrayOf(vararg args: T) = VariantArray<T>().also { it.addAll(args) }
/**
* Convert an iterable into a GodotArray
* Warning: Might be slow if the iterable contains a lot of items because can only append items one by one
*/
inline fun <reified T> Iterable<T>.toVariantArray() = VariantArray<T>().also { arr ->
forEach {
arr.append(it)
}
}
| 0 | 0.864889 | 1 | 0.864889 | game-dev | MEDIA | 0.174322 | game-dev | 0.938524 | 1 | 0.938524 |
Baystation12/Baystation12 | 33,194 | code/modules/client/preference_setup/general/02_body.dm | var/global/list/valid_bloodtypes = list("A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-")
/datum/preferences
var/species = SPECIES_HUMAN
var/gender = MALE //gender of character (well duh)
var/pronouns = PRONOUNS_THEY_THEM
var/b_type = "A+" //blood type (not-chooseable)
var/head_hair_style = "Bald" //Hair type
var/head_hair_color = "#000000"
var/facial_hair_style = "Shaved" //Face hair type
var/facial_hair_color = "#000000"
var/eye_color = "#000000"
var/skin_tone = 0
var/skin_color = "#000000"
var/base_skin = ""
var/list/body_markings = list()
var/list/body_descriptors = list()
// maps each organ to either null(intact), "cyborg" or "amputated"
// will probably not be able to do this for head and torso ;)
var/list/organ_data
var/list/rlimb_data
var/disabilities = 0
var/list/picked_traits
/datum/category_item/player_setup_item/physical/body
name = "Body"
sort_order = 2
var/hide_species = TRUE
/datum/category_item/player_setup_item/physical/body/load_character(datum/pref_record_reader/R)
pref.species = R.read("species")
if(R.get_version() < 2 && pref.species == "booster")
pref.species = "human"
pref.age = R.read("age")
pref.gender = R.read("gender")
pref.pronouns = R.read("pronouns")
if(R.get_version() < 3 && !(pref.pronouns))
switch (pref.gender)
if (MALE)
pref.pronouns = PRONOUNS_HE_HIM
if (FEMALE)
pref.pronouns = PRONOUNS_SHE_HER
else
pref.pronouns = PRONOUNS_THEY_THEM
pref.head_hair_color = R.read("head_hair_color")
if (!pref.head_hair_color)
pref.head_hair_color = rgb(R.read("hair_red"), R.read("hair_green"), R.read("hair_blue"))
pref.facial_hair_color = R.read("facial_hair_color")
if (!pref.facial_hair_color)
pref.facial_hair_color = rgb(R.read("facial_red"), R.read("facial_green"), R.read("facial_blue"))
pref.eye_color = R.read("eye_color")
if (!pref.eye_color)
pref.eye_color = rgb(R.read("eyes_red"), R.read("eyes_green"), R.read("eyes_blue"))
pref.skin_tone = R.read("skin_tone")
pref.skin_color = R.read("skin_color")
if (!pref.skin_color)
pref.skin_color = rgb(R.read("skin_red"), R.read("skin_green"), R.read("skin_blue"))
pref.base_skin = R.read("skin_base")
pref.head_hair_style = R.read("hair_style_name")
pref.facial_hair_style = R.read("facial_style_name")
pref.b_type = R.read("b_type")
pref.disabilities = R.read("disabilities")
pref.organ_data = R.read("organ_data")
pref.rlimb_data = R.read("rlimb_data")
pref.body_markings = R.read("body_markings")
pref.body_descriptors = R.read("body_descriptors")
pref.picked_traits = R.read("traits")
pref.picked_traits = sanitize_trait_prefs(pref.picked_traits)
/datum/category_item/player_setup_item/physical/body/save_character(datum/pref_record_writer/W)
W.write("species", pref.species)
W.write("gender", pref.gender)
W.write("pronouns", pref.pronouns)
W.write("age", pref.age)
W.write("head_hair_color", pref.head_hair_color)
W.write("facial_hair_color", pref.facial_hair_color)
W.write("skin_tone", pref.skin_tone)
W.write("skin_color", pref.skin_color)
W.write("skin_base", pref.base_skin)
W.write("hair_style_name", pref.head_hair_style)
W.write("facial_style_name", pref.facial_hair_style)
W.write("eye_color", pref.eye_color)
W.write("b_type", pref.b_type)
W.write("disabilities", pref.disabilities)
W.write("organ_data", pref.organ_data)
W.write("rlimb_data", pref.rlimb_data)
W.write("body_markings", pref.body_markings)
W.write("body_descriptors", pref.body_descriptors)
W.write("traits", pref.picked_traits)
/datum/category_item/player_setup_item/physical/body/load_slot(datum/pref_record_reader/R, datum/preferences_slot/slot)
slot.age = R.read("age")
/datum/category_item/player_setup_item/physical/body/sanitize_character()
pref.head_hair_color = sanitize_hexcolor(pref.head_hair_color)
pref.facial_hair_color = sanitize_hexcolor(pref.facial_hair_color)
pref.eye_color = sanitize_hexcolor(pref.eye_color)
pref.skin_color = sanitize_hexcolor(pref.skin_color)
pref.head_hair_style = sanitize_inlist(pref.head_hair_style, GLOB.hair_styles_list, initial(pref.head_hair_style))
pref.facial_hair_style = sanitize_inlist(pref.facial_hair_style, GLOB.facial_hair_styles_list, initial(pref.facial_hair_style))
pref.b_type = sanitize_text(pref.b_type, initial(pref.b_type))
if(!pref.species || !(pref.species in GLOB.playable_species))
pref.species = SPECIES_HUMAN
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
pref.gender = sanitize_inlist(pref.gender, mob_species.genders, pick(mob_species.genders))
pref.pronouns = sanitize_inlist(pref.pronouns, mob_species.pronouns, pick(mob_species.pronouns))
pref.age = sanitize_integer(pref.age, mob_species.min_age, mob_species.max_age, initial(pref.age))
var/low_skin_tone = mob_species ? (35 - mob_species.max_skin_tone()) : -185
sanitize_integer(pref.skin_tone, low_skin_tone, 34, initial(pref.skin_tone))
if(!mob_species.base_skin_colours || isnull(mob_species.base_skin_colours[pref.base_skin]))
pref.base_skin = ""
pref.disabilities = sanitize_integer(pref.disabilities, 0, 65535, initial(pref.disabilities))
if(!istype(pref.organ_data)) pref.organ_data = list()
if(!istype(pref.rlimb_data)) pref.rlimb_data = list()
if (!istype(pref.picked_traits)) pref.picked_traits = list()
if(!istype(pref.body_markings))
pref.body_markings = list()
else
pref.body_markings &= GLOB.body_marking_styles_list
sanitize_organs()
var/list/last_descriptors = list()
if(islist(pref.body_descriptors))
last_descriptors = pref.body_descriptors.Copy()
pref.body_descriptors = list()
if(LAZYLEN(mob_species.descriptors))
for(var/entry in mob_species.descriptors)
var/datum/mob_descriptor/descriptor = mob_species.descriptors[entry]
if(istype(descriptor))
if(isnull(last_descriptors[entry]))
pref.body_descriptors[entry] = descriptor.default_value // Species datums have initial default value.
else
pref.body_descriptors[entry] = clamp(last_descriptors[entry], 1, LAZYLEN(descriptor.standalone_value_descriptors))
/datum/category_item/player_setup_item/physical/body/content(mob/user)
. = list()
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
. += "<b>Species</b> [BTN("show_species", "Info")]"
. += "<br />[TBTN("set_species", mob_species.name, "Selected")]"
. += "<br /><br /><b>Body</b> [BTN("random", "Randomize")]"
. += "<br />[TBTN("gender", pref.gender, "Bodytype")]"
. += "<br />[TBTN("pronouns", pref.pronouns, "Pronouns")]"
. += "<br />[TBTN("age", pref.age, "Age")]"
. += "<br />[TBTN("blood_type", pref.b_type, "Blood Type")]"
. += "<br />[VTBTN("disabilities", NEARSIGHTED, pref.disabilities & NEARSIGHTED ? "Yes" : "No", "Glasses")]"
if (length(pref.body_descriptors))
for (var/entry in pref.body_descriptors)
var/datum/mob_descriptor/descriptor = mob_species.descriptors[entry]
if (!descriptor) //this hides a nabber problem
continue
var/description = descriptor.get_standalone_value_descriptor(pref.body_descriptors[entry])
. += "<br />[VBTN("change_descriptor", entry, capitalize(descriptor.chargen_label))] - [description]"
if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_EYE_COLOR))
var/color = pref.eye_color
. += "[TBTN("eye_color", "Color", "<br />Eyes")] [COLOR_PREVIEW(color)]"
var/has_head_hair = length(mob_species.get_hair_styles())
if (has_head_hair > 1)
. += "<br />Hair "
if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_HAIR_COLOR))
var/color = pref.head_hair_color
. += "[BTN("hair_color", "Color")] [COLOR_PREVIEW(color)] "
. += "[BTN("hair_style=1;dec", "<")][BTN("hair_style=1;inc", ">")][BTN("hair_style", pref.head_hair_style)]"
var/has_facial_hair = length(mob_species.get_facial_hair_styles(pref.gender))
if (has_facial_hair > 1)
. += "<br />Facial Hair "
if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_HAIR_COLOR))
var/color = pref.facial_hair_color
. += "[BTN("facial_color", "Color")] [COLOR_PREVIEW(color)] "
. += "[BTN("facial_style=1;dec", "<")][BTN("facial_style=1;inc", ">")][BTN("facial_style", pref.facial_hair_style)]"
if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_BASE_SKIN_COLOURS))
. += TBTN("base_skin", pref.base_skin, "<br />Base Skin")
if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_SKIN_COLOR))
var/color = pref.skin_color
. += "[TBTN("skin_color", "Color", "<br />Skin Color")] [COLOR_PREVIEW(color)]"
else if (HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_A_SKIN_TONE))
. += "[TBTN("skin_tone", "[-pref.skin_tone + 35]/[mob_species.max_skin_tone()]", "<br />Skin Tone")]"
. += "<br />[BTN("marking_style", "+ Body Marking")]"
for (var/marking in pref.body_markings)
. += "<br />[VTBTN("marking_remove", marking, "-", marking)] "
var/datum/sprite_accessory/marking/instance = GLOB.body_marking_styles_list[marking]
if (instance.do_coloration == DO_COLORATION_USER)
var/color = pref.body_markings[marking]
. += "[VBTN("marking_color", marking, "Color")] [COLOR_PREVIEW(color)]"
if (length(pref.body_markings))
. += "<br />"
. += "<br />[TBTN("reset_limbs", "Reset", "Body Parts")] [BTN("limbs", "Adjust Limbs")] [BTN("organs", "Adjust Organs")]"
var/list/alt_organs = list()
for (var/name in pref.organ_data)
var/status = pref.organ_data[name]
var/organ_name
switch (name)
if (BP_L_ARM) organ_name = "left arm"
if (BP_R_ARM) organ_name = "right arm"
if (BP_L_LEG) organ_name = "left leg"
if (BP_R_LEG) organ_name = "right leg"
if (BP_L_FOOT) organ_name = "left foot"
if (BP_R_FOOT) organ_name = "right foot"
if (BP_L_HAND) organ_name = "left hand"
if (BP_R_HAND) organ_name = "right hand"
if (BP_HEART) organ_name = BP_HEART
if (BP_EYES) organ_name = BP_EYES
if (BP_BRAIN) organ_name = BP_BRAIN
if (BP_LUNGS) organ_name = BP_LUNGS
if (BP_LIVER) organ_name = BP_LIVER
if (BP_KIDNEYS) organ_name = BP_KIDNEYS
if (BP_STOMACH) organ_name = BP_STOMACH
if (BP_CHEST) organ_name = "upper body"
if (BP_GROIN) organ_name = "lower body"
if (BP_HEAD) organ_name = "head"
switch (status)
if ("amputated") alt_organs += "Amputated [organ_name]"
if ("mechanical")
alt_organs += "[organ_name == BP_BRAIN ? "Positronic" : "Synthetic"] [organ_name]"
if ("cyborg")
var/datum/robolimb/limb = basic_robolimb
if (pref.rlimb_data[name] && all_robolimbs[pref.rlimb_data[name]])
limb = all_robolimbs[pref.rlimb_data[name]]
alt_organs += "[limb.company] [organ_name] prosthesis"
if ("assisted")
switch (organ_name)
if (BP_HEART) alt_organs += "Pacemaker-assisted [organ_name]"
if ("voicebox") alt_organs += "Surgically altered [organ_name]"
if (BP_EYES) alt_organs += "Retinal overlayed [organ_name]"
if (BP_BRAIN) alt_organs += "Machine-interface [organ_name]"
else alt_organs += "Mechanically assisted [organ_name]"
if (!length(alt_organs))
alt_organs += "(No differences from baseline)"
. += "<br />[alt_organs.Join(", ")]"
. = jointext(., null)
. += "<br />[TBTN("res_trait", "Reset Traits", "Traits")] [BTN("add_trait", "Add Trait")]"
var/list/alt_traits = list()
for (var/picked_type as anything in pref.picked_traits)
var/singleton/trait/picked = GET_SINGLETON(picked_type)
if (!picked || !istype(picked))
continue
var/name = picked.name
var/severity
if (length(picked.metaoptions))
var/list/metaoptions = pref.picked_traits[picked_type]
for (var/option as anything in metaoptions)
severity = metaoptions[option]
if (isnull(severity))
continue
severity = LetterizeSeverity(severity)
if (ispath(option, /datum/reagent))
var/datum/reagent/picked_reagent = option
option = initial(picked_reagent.name)
alt_traits += "[name] [option] [severity]"
else
severity = pref.picked_traits[picked_type]
if (isnull(severity))
continue
severity = LetterizeSeverity(severity)
alt_traits += "[name] [severity]"
if (!length(alt_traits))
alt_traits += "No traits selected."
. += "<br />[alt_traits.Join("; ")]"
. = jointext(., null)
/datum/category_item/player_setup_item/physical/body/proc/HasAppearanceFlag(singleton/species/mob_species, flag)
return mob_species && (mob_species.appearance_flags & flag)
/datum/category_item/player_setup_item/physical/body/OnTopic(href,list/href_list, mob/user)
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
if(href_list["toggle_species_verbose"])
hide_species = !hide_species
return TOPIC_REFRESH
else if(href_list["gender"])
mob_species = GLOB.species_by_name[pref.species]
var/new_gender = input(user, "Choose your character's bodytype:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.gender) as null|anything in mob_species.genders
if(new_gender && CanUseTopic(user) && (new_gender in mob_species.genders))
pref.gender = new_gender
if(!(pref.facial_hair_style in mob_species.get_facial_hair_styles(pref.gender)))
ResetFacialHair()
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["age"])
var/new_age = input(user, "Choose your character's age:\n([mob_species.min_age]-[mob_species.max_age])", CHARACTER_PREFERENCE_INPUT_TITLE, pref.age) as num|null
if(new_age && CanUseTopic(user))
pref.age = max(min(round(text2num(new_age)), mob_species.max_age), mob_species.min_age)
for(var/datum/preferences_slot/slot in pref.slot_priority_list)
if(slot.slot != pref.default_slot)
continue
slot.age = pref.age
pref.skills_allocated = pref.sanitize_skills(pref.skills_allocated) // The age may invalidate skill loadouts
return TOPIC_REFRESH
else if(href_list["random"])
pref.randomize_appearance_and_body_for()
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["pronouns"])
var/new_pronouns = input(user, "Choose your character's pronouns:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.pronouns) as null|anything in mob_species.pronouns
mob_species = GLOB.species_by_name[pref.species]
if(new_pronouns && CanUseTopic(user) && (new_pronouns in mob_species.pronouns))
pref.pronouns = new_pronouns
return TOPIC_REFRESH
else if(href_list["change_descriptor"])
if(mob_species.descriptors)
var/desc_id = href_list["change_descriptor"]
if(pref.body_descriptors[desc_id])
var/datum/mob_descriptor/descriptor = mob_species.descriptors[desc_id]
var/choice = input("Please select a descriptor.", "Descriptor") as null|anything in descriptor.chargen_value_descriptors
if(choice && mob_species.descriptors[desc_id]) // Check in case they sneakily changed species.
pref.body_descriptors[desc_id] = descriptor.chargen_value_descriptors[choice]
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["blood_type"])
var/new_b_type = input(user, "Choose your character's blood-type:", CHARACTER_PREFERENCE_INPUT_TITLE) as null|anything in valid_bloodtypes
if(new_b_type && CanUseTopic(user))
pref.b_type = new_b_type
return TOPIC_REFRESH
else if(href_list["show_species"])
var/choice = input("Which species would you like to look at?") as null|anything in GLOB.playable_species
if(choice)
var/singleton/species/current_species = GLOB.species_by_name[choice]
show_browser(user, current_species.get_description(), "window=species;size=700x400")
return TOPIC_HANDLED
else if(href_list["set_species"])
var/list/species_to_pick = list()
for(var/species in GLOB.playable_species)
if(!GLOB.skip_allow_lists && !check_rights(R_ADMIN, 0) && config.usealienwhitelist)
var/singleton/species/current_species = GLOB.species_by_name[species]
if(!(current_species.spawn_flags & SPECIES_CAN_JOIN))
continue
else if((current_species.spawn_flags & SPECIES_IS_WHITELISTED) && !is_alien_whitelisted(preference_mob(),current_species))
continue
species_to_pick += species
var/choice = input("Select a species to play as.") as null|anything in species_to_pick
if(!choice || !(choice in GLOB.species_by_name))
return
var/prev_species = pref.species
pref.species = choice
if(prev_species != pref.species)
mob_species = GLOB.species_by_name[pref.species]
if(!(pref.gender in mob_species.genders))
pref.gender = mob_species.genders[1]
if(!(pref.pronouns in mob_species.pronouns))
pref.pronouns = mob_species.pronouns[1]
ResetAllHair()
//reset hair colour and skin colour
pref.head_hair_color = "#000000"
pref.skin_tone = 0
pref.age = max(min(pref.age, mob_species.max_age), mob_species.min_age)
reset_limbs() // Safety for species with incompatible manufacturers; easier than trying to do it case by case.
pref.body_markings.Cut() // Basically same as above.
pref.picked_traits.Cut()
prune_occupation_prefs()
pref.skills_allocated = pref.sanitize_skills(pref.skills_allocated)
pref.cultural_info = mob_species.default_cultural_info.Copy()
sanitize_organs()
if(!HasAppearanceFlag(GLOB.species_by_name[pref.species], SPECIES_APPEARANCE_HAS_UNDERWEAR))
pref.all_underwear.Cut()
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["hair_color"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_HAIR_COLOR))
return TOPIC_NOACTION
var/new_hair = input(user, "Choose your character's hair colour:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.head_hair_color) as color|null
if(new_hair && HasAppearanceFlag(GLOB.species_by_name[pref.species], SPECIES_APPEARANCE_HAS_HAIR_COLOR) && CanUseTopic(user))
pref.head_hair_color = new_hair
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["hair_style"])
var/list/valid_hairstyles = mob_species.get_hair_styles()
var/new_h_style
var/hair_index = valid_hairstyles.Find(pref.head_hair_style)
if (href_list["inc"])
if (hair_index < length(valid_hairstyles) && valid_hairstyles[hair_index + 1])
new_h_style = valid_hairstyles[hair_index + 1]
else if (href_list["dec"])
if (hair_index > 1 && valid_hairstyles[hair_index - 1])
new_h_style = valid_hairstyles[hair_index - 1]
else
new_h_style = input(user, "Choose your character's hair style:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.head_hair_style) as null|anything in valid_hairstyles
mob_species = GLOB.species_by_name[pref.species]
if(new_h_style && CanUseTopic(user) && (new_h_style in mob_species.get_hair_styles()))
pref.head_hair_style = new_h_style
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["facial_color"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_HAIR_COLOR))
return TOPIC_NOACTION
var/new_facial = input(user, "Choose your character's facial-hair colour:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.facial_hair_color) as color|null
if(new_facial && HasAppearanceFlag(GLOB.species_by_name[pref.species], SPECIES_APPEARANCE_HAS_HAIR_COLOR) && CanUseTopic(user))
pref.facial_hair_color = new_facial
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["eye_color"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_EYE_COLOR))
return TOPIC_NOACTION
var/new_eyes = input(user, "Choose your character's eye colour:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.eye_color) as color|null
if(new_eyes && HasAppearanceFlag(GLOB.species_by_name[pref.species], SPECIES_APPEARANCE_HAS_EYE_COLOR) && CanUseTopic(user))
pref.eye_color = new_eyes
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["base_skin"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_BASE_SKIN_COLOURS))
return TOPIC_NOACTION
var/new_s_base = input(user, "Choose your character's base colour:", CHARACTER_PREFERENCE_INPUT_TITLE) as null|anything in mob_species.base_skin_colours
if(new_s_base && CanUseTopic(user))
pref.base_skin = new_s_base
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["skin_tone"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_A_SKIN_TONE))
return TOPIC_NOACTION
var/new_s_tone = input(user, "Choose your character's skin-tone. Lower numbers are lighter, higher are darker. Range: 1 to [mob_species.max_skin_tone()]", CHARACTER_PREFERENCE_INPUT_TITLE, (-pref.skin_tone) + 35) as num|null
mob_species = GLOB.species_by_name[pref.species]
if(new_s_tone && HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_A_SKIN_TONE) && CanUseTopic(user))
pref.skin_tone = 35 - max(min(round(new_s_tone), mob_species.max_skin_tone()), 1)
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["skin_color"])
if(!HasAppearanceFlag(mob_species, SPECIES_APPEARANCE_HAS_SKIN_COLOR))
return TOPIC_NOACTION
var/new_skin = input(user, "Choose your character's skin colour: ", CHARACTER_PREFERENCE_INPUT_TITLE, pref.skin_color) as color|null
if(new_skin && HasAppearanceFlag(GLOB.species_by_name[pref.species], SPECIES_APPEARANCE_HAS_SKIN_COLOR) && CanUseTopic(user))
pref.skin_color = new_skin
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["facial_style"])
var/list/valid_facialhairstyles = mob_species.get_facial_hair_styles(pref.gender)
var/new_f_style
var/hair_index = valid_facialhairstyles.Find(pref.facial_hair_style)
if (href_list["inc"])
if (hair_index < length(valid_facialhairstyles) && valid_facialhairstyles[hair_index + 1])
new_f_style = valid_facialhairstyles[hair_index + 1]
else if (href_list["dec"])
if (hair_index > 1 && valid_facialhairstyles[hair_index - 1])
new_f_style = valid_facialhairstyles[hair_index - 1]
else
new_f_style = input(user, "Choose your character's facial-hair style:", CHARACTER_PREFERENCE_INPUT_TITLE, pref.facial_hair_style) as null|anything in valid_facialhairstyles
mob_species = GLOB.species_by_name[pref.species]
if(new_f_style && CanUseTopic(user) && (new_f_style in mob_species.get_facial_hair_styles(pref.gender)))
pref.facial_hair_style = new_f_style
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["marking_style"])
var/list/disallowed_markings = list()
for (var/M in pref.body_markings)
var/datum/sprite_accessory/marking/mark_style = GLOB.body_marking_styles_list[M]
disallowed_markings |= mark_style.disallows
var/list/usable_markings = pref.body_markings.Copy() ^ GLOB.body_marking_styles_list.Copy()
for(var/M in usable_markings)
var/datum/sprite_accessory/S = usable_markings[M]
if(is_type_in_list(S, disallowed_markings) || (S.species_allowed && !(mob_species.get_bodytype() in S.species_allowed)) || (S.subspecies_allowed && !(mob_species.name in S.subspecies_allowed)))
usable_markings -= M
var/new_marking = input(user, "Choose a body marking:", CHARACTER_PREFERENCE_INPUT_TITLE) as null|anything in usable_markings
if(new_marking && CanUseTopic(user))
pref.body_markings[new_marking] = "#000000" //New markings start black
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["marking_remove"])
var/M = href_list["marking_remove"]
pref.body_markings -= M
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["marking_color"])
var/M = href_list["marking_color"]
var/mark_color = input(user, "Choose the [M] color: ", CHARACTER_PREFERENCE_INPUT_TITLE, pref.body_markings[M]) as color|null
if(mark_color && CanUseTopic(user))
pref.body_markings[M] = "[mark_color]"
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["reset_limbs"])
reset_limbs()
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["limbs"])
var/list/limb_selection_list = list("Left Leg","Right Leg","Left Arm","Right Arm","Left Foot","Right Foot","Left Hand","Right Hand","Full Body")
// Full prosthetic bodies without a brain are borderline unkillable so make sure they have a brain to remove/destroy.
var/singleton/species/current_species = GLOB.species_by_name[pref.species]
if(current_species.spawn_flags & SPECIES_NO_FBP_CHARGEN)
limb_selection_list -= "Full Body"
else if(pref.organ_data[BP_CHEST] == "cyborg")
limb_selection_list |= "Head"
var/organ_tag = input(user, "Which limb do you want to change?") as null|anything in limb_selection_list
if(!organ_tag || !CanUseTopic(user)) return TOPIC_NOACTION
var/limb = null
var/second_limb = null // if you try to change the arm, the hand should also change
var/third_limb = null // if you try to unchange the hand, the arm should also change
// Do not let them amputate their entire body, ty.
var/list/choice_options = list("Normal","Amputated","Prosthesis")
//Dare ye who decides to one day make fbps be able to have fleshy bits. Heed my warning, recursion is a bitch. - Snapshot
if(pref.organ_data[BP_CHEST] == "cyborg")
choice_options = list("Amputated", "Prosthesis")
switch(organ_tag)
if("Left Leg")
limb = BP_L_LEG
second_limb = BP_L_FOOT
if("Right Leg")
limb = BP_R_LEG
second_limb = BP_R_FOOT
if("Left Arm")
limb = BP_L_ARM
second_limb = BP_L_HAND
if("Right Arm")
limb = BP_R_ARM
second_limb = BP_R_HAND
if("Left Foot")
limb = BP_L_FOOT
third_limb = BP_L_LEG
if("Right Foot")
limb = BP_R_FOOT
third_limb = BP_R_LEG
if("Left Hand")
limb = BP_L_HAND
third_limb = BP_L_ARM
if("Right Hand")
limb = BP_R_HAND
third_limb = BP_R_ARM
if("Head")
limb = BP_HEAD
choice_options = list("Prosthesis")
if("Full Body")
limb = BP_CHEST
third_limb = BP_GROIN
choice_options = list("Normal","Prosthesis")
var/new_state = input(user, "What state do you wish the limb to be in?") as null|anything in choice_options
if(!new_state || !CanUseTopic(user)) return TOPIC_NOACTION
switch(new_state)
if("Normal")
if(limb == BP_CHEST)
for(var/other_limb in (BP_ALL_LIMBS - BP_CHEST))
pref.organ_data[other_limb] = null
pref.rlimb_data[other_limb] = null
for(var/internal_organ in list(BP_HEART,BP_EYES,BP_LUNGS,BP_LIVER,BP_KIDNEYS,BP_STOMACH,BP_BRAIN))
pref.organ_data[internal_organ] = null
pref.organ_data[limb] = null
pref.rlimb_data[limb] = null
if(third_limb)
pref.organ_data[third_limb] = null
pref.rlimb_data[third_limb] = null
if("Amputated")
if(limb == BP_CHEST)
return
pref.organ_data[limb] = "amputated"
pref.rlimb_data[limb] = null
if(second_limb)
pref.organ_data[second_limb] = "amputated"
pref.rlimb_data[second_limb] = null
if("Prosthesis")
var/singleton/species/temp_species = pref.species ? GLOB.species_by_name[pref.species] : GLOB.species_by_name[SPECIES_HUMAN]
var/tmp_species = temp_species.get_bodytype(user)
var/list/usable_manufacturers = list()
for(var/company in chargen_robolimbs)
var/datum/robolimb/M = chargen_robolimbs[company]
if(tmp_species in M.species_cannot_use)
continue
if(length(M.restricted_to) && !(tmp_species in M.restricted_to))
continue
if(length(M.applies_to_part) && !(limb in M.applies_to_part))
continue
if(M.allowed_bodytypes && !(tmp_species in M.allowed_bodytypes))
continue
usable_manufacturers[company] = M
if(!length(usable_manufacturers))
return
var/choice = input(user, "Which manufacturer do you wish to use for this limb?") as null|anything in usable_manufacturers
if(!choice)
return
pref.rlimb_data[limb] = choice
pref.organ_data[limb] = "cyborg"
if(second_limb)
pref.rlimb_data[second_limb] = choice
pref.organ_data[second_limb] = "cyborg"
if(third_limb && pref.organ_data[third_limb] == "amputated")
pref.organ_data[third_limb] = null
if(limb == BP_CHEST)
for(var/other_limb in BP_ALL_LIMBS - BP_CHEST)
pref.organ_data[other_limb] = "cyborg"
pref.rlimb_data[other_limb] = choice
if(!pref.organ_data[BP_BRAIN])
pref.organ_data[BP_BRAIN] = "assisted"
for(var/internal_organ in list(BP_HEART,BP_EYES,BP_LUNGS,BP_LIVER,BP_KIDNEYS))
pref.organ_data[internal_organ] = "mechanical"
return TOPIC_REFRESH_UPDATE_PREVIEW
else if(href_list["organs"])
var/organ_name = input(user, "Which internal function do you want to change?") as null|anything in list("Heart", "Eyes", "Lungs", "Liver", "Kidneys", "Stomach")
if(!organ_name) return
var/organ = null
switch(organ_name)
if("Heart")
organ = BP_HEART
if("Eyes")
organ = BP_EYES
if("Lungs")
organ = BP_LUNGS
if("Liver")
organ = BP_LIVER
if("Kidneys")
organ = BP_KIDNEYS
if("Stomach")
organ = BP_STOMACH
var/list/organ_choices = list("Normal","Assisted","Synthetic")
if(mob_species && mob_species.spawn_flags & SPECIES_NO_ROBOTIC_INTERNAL_ORGANS)
organ_choices -= "Assisted"
organ_choices -= "Synthetic"
if(pref.organ_data[BP_CHEST] == "cyborg")
organ_choices -= "Normal"
organ_choices += "Synthetic"
var/new_state = input(user, "What state do you wish the organ to be in?") as null|anything in organ_choices
if(!new_state) return
switch(new_state)
if("Normal")
pref.organ_data[organ] = null
if("Assisted")
pref.organ_data[organ] = "assisted"
if("Synthetic")
pref.organ_data[organ] = "mechanical"
sanitize_organs()
return TOPIC_REFRESH
else if(href_list["disabilities"])
var/disability_flag = text2num(href_list["disabilities"])
pref.disabilities ^= disability_flag
return TOPIC_REFRESH_UPDATE_PREVIEW
else if (href_list["res_trait"])
if (!length(pref.picked_traits))
return
pref.picked_traits.Cut()
return TOPIC_REFRESH
else if (href_list["add_trait"])
if (!mob_species)
return
var/list/possible_traits = mob_species.get_selectable_traits()
var/picked = input(user, "Select a trait to apply.", "Add Trait") as null | anything in possible_traits
var/singleton/trait/selected = possible_traits[picked]
if (!selected || !istype(selected))
return
if (selected.maximum_count && length(pref.picked_traits[selected.type]) >= selected.maximum_count)
to_chat(usr, SPAN_WARNING("\The [selected.name] trait can only be selected [selected.maximum_count] times."))
return
for (var/existing_type as anything in pref.picked_traits)
var/singleton/trait/existing_trait = GET_SINGLETON(existing_type)
if (!existing_trait || !istype(existing_trait))
continue
if (LAZYISIN(existing_trait.incompatible_traits, selected.type) || LAZYISIN(selected.incompatible_traits, existing_type))
to_chat(usr, SPAN_WARNING("\The [selected.name] trait is incompatible with [existing_trait.name]."))
return
var/list/possible_levels = selected.levels
var/selected_level
if (length(possible_levels) > 1)
var/list/letterized_levels
for (var/severity in possible_levels)
LAZYSET(letterized_levels, LetterizeSeverity(severity), severity)
var/letterized_input = input(user, "Select the trait's level to apply.", "Select Level") as null | anything in letterized_levels
if (!letterized_input)
return
selected_level = letterized_levels[letterized_input]
else
selected_level = possible_levels[1]
var/additional_data
if (length(selected.metaoptions))
var/list/sanitized_metaoptions
for (var/atom/option as anything in selected.metaoptions)
var/named_option = initial(option.name)
LAZYSET(sanitized_metaoptions, named_option, option)
var/additional_input = input(user, "[selected.addprompt]", "Select Option") as null | anything in sanitized_metaoptions
if (!additional_input)
return
additional_data = sanitized_metaoptions[additional_input]
if (additional_data)
var/list/interim = list()
if (!LAZYISIN(pref.picked_traits, selected.type))
LAZYSET(pref.picked_traits, selected.type, interim)
var/list/existing_meta_options = pref.picked_traits[selected.type]
if (existing_meta_options[additional_data] == selected_level)
return
LAZYSET(existing_meta_options, additional_data, selected_level)
LAZYSET(pref.picked_traits, selected.type, existing_meta_options)
else
LAZYSET(pref.picked_traits, selected.type, selected_level)
return TOPIC_REFRESH
return ..()
/datum/category_item/player_setup_item/physical/body/proc/reset_limbs()
pref.organ_data.Cut()
pref.rlimb_data.Cut()
/datum/category_item/player_setup_item/proc/ResetAllHair()
ResetHair()
ResetFacialHair()
/datum/category_item/player_setup_item/proc/ResetHair()
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
var/list/valid_hairstyles = mob_species.get_hair_styles()
if(length(valid_hairstyles))
pref.head_hair_style = pick(valid_hairstyles)
else
//this shouldn't happen
pref.head_hair_style = GLOB.hair_styles_list["Bald"]
/datum/category_item/player_setup_item/proc/ResetFacialHair()
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
var/list/valid_facialhairstyles = mob_species.get_facial_hair_styles(pref.gender)
if(length(valid_facialhairstyles))
pref.facial_hair_style = pick(valid_facialhairstyles)
else
//this shouldn't happen
pref.facial_hair_style = GLOB.facial_hair_styles_list["Shaved"]
/datum/category_item/player_setup_item/physical/body/proc/sanitize_organs()
var/singleton/species/mob_species = GLOB.species_by_name[pref.species]
if(mob_species && mob_species.spawn_flags & SPECIES_NO_ROBOTIC_INTERNAL_ORGANS)
for(var/name in pref.organ_data)
var/status = pref.organ_data[name]
if(status in list("assisted","mechanical"))
pref.organ_data[name] = null
| 0 | 0.900428 | 1 | 0.900428 | game-dev | MEDIA | 0.874023 | game-dev | 0.923822 | 1 | 0.923822 |
lune-org/lune | 2,120 | crates/lune-roblox/src/datatypes/types/number_range.rs | use core::fmt;
use mlua::prelude::*;
use rbx_dom_weak::types::NumberRange as DomNumberRange;
use lune_utils::TableBuilder;
use crate::exports::LuaExportsTable;
use super::super::*;
/**
An implementation of the [NumberRange](https://create.roblox.com/docs/reference/engine/datatypes/NumberRange) Roblox datatype.
This implements all documented properties, methods & constructors of the `NumberRange` class as of March 2023.
*/
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NumberRange {
pub(crate) min: f32,
pub(crate) max: f32,
}
impl LuaExportsTable for NumberRange {
const EXPORT_NAME: &'static str = "NumberRange";
fn create_exports_table(lua: Lua) -> LuaResult<LuaTable> {
let number_range_new = |_: &Lua, (min, max): (f32, Option<f32>)| {
Ok(match max {
Some(max) => NumberRange {
min: min.min(max),
max: min.max(max),
},
None => NumberRange { min, max: min },
})
};
TableBuilder::new(lua)?
.with_function("new", number_range_new)?
.build_readonly()
}
}
impl LuaUserData for NumberRange {
fn add_fields<F: LuaUserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("Min", |_, this| Ok(this.min));
fields.add_field_method_get("Max", |_, this| Ok(this.max));
}
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(LuaMetaMethod::Eq, userdata_impl_eq);
methods.add_meta_method(LuaMetaMethod::ToString, userdata_impl_to_string);
}
}
impl fmt::Display for NumberRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, {}", self.min, self.max)
}
}
impl From<DomNumberRange> for NumberRange {
fn from(v: DomNumberRange) -> Self {
Self {
min: v.min,
max: v.max,
}
}
}
impl From<NumberRange> for DomNumberRange {
fn from(v: NumberRange) -> Self {
Self {
min: v.min,
max: v.max,
}
}
}
| 0 | 0.864274 | 1 | 0.864274 | game-dev | MEDIA | 0.445798 | game-dev | 0.874271 | 1 | 0.874271 |
microsoft/MixedRealityToolkit-Unity | 7,720 | Assets/MRTK/Core/Utilities/Physics/VectorRollingStatistics.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Physics
{
/// <summary>
/// Vector Statistics used in gaze stabilization.
/// </summary>
public class VectorRollingStatistics
{
/// <summary>
/// Current standard deviation of the positions of the vectors.
/// </summary>
public float CurrentStandardDeviation { get; private set; }
/// <summary>
/// Difference to standardDeviation when the latest sample was added.
/// </summary>
public float StandardDeviationDeltaAfterLatestSample { get; private set; }
/// <summary>
/// How many standard deviations the latest sample was away.
/// </summary>
public float StandardDeviationsAwayOfLatestSample { get; private set; }
/// <summary>
/// The average position.
/// </summary>
public Vector3 Average { get; private set; }
/// <summary>
/// The number of samples in the current set (may be 0 - maxSamples)
/// </summary>
public float ActualSampleCount { get; private set; }
/// <summary>
/// Keeps track of the index into the sample list for the rolling average.
/// </summary>
private int currentSampleIndex;
/// <summary>
/// An array of samples for calculating standard deviation.
/// </summary>
private Vector3[] samples;
/// <summary>
/// The sum of all of the samples.
/// </summary>
private Vector3 cumulativeFrame;
/// <summary>
/// The sum of all of the samples squared.
/// </summary>
private Vector3 cumulativeFrameSquared;
/// <summary>
/// The total number of samples taken.
/// </summary>
private int cumulativeFrameSamples;
/// <summary>
/// The maximum number of samples to include in
/// the average and standard deviation calculations.
/// </summary>
private int maxSamples;
/// <summary>
/// Initialize the rolling stats.
/// </summary>
public void Init(int sampleCount)
{
maxSamples = sampleCount;
samples = new Vector3[sampleCount];
Reset();
}
/// <summary>
/// Resets the stats to zero.
/// </summary>
public void Reset()
{
currentSampleIndex = 0;
ActualSampleCount = 0;
cumulativeFrame = Vector3.zero;
cumulativeFrameSquared = Vector3.zero;
cumulativeFrameSamples = 0;
CurrentStandardDeviation = 0.0f;
StandardDeviationDeltaAfterLatestSample = 0.0f;
StandardDeviationsAwayOfLatestSample = 0.0f;
Average = Vector3.zero;
if (samples != null)
{
for (int index = 0; index < samples.Length; index++)
{
samples[index] = Vector3.zero;
}
}
}
/// <summary>
/// Adds a new sample to the sample list and updates the stats.
/// </summary>
/// <param name="value">The new sample to add</param>
public void AddSample(Vector3 value)
{
if (maxSamples == 0)
{
return;
}
// remove the old sample from our accumulation
Vector3 oldSample = samples[currentSampleIndex];
// -- Below replaces operations:
// cumulativeFrame -= oldSample;
// cumulativeFrameSquared -= (oldSample.Mul(oldSample));
cumulativeFrame.x -= oldSample.x;
cumulativeFrame.y -= oldSample.y;
cumulativeFrame.z -= oldSample.z;
oldSample.x *= oldSample.x;
oldSample.y *= oldSample.y;
oldSample.z *= oldSample.z;
cumulativeFrameSquared.x -= oldSample.x;
cumulativeFrameSquared.y -= oldSample.y;
cumulativeFrameSquared.z -= oldSample.z;
// --
// Add the new sample to the accumulation
samples[currentSampleIndex] = value;
// -- Below replaces operations:
// cumulativeFrame += value;
// cumulativeFrameSquared += value.Mul(value);
cumulativeFrame.x += value.x;
cumulativeFrame.y += value.y;
cumulativeFrame.z += value.z;
Vector3 valueSquared = value;
valueSquared.x = value.x * value.x;
valueSquared.y = value.y * value.y;
valueSquared.z = value.z * value.z;
cumulativeFrameSquared.x += valueSquared.x;
cumulativeFrameSquared.y += valueSquared.y;
cumulativeFrameSquared.z += valueSquared.z;
// --
// Keep track of how many samples we have
cumulativeFrameSamples++;
ActualSampleCount = Mathf.Min(maxSamples, cumulativeFrameSamples);
// see how many standard deviations the current sample is from the previous average
// -- Below replaces operations:
// Vector3 deltaFromAverage = (Average - value);
Vector3 deltaFromAverage = Average;
deltaFromAverage.x -= value.x;
deltaFromAverage.y -= value.y;
deltaFromAverage.z -= value.z;
// --
float oldStandardDeviation = CurrentStandardDeviation;
// -- Below replaces operations:
// StandardDeviationsAwayOfLatestSample = oldStandardDeviation.Equals(0) ? 0 : (deltaFromAverage / oldStandardDeviation).magnitude;
if (oldStandardDeviation == 0)
{
StandardDeviationsAwayOfLatestSample = 0;
}
else
{
deltaFromAverage.x /= oldStandardDeviation;
deltaFromAverage.y /= oldStandardDeviation;
deltaFromAverage.z /= oldStandardDeviation;
StandardDeviationsAwayOfLatestSample = deltaFromAverage.magnitude;
}
// --
// And calculate new averages and standard deviations
// (note that calculating a standard deviation of a Vector3 might not
// be done properly, but the logic is working for the gaze stabilization scenario)
// -- Below replaces operations:
// Average = cumulativeFrame / ActualSampleCount;
// float newStandardDev = Mathf.Sqrt((cumulativeFrameSquared / ActualSampleCount - Average.Mul(Average)).magnitude);
Vector3 average = Average;
average.x = cumulativeFrame.x / ActualSampleCount;
average.y = cumulativeFrame.y / ActualSampleCount;
average.z = cumulativeFrame.z / ActualSampleCount;
Average = average;
Vector3 frmSqrDivSamples = cumulativeFrameSquared;
frmSqrDivSamples.x /= ActualSampleCount;
frmSqrDivSamples.y /= ActualSampleCount;
frmSqrDivSamples.z /= ActualSampleCount;
frmSqrDivSamples.x -= (average.x * average.x);
frmSqrDivSamples.y -= (average.y * average.y);
frmSqrDivSamples.z -= (average.z * average.z);
float newStandardDev = Mathf.Sqrt(frmSqrDivSamples.magnitude);
// --
StandardDeviationDeltaAfterLatestSample = oldStandardDeviation - newStandardDev;
CurrentStandardDeviation = newStandardDev;
// update the next list position
currentSampleIndex = (currentSampleIndex + 1) % maxSamples;
}
}
}
| 0 | 0.769333 | 1 | 0.769333 | game-dev | MEDIA | 0.55608 | game-dev | 0.868265 | 1 | 0.868265 |
Lounode/Extrabotany | 1,676 | Xplat/src/main/java/io/github/lounode/extrabotany/common/item/equipment/armor/goblin_slayer/GoblinSlayerHelmetItem.java | package io.github.lounode.extrabotany.common.item.equipment.armor.goblin_slayer;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.MobType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import io.github.lounode.eventwrapper.event.entity.living.LivingHurtEventWrapper;
import io.github.lounode.eventwrapper.eventbus.api.EventBusSubscriberWrapper;
import io.github.lounode.eventwrapper.eventbus.api.SubscribeEventWrapper;
import io.github.lounode.extrabotany.common.item.ExtraBotanyItems;
import io.github.lounode.extrabotany.common.lib.ExtraBotanyTags;
public class GoblinSlayerHelmetItem extends GoblinSlayerArmorItem {
private static final float UNDEAD_DAMAGE_BONUS = 0.5F;
public GoblinSlayerHelmetItem(Properties properties) {
super(Type.HELMET, properties);
}
@EventBusSubscriberWrapper
public static class EventHandler {
@SubscribeEventWrapper
public static void onPlayerAttack(LivingHurtEventWrapper event) {
if (!(event.getSource().getEntity() instanceof Player player)) {
return;
}
ItemStack armorStack = player.getItemBySlot(EquipmentSlot.HEAD);
if (!armorStack.is(ExtraBotanyItems.goblinSlayerHelmet)) {
return;
}
if (!(armorStack.getItem() instanceof GoblinSlayerArmorItem suit)) {
return;
}
if (!suit.hasArmorSet(player)) {
return;
}
if (event.getEntity().getMobType() == MobType.UNDEAD) {
float origin = event.getAmount();
event.setAmount(origin * (1 + UNDEAD_DAMAGE_BONUS));
}
if (event.getEntity().getType().is(ExtraBotanyTags.Entities.GOBLINS)) {
event.setAmount(Integer.MAX_VALUE);
}
}
}
}
| 0 | 0.879705 | 1 | 0.879705 | game-dev | MEDIA | 0.996265 | game-dev | 0.955034 | 1 | 0.955034 |
Raven-APlus/RavenAPlus | 3,237 | src/main/java/keystrokesmod/module/impl/world/Tower.java | package keystrokesmod.module.impl.world;
import keystrokesmod.module.Module;
import keystrokesmod.module.ModuleManager;
import keystrokesmod.module.impl.world.tower.*;
import keystrokesmod.module.setting.impl.*;
import keystrokesmod.utility.MoveUtil;
import keystrokesmod.utility.Utils;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import org.lwjgl.input.Keyboard;
import static keystrokesmod.module.ModuleManager.scaffold;
public class Tower extends Module {
private final ButtonSetting disableWhileCollided;
private final ButtonSetting disableWhileHurt;
private final ButtonSetting sprintJumpForward;
private final ButtonSetting stopMotion;
private boolean lastTowering = false;
public Tower() {
super("Tower", category.world);
this.registerSetting(new DescriptionSetting("Works with SafeWalk & Scaffold"));
final ModeValue mode;
this.registerSetting(mode = new ModeValue("Mode", this)
.add(new VanillaTower("Vanilla", this))
.add(new JumpSprintTower("JumpSprint", this))
.add(new HypixelTower("Hypixel", this))
.add(new BlocksMCTower("BlocksMC", this))
.add(new ConstantMotionTower("ConstantMotion", this))
.add(new VulcanTower("Vulcan", this))
);
this.registerSetting(disableWhileCollided = new ButtonSetting("Disable while collided", false));
this.registerSetting(disableWhileHurt = new ButtonSetting("Disable while hurt", false));
this.registerSetting(sprintJumpForward = new ButtonSetting("Sprint jump forward", true));
this.registerSetting(stopMotion = new ButtonSetting("Stop motion", false));
this.canBeEnabled = false;
mode.enable();
FMLCommonHandler.instance().bus().register(new Object(){
@SubscribeEvent
public void onUpdate(TickEvent.ClientTickEvent event) {
final boolean curCanTower = canTower();
if (!curCanTower && lastTowering && stopMotion.isToggled())
MoveUtil.stop();
lastTowering = curCanTower;
}
});
}
public boolean canTower() {
if (scaffold.totalBlocks() == 0) return false;
if (mc.currentScreen != null) return false;
if (!Utils.nullCheck() || !Utils.jumpDown()) {
return false;
}
else if (disableWhileHurt.isToggled() && mc.thePlayer.hurtTime >= 9) {
return false;
}
else if (disableWhileCollided.isToggled() && mc.thePlayer.isCollidedHorizontally) {
return false;
}
else return modulesEnabled();
}
public boolean modulesEnabled() {
return ((ModuleManager.safeWalk.isEnabled() && ModuleManager.safeWalk.tower.isToggled() && SafeWalk.canSafeWalk()) || (scaffold.isEnabled() && scaffold.tower.isToggled()));
}
public boolean canSprint() {
return canTower() && this.sprintJumpForward.isToggled() && Keyboard.isKeyDown(mc.gameSettings.keyBindForward.getKeyCode()) && Utils.jumpDown();
}
} | 0 | 0.905581 | 1 | 0.905581 | game-dev | MEDIA | 0.733914 | game-dev | 0.959501 | 1 | 0.959501 |
ArduPilot/MissionPlanner | 4,827 | ExtLibs/Utilities/EnumTranslator.cs | #region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MissionPlanner.Attributes;
#endregion
namespace MissionPlanner.Utilities
{
public static class EnumTranslator
{
/// <summary>
/// Translates this instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Dictionary<int, string> Translate<T>()
{
return Translate<T>(true);
}
public static List<KeyValuePair<int, string>> EnumToList<T>()
{
var ans = Translate<T>(string.Empty, true, false);
return ans.ToList();
}
/// <summary>
/// Translates the specified check private.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="checkPrivate">if set to <c>true</c> [check private].</param>
/// <returns></returns>
public static Dictionary<int, string> Translate<T>(bool checkPrivate)
{
return Translate<T>(string.Empty, checkPrivate);
}
/// <summary>
/// Translates the specified default text.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultText">The default text.</param>
/// <param name="checkPrivate">if set to <c>true</c> [check private].</param>
/// <returns></returns>
public static Dictionary<int, string> Translate<T>(string defaultText, bool checkPrivate)
{
return Translate<T>(defaultText, checkPrivate, true);
}
/// <summary>
/// Translates the specified default text.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultText">The default text.</param>
/// <param name="checkPrivate">if set to <c>true</c> [check private].</param>
/// <param name="sorting">if set to <c>true</c> [sorting].</param>
/// <returns></returns>
public static Dictionary<int, string> Translate<T>(string defaultText, bool checkPrivate, bool sorting)
{
var types = new Dictionary<int, string>();
var tempTypes = new Dictionary<int, string>();
if (!String.IsNullOrEmpty(defaultText)) types.Add(-1, defaultText);
foreach (FieldInfo fieldInfo in typeof(T).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
bool add = true;
string displayText = string.Empty;
T type = (T)fieldInfo.GetValue(typeof(T));
object[] displayTextObjectArr = fieldInfo.GetCustomAttributes(typeof(DisplayTextAttribute), true);
displayText = (displayTextObjectArr.Length > 0)
? ((DisplayTextAttribute)displayTextObjectArr[0]).Text
: type.ToString();
if (checkPrivate)
{
object[] privateAttributeObjectArr = fieldInfo.GetCustomAttributes(typeof(PrivateAttribute), true);
if (privateAttributeObjectArr.Length > 0)
{
add = !((PrivateAttribute)privateAttributeObjectArr[0]).IsPrivate;
}
}
if (add)
{
tempTypes.Add(Convert.ToInt32(type), displayText);
}
}
if (sorting)
{
foreach(var x in tempTypes.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value)){ types.Add(x.Key, x.Value); }
}
else
{
foreach (var x in tempTypes.ToDictionary(x => x.Key, x => x.Value)) { types.Add(x.Key, x.Value); }
}
return types;
}
/// <summary>
/// Gets the display text.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
public static string GetDisplayText<T>(T value)
{
var displayText = string.Empty;
var fieldInfo = value.GetType().GetField(value.ToString());
if(fieldInfo != null)
{
T type = (T)fieldInfo.GetValue(typeof(T));
if(type != null)
{
object[] displayTextObjectArr = fieldInfo.GetCustomAttributes(typeof(DisplayTextAttribute), true);
displayText = (displayTextObjectArr.Length > 0)
? ((DisplayTextAttribute)displayTextObjectArr[0]).Text
: type.ToString();
}
}
return displayText;
}
public static int GetValue<T>(string item)
{
var list = Translate<T>();
foreach (var kvp in list)
{
if (kvp.Value == item)
return kvp.Key;
}
return -1;
}
}
}
| 0 | 0.948441 | 1 | 0.948441 | game-dev | MEDIA | 0.283973 | game-dev | 0.968684 | 1 | 0.968684 |
klyx-dev/klyx | 4,081 | core/src/commonMain/kotlin/com/klyx/core/settings/AppSettings.kt | package com.klyx.core.settings
import com.klyx.core.theme.Appearance
import com.klyx.core.theme.Contrast
import com.klyx.core.theme.DEFAULT_SEED_COLOR
import io.github.xn32.json5k.SerialComment
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
@Serializable
data class AppSettings(
@SerialComment(
"""
Whether to use dynamic colors or not.
(This is only available on Android 12+)
"""
)
val dynamicColor: Boolean = true,
@SerialComment(
"""
The appearance of the UI.
Available options:
- light
- dark
- system
"""
)
val appearance: Appearance = Appearance.System,
@SerialComment(
"""
The contrast of the UI.
Available options:
- normal
- medium
- high
"""
)
val contrast: Contrast = Contrast.Normal,
@SerialComment(
"""
The name of the Klyx theme to use for the UI (it will not work if dynamic colors are enabled).
Available themes:
- Autumn Ember
- Emerald Waves
- Ocean Breeze
- Golden Glow
Note: More themes can be added using theme extensions.
"""
)
val theme: String = "Ocean Breeze",
val seedColor: Int = DEFAULT_SEED_COLOR,
val paletteStyleIndex: Int = 0,
@SerialComment("The editor settings")
val editor: EditorSettings = EditorSettings(),
@SerialComment("Whether to show the FPS counter in the UI")
val showFps: Boolean = false,
@SerialComment(
"""
Whether to load extensions on app startup or at runtime.
If disabled, extensions will be loaded at runtime instead of on the splash screen.
"""
)
val loadExtensionsOnStartup: Boolean = true,
@SerialComment("Whether to show terminal tab option or not in the menu.")
val terminalTab: Boolean = false,
@SerialComment("Different settings for specific languages.")
val languages: Map<String, JsonObject> = emptyMap(),
@SerialComment("LSP Specific settings.")
val lsp: Map<String, LspSettings> = mapOf(
"pylsp" to LspSettings(
// settings = buildJsonObject {
// putJsonObject("plugins") {
// putJsonObject("pycodestyle") {
// put("enabled", true)
// putJsonArray("ignore") {
// add("W292")
// }
// }
// }
// },
initializationOptions = buildJsonObject {
putJsonObject("plugins") {
putJsonObject("pyflakes") {
put("enabled", true)
}
putJsonObject("pylint") {
put("enabled", true)
}
putJsonObject("pydocstyle") {
put("enabled", true)
}
putJsonObject("pylint-quotes") {
put("enabled", true)
}
putJsonObject("mypy") {
put("enabled", true)
put("live_mode", false)
}
putJsonObject("pyright") {
put("enabled", true)
}
putJsonObject("flake8") {
put("enabled", true)
put("maxLineLength", 100)
}
}
}
),
"rust-analyzer" to LspSettings(
initializationOptions = buildJsonObject {
put("cargo.buildScripts.enable", true)
put("procMacro.enable", true)
//put("completion.fullFunctionSignatures.enable", true)
}
)
)
) : KlyxSettings
| 0 | 0.838831 | 1 | 0.838831 | game-dev | MEDIA | 0.371593 | game-dev | 0.722696 | 1 | 0.722696 |
GAIPS/FAtiMA-Toolkit | 2,536 | Assets/IntegratedAuthoringTool/EventTriggers.cs | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RolePlayCharacter;
using Utilities;
using WellFormedNames;
namespace IntegratedAuthoringTool
{
public class EventTriggers
{
public static Dictionary<Name, string> _EventTriggerVariables = new Dictionary<Name, string>()
{
{
Name.BuildName("Has(Floor)"), "Has(Floor)"
},
{
Name.BuildName("DialogueState"), "DialogueState"
}
};
public List<Name> ComputeTriggersList(List<RolePlayCharacter.RolePlayCharacterAsset> rpcs)
{
var retList = new List<Name>();
foreach (var npc in rpcs)
{
var ev = NoDialoguesLeft(npc);
if (ev != null)
retList.AddRange(ev);
}
return retList;
}
private List<Name> NoDialoguesLeft(RolePlayCharacter.RolePlayCharacterAsset rpc)
{
var decisions = rpc.Decide();
var hasFloor = _EventTriggerVariables[(Name)"Has(Floor)"];
var dialogueStates = rpc.GetAllBeliefs().ToList().FindAll(x => x.Name.ToString().Contains(_EventTriggerVariables[(Name) "DialogueState"]));
List<string> dialogueStateTargets = new List<string>();
List<string> dialogueStateValues = new List<string>();
List<Name> noDialogueEvents = new List<Name>();
foreach (var d in dialogueStates)
{
var belief = d.Name.ToString().Split('(', ')');
dialogueStateTargets.Add(belief[1]);
dialogueStateValues.Add(d.Value);
}
if (rpc.GetBeliefValue(hasFloor) != rpc.CharacterName.ToString())
return null;
if (!decisions.Any())
{
int i = 0;
foreach (var target in dialogueStateTargets)
{
noDialogueEvents.Add(EventHelper.ActionEnd(target, "NoDialoguesLeft(" + target + "," + dialogueStateValues[i] + ")", rpc.CharacterName.ToString()));
i++;
}
return noDialogueEvents;
}
/* var speakDecisions = decisions.Select(x => x.Key.ToString() == "Speak");
if (speakDecisions.IsEmpty())
return noDialoguesEvent;
*/
return null;
}
}
} | 0 | 0.853803 | 1 | 0.853803 | game-dev | MEDIA | 0.930791 | game-dev | 0.824285 | 1 | 0.824285 |
RavEngine/RavEngine | 4,878 | deps/physx/physx/source/simulationcontroller/src/ScIterators.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "ScIterators.h"
#include "ScBodySim.h"
#include "ScShapeSim.h"
#include "ScShapeInteraction.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////
Sc::ContactIterator::Pair::Pair(const void*& contactPatches, const void*& contactPoints, const void*& frictionPatches, PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches,
ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1)
: mIndex(0)
, mNumContacts(numContacts)
, mIter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), reinterpret_cast<const PxU32*>(forces + numContacts), numPatches, numContacts)
, mAnchorIter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(frictionPatches), numPatches)
, mForces(forces)
, mActor0(actor0->getPxActor())
, mActor1(actor1->getPxActor())
{
mCurrentContact.shape0 = shape0.getPxShape();
mCurrentContact.shape1 = shape1.getPxShape();
mCurrentContact.normalForceAvailable = (forces != NULL);
}
Sc::ContactIterator::Pair* Sc::ContactIterator::getNextPair()
{
PX_ASSERT(mCurrent || (mCurrent == mLast));
if(mCurrent < mLast)
{
ShapeInteraction* si = static_cast<ShapeInteraction*>(*mCurrent);
const void* contactPatches = NULL;
const void* contactPoints = NULL;
PxU32 contactDataSize = 0;
const PxReal* forces = NULL;
PxU32 numContacts = 0;
PxU32 numPatches = 0;
const void* frictionPatches = NULL;
PxU32 nextOffset = si->getContactPointData(contactPatches, contactPoints, contactDataSize, numContacts, numPatches, forces, mOffset, *mOutputs, frictionPatches);
if (nextOffset == mOffset)
++mCurrent;
else
mOffset = nextOffset;
mCurrentPair = Pair(contactPatches, contactPoints, frictionPatches, contactDataSize, forces, numContacts, numPatches, si->getShape0(), si->getShape1(), &si->getActorSim0(), &si->getActorSim1());
return &mCurrentPair;
}
else
return NULL;
}
Sc::Contact* Sc::ContactIterator::Pair::getNextContact()
{
if(mIndex < mNumContacts)
{
while (!mIter.hasNextContact())
{
if(!mIter.hasNextPatch())
return NULL;
mIter.nextPatch();
}
mIter.nextContact();
mCurrentContact.normal = mIter.getContactNormal();
mCurrentContact.point = mIter.getContactPoint();
mCurrentContact.separation = mIter.getSeparation();
mCurrentContact.normalForce = mForces ? mForces[mIndex] : 0;
mCurrentContact.faceIndex0 = mIter.getFaceIndex0();
mCurrentContact.faceIndex1 = mIter.getFaceIndex1();
mIndex++;
return &mCurrentContact;
}
return NULL;
}
Sc::FrictionAnchor* Sc::ContactIterator::Pair::getNextFrictionAnchor()
{
if(mAnchorIter.hasNextPatch())
{
while (!mAnchorIter.hasNextFrictionAnchor())
{
if(!mAnchorIter.hasNextPatch())
return NULL;
mAnchorIter.nextPatch();
}
mAnchorIter.nextFrictionAnchor();
mCurrentAnchor.normal = mAnchorIter.getNormal();
mCurrentAnchor.point = mAnchorIter.getPosition();
mCurrentAnchor.impulse = mAnchorIter.getImpulse();
return &mCurrentAnchor;
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
| 0 | 0.723306 | 1 | 0.723306 | game-dev | MEDIA | 0.697543 | game-dev | 0.951788 | 1 | 0.951788 |
Shadows-of-Fire/Apotheosis | 2,785 | src/main/java/dev/shadowsoffire/apotheosis/compat/twilight/OreMagnetBonus.java | package dev.shadowsoffire.apotheosis.compat.twilight;
import java.util.Map;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import dev.shadowsoffire.apotheosis.socket.gem.GemClass;
import dev.shadowsoffire.apotheosis.socket.gem.GemInstance;
import dev.shadowsoffire.apotheosis.socket.gem.GemView;
import dev.shadowsoffire.apotheosis.socket.gem.Purity;
import dev.shadowsoffire.apotheosis.socket.gem.bonus.GemBonus;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.common.util.AttributeTooltipContext;
public class OreMagnetBonus extends GemBonus {
public static final Codec<OreMagnetBonus> CODEC = RecordCodecBuilder.create(inst -> inst
.group(
gemClass(),
Purity.mapCodec(Codec.intRange(0, 4096)).fieldOf("values").forGetter(a -> a.values))
.apply(inst, OreMagnetBonus::new));
protected final Map<Purity, Integer> values;
public OreMagnetBonus(GemClass gemClass, Map<Purity, Integer> values) {
super(gemClass);
this.values = values;
}
@Override
public InteractionResult onItemUse(GemInstance inst, UseOnContext ctx) {
BlockState state = ctx.getLevel().getBlockState(ctx.getClickedPos());
if (state.isAir()) {
return null;
}
Level level = ctx.getLevel();
Player player = ctx.getPlayer();
player.startUsingItem(ctx.getHand());
// The ore magnet only checks that the use duration (72000 - param) is > 10
// https://github.com/TeamTwilight/twilightforest/blob/1.21.x/src/main/java/twilightforest/item/OreMagnetItem.java#L76
AdventureTwilightCompat.ORE_MAGNET.value().releaseUsing(inst.gemStack(), level, player, 0);
player.stopUsingItem();
int cost = this.values.get(inst.purity());
ctx.getItemInHand().hurtAndBreak(cost, player, LivingEntity.getSlotForHand(ctx.getHand()));
return super.onItemUse(inst, ctx);
}
@Override
public Codec<? extends GemBonus> getCodec() {
return CODEC;
}
@Override
public boolean supports(Purity purity) {
return this.values.containsKey(purity);
}
@Override
public Component getSocketBonusTooltip(GemView gem, AttributeTooltipContext ctx) {
return Component.translatable("bonus." + this.getTypeKey() + ".desc", this.values.get(gem.purity())).withStyle(ChatFormatting.YELLOW);
}
}
| 0 | 0.692356 | 1 | 0.692356 | game-dev | MEDIA | 0.982929 | game-dev | 0.835277 | 1 | 0.835277 |
Cuyler36/ACSE | 8,191 | ACSE.WinForms/Utilities/DataUtility.cs | using System;
using System.IO;
using ACSE.Core.Items;
using ACSE.Core.Saves;
using ACSE.Core.Town.Acres;
namespace ACSE.WinForms.Utilities
{
public static class DataUtility
{
// Export/Import Methods
public static void ExportAcres(WorldAcre[] acres, SaveGeneration saveGeneration, string saveFileName)
{
using (var saveDialog = new System.Windows.Forms.SaveFileDialog())
{
saveDialog.Filter = "ACSE Acre Save (*.aas)|*.aas";
saveDialog.FileName = saveFileName + " Acre Data.aas";
if (saveDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
try
{
using (var stream = new FileStream(saveDialog.FileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(new byte[] { 0x41, 0x41, 0x53 }); // "AAS" Identifier
writer.Write((byte)acres.Length); // Total Acre Count
writer.Write((byte)saveGeneration); // Save Generation
writer.Write(new byte[] { 0, 0, 0 }); // Padding
foreach (var t in acres)
{
writer.Write(BitConverter.GetBytes(t.AcreId));
}
writer.Flush();
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Acre exportation failed!", "Acre Export Error", System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
public static void ImportAcres(ref WorldAcre[] acres, SaveGeneration saveGeneration)
{
using (var openDialog = new System.Windows.Forms.OpenFileDialog())
{
openDialog.Filter = "ACSE Acre Save (*.aas)|*.aas";
openDialog.FileName = "";
if (openDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
try
{
using (var stream = new FileStream(openDialog.FileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream))
{
if (!System.Text.Encoding.ASCII.GetString(reader.ReadBytes(3)).Equals("AAS") ||
reader.ReadByte() != acres.Length ||
(SaveGeneration)reader.ReadByte() != saveGeneration) return;
reader.BaseStream.Seek(8, SeekOrigin.Begin);
foreach (var t in acres)
{
t.AcreId = reader.ReadUInt16();
t.BaseAcreId = (ushort)(t.AcreId & 0xFFFC);
}
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Acre importation failed!", "Acre Import Error", System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
public static void ExportTown(WorldAcre[] acres, SaveGeneration saveGeneration, string saveFileName)
{
using (var saveDialog = new System.Windows.Forms.SaveFileDialog())
{
saveDialog.Filter = "ACSE Town Save (*.ats)|*.ats";
saveDialog.FileName = saveFileName + " Town Data.ats";
if (saveDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
try
{
using (var stream = new FileStream(saveDialog.FileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(new byte[] { 0x41, 0x54, 0x53 }); // "ATS" Identifier
writer.Write((byte)acres.Length); // Total Acre Count
writer.Write((byte)saveGeneration); // Save Generation
writer.Write(new byte[] { 0, 0, 0 }); // Padding
if (saveGeneration == SaveGeneration.N3DS)
{
foreach (var acre in acres)
{
foreach (var item in acre.Items)
{
writer.Write(BitConverter.GetBytes(item.ToUInt32()));
}
}
}
else
{
foreach (var acre in acres)
{
foreach (var item in acre.Items)
{
writer.Write(BitConverter.GetBytes(item.ItemId));
}
}
}
writer.Flush();
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Town exportation failed!", "Town Export Error", System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
public static void ImportTown(ref WorldAcre[] acres, SaveGeneration saveGeneration)
{
using (var openDialog = new System.Windows.Forms.OpenFileDialog())
{
openDialog.Filter = "ACSE Town Save (*.ats)|*.ats";
openDialog.FileName = "";
if (openDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
try
{
using (var stream = new FileStream(openDialog.FileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream))
{
if (!System.Text.Encoding.ASCII.GetString(reader.ReadBytes(3)).Equals("ATS") ||
reader.ReadByte() != acres.Length ||
(SaveGeneration)reader.ReadByte() != saveGeneration) return;
reader.BaseStream.Seek(8, SeekOrigin.Begin);
if (saveGeneration == SaveGeneration.N3DS)
{
foreach (var acre in acres)
{
for (var x = 0; x < acre.Items.Length; x++)
{
acre.Items[x] = new Item(reader.ReadUInt32());
}
}
}
else
{
foreach (var acre in acres)
{
for (var x = 0; x < acre.Items.Length; x++)
{
acre.Items[x] = new Item(reader.ReadUInt16());
}
}
}
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Acre importation failed!", "Acre Import Error", System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
}
}
| 0 | 0.641857 | 1 | 0.641857 | game-dev | MEDIA | 0.415143 | game-dev | 0.881734 | 1 | 0.881734 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.