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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lunar-sway/minestuck | 11,168 | src/main/java/com/mraof/minestuck/entity/item/GristEntity.java | package com.mraof.minestuck.entity.item;
import com.mraof.minestuck.alchemy.GristGutter;
import com.mraof.minestuck.alchemy.GristHelper;
import com.mraof.minestuck.api.alchemy.GristAmount;
import com.mraof.minestuck.api.alchemy.GristSet;
import com.mraof.minestuck.api.alchemy.GristType;
import com.mraof.minestuck.api.alchemy.GristTypes;
import com.mraof.minestuck.computer.editmode.ServerEditHandler;
import com.mraof.minestuck.entity.MSEntityTypes;
import com.mraof.minestuck.network.GristRejectAnimationPacket;
import com.mraof.minestuck.player.GristCache;
import com.mraof.minestuck.player.IdentifierHandler;
import com.mraof.minestuck.player.PlayerIdentifier;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.RandomSource;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.common.util.FakePlayer;
import net.neoforged.neoforge.entity.IEntityWithComplexSpawn;
import net.neoforged.neoforge.network.PacketDistributor;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.function.Consumer;
import java.util.function.Predicate;
@ParametersAreNonnullByDefault
public class GristEntity extends Entity implements IEntityWithComplexSpawn
{
//TODO Perhaps use a data manager for grist type in the same way as the underling entity?
public int cycle;
public int consumeDelay;
public int gristAge = 0;
private int gristHealth = 5;
//Type of grist
private GristType gristType = GristTypes.BUILD.get();
private long gristValue = 1;
private Player closestPlayer;
private int targetCycle;
private int shakeTimer = 0;
public static GristEntity create(EntityType<? extends GristEntity> type, Level level)
{
return new GristEntity(type, level);
}
public GristEntity(Level level, double x, double y, double z, GristAmount gristData)
{
super(MSEntityTypes.GRIST.get(), level);
this.gristValue = gristData.amount();
//this.yOffset = this.height / 2.0F;
this.setPos(x, y, z);
this.setYRot((float) (Math.random() * 360.0D));
this.setDeltaMovement(level.random.nextGaussian() * 0.2D - 0.1D, level.random.nextGaussian() * 0.2D, level.random.nextGaussian() * 0.2D - 0.1D);
this.gristType = gristData.type();
}
public GristEntity(EntityType<? extends GristEntity> type, Level level)
{
super(type, level);
}
/**
* this is where we set up our consumedelay
*/
public GristEntity(Level level, double x, double y, double z, GristAmount gristData, int pickupDelay)
{
this(level, x, y, z, gristData);
consumeDelay = pickupDelay;
// Set the class's consume-delay variable to equal the pickupDelay value that got passed in.
}
/**
* This is a version of the spawn grist entities function with a delay.
*/
public static void spawnGristEntities(GristSet gristSet, Level level, double x, double y, double z, RandomSource rand, Consumer<GristEntity> postProcessor, int delay, int gusherCount)
{
for(GristAmount amount : gristSet.asAmounts())
{
long countLeft = amount.amount();
for(int i = 0; i < 10 && countLeft > 0; i++)
{
long spawnedCount = countLeft <= amount.amount() / 10 || i ==
gusherCount - 1 ? countLeft : Math.min(countLeft,
(long) level.random.nextDouble() * countLeft + 1);
GristAmount spawnedAmount = amount.type().amount(spawnedCount);
GristEntity entity = new GristEntity(level, x, y, z, spawnedAmount, delay);
postProcessor.accept(entity);
level.addFreshEntity(entity);
countLeft -= spawnedCount;
}
}
}
public static void spawnGristEntities(GristSet gristSet, Level level, double x, double y, double z, RandomSource rand, Consumer<GristEntity> postProcessor)
{
spawnGristEntities(gristSet, level, x, y, z, rand, postProcessor, 0, 10);
}
@Override
protected void defineSynchedData(SynchedEntityData.Builder builder)
{
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
* prevent them from trampling crops
*/
@Override
protected MovementEmission getMovementEmission()
{
return Entity.MovementEmission.NONE;
}
@Override
public boolean hurt(DamageSource source, float amount)
{
if(this.isInvulnerableTo(source))
{
return false;
} else
{
this.markHurt();
this.gristHealth = (int) ((float) this.gristHealth - amount);
if(this.gristHealth <= 0)
{
this.discard();
}
return false;
}
}
private static final int SHAKE_DURATION = 37;
public void setAnimationFromPacket()
{
shakeTimer = SHAKE_DURATION;
}
public float getShakeFactor()
{
return (float) shakeTimer / SHAKE_DURATION;
}
public class PlayerCanPickUpGristSelector implements Predicate<Entity>
{
@Override
public boolean test(@Nullable Entity player)
{
if(!(player instanceof Player))
{
return false;
}
return GristEntity.this.getPlayerCacheRoom((Player) player) >= GristEntity.this.gristValue;
}
}
public long getPlayerCacheRoom(Player entityIn)
{
if(entityIn instanceof ServerPlayer player)
{
long cacheCapacity = GristCache.get(player).getRemainingCapacity(gristType);
long gutterCapacity = GristGutter.get(player).map(GristGutter::getRemainingCapacity).orElse(0L);
return gutterCapacity + cacheCapacity;
}
return 0;
}
@Override
public void tick()
{
super.tick();
long canPickUp = getPlayerCacheRoom(closestPlayer);
if(this.level().isClientSide && shakeTimer > 0)
{
shakeTimer--;
}
this.xo = this.getX();
this.yo = this.getY();
this.zo = this.getZ();
this.setDeltaMovement(this.getDeltaMovement().add(0, -0.03D, 0));
if(this.isInLava())
{
this.setDeltaMovement(0.2D, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F);
this.playSound(SoundEvents.GENERIC_BURN, 0.4F, 2.0F + this.random.nextFloat() * 0.4F);
}
//this.setPosition(this.getPosX(), (this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D, this.getPosZ());
double d0 = this.getDimensions(Pose.STANDING).width() * 2.0D;
// Periodically re-evaluate whether the grist should be following this particular player
if(this.targetCycle < this.cycle - 20 + this.getId() % 100) //Why should I care about the entityId
{
if(this.closestPlayer == null || canPickUp < gristValue || this.closestPlayer.distanceToSqr(this) > d0 * d0)
{
this.closestPlayer = this.level().getNearestPlayer(
this.getX(), this.getY(), this.getZ(),
d0,
new PlayerCanPickUpGristSelector());
}
this.targetCycle = this.cycle;
}
// If the grist has someone to follow, move towards that player
if(this.closestPlayer != null)
{
double d1 = (this.closestPlayer.getX() - this.getX()) / d0;
double d2 = (this.closestPlayer.getY() + (double) this.closestPlayer.getEyeHeight() - this.getY()) / d0;
double d3 = (this.closestPlayer.getZ() - this.getZ()) / d0;
double d4 = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3);
double d5 = this.getDimensions(Pose.STANDING).width() * 2.0D - d4;
if(d5 > 0.0D)
{
this.setDeltaMovement(this.getDeltaMovement().add(d1 / d4 * d5 * 0.1D, d2 / d4 * d5 * 0.1D, d3 / d4 * d5 * 0.1D));
}
}
this.move(MoverType.SELF, this.getDeltaMovement());
float f = 0.98F;
if(this.onGround())
{
BlockPos pos = BlockPos.containing(this.getX(), this.getBoundingBox().minY - 1, this.getZ());
f = this.level().getBlockState(pos).getFriction(level(), pos, this) * 0.98F;
}
this.setDeltaMovement(this.getDeltaMovement().multiply(f, 0.98D, f));
if(this.onGround())
{
this.setDeltaMovement(this.getDeltaMovement().multiply(1, -0.9D, 1));
}
++this.cycle;
++this.gristAge;
if(this.gristAge >= 6000)
{
this.discard();
}
}
@Override
public void checkDespawn()
{
if(this.gristValue <= 0)
discard();
}
/*
* Returns if this entity is in water and will end up adding the waters velocity to the entity
*/
/*@Override
public boolean handleWaterMovement()
{
return this.world.handleMaterialAcceleration(this.getBoundingBox(), Material.WATER, this);
}*/
@Override
protected void addAdditionalSaveData(CompoundTag compound)
{
compound.putShort("Health", (short) this.gristHealth);
compound.putShort("Age", (short) this.gristAge);
compound.putLong("Value", (short) this.gristValue);
compound.put("Type", GristHelper.encodeGristType(gristType));
}
@Override
protected void readAdditionalSaveData(CompoundTag compound)
{
this.gristHealth = compound.getShort("Health") & 255;
this.gristAge = compound.getShort("Age");
if(compound.contains("Value", Tag.TAG_ANY_NUMERIC))
this.gristValue = compound.getLong("Value");
if(compound.contains("Type", Tag.TAG_STRING))
this.gristType = GristHelper.parseGristType(compound.get("Type")).orElseGet(GristTypes.BUILD);
}
/**
* Called by a player entity when they collide with an entity
*/
@Override
public void playerTouch(Player player)
{
if(!(player instanceof ServerPlayer serverPlayer) || player instanceof FakePlayer)
return;
if(ServerEditHandler.isInEditmode(serverPlayer))
return;
long canPickUp = getPlayerCacheRoom(serverPlayer);
if(canPickUp >= gristValue)
consumeGrist(IdentifierHandler.encode(serverPlayer), true);
else
{
GristRejectAnimationPacket packet = GristRejectAnimationPacket.createPacket(this);
PacketDistributor.sendToPlayersTrackingEntity(this, packet);
}
}
public void consumeGrist(PlayerIdentifier identifier, boolean sound)
{
if(this.level().isClientSide)
throw new IllegalStateException("Grist entities shouldn't be consumed client-side.");
if(sound)
this.playSound(SoundEvents.ITEM_PICKUP, 0.1F, 0.5F * ((this.random.nextFloat() - this.random.nextFloat()) * 0.7F + 1.8F));
GristCache.get(level(), identifier).addWithGutter(this.getAmount(), GristHelper.EnumSource.CLIENT);
this.discard();
}
@Override
public boolean isAttackable()
{
return false;
}
public GristType getGristType()
{
return gristType;
}
public GristAmount getAmount()
{
return gristType.amount(gristValue);
}
@Override
public EntityDimensions getDimensions(Pose poseIn)
{
return super.getDimensions(poseIn).scale((float) Math.pow(gristValue, .25));
}
public float getSizeByValue()
{
return (float) (Math.pow((double) this.gristValue, 0.25D) / 3.0D);
}
@Override
public void writeSpawnData(RegistryFriendlyByteBuf buffer)
{
GristType.STREAM_CODEC.encode(buffer, gristType);
buffer.writeLong(gristValue);
}
@Override
public void readSpawnData(RegistryFriendlyByteBuf data)
{
gristType = GristType.STREAM_CODEC.decode(data);
gristValue = data.readLong();
}
}
| 412 | 0.943055 | 1 | 0.943055 | game-dev | MEDIA | 0.905408 | game-dev | 0.982249 | 1 | 0.982249 |
ReactiveDrop/reactivedrop_public_src | 6,375 | src/game/server/physics.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: This is the abstraction layer for the physics simulation system
// Any calls to the external physics library (ipion) should be made through this
// layer. Eventually, the physics system will probably become a DLL and made
// accessible to the client & server side code.
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef PHYSICS_H
#define PHYSICS_H
#ifdef _WIN32
#pragma once
#endif
#include "physics_shared.h"
class CBaseEntity;
class IPhysicsMaterial;
class IPhysicsConstraint;
class IPhysicsSpring;
class IPhysicsSurfaceProps;
class CTakeDamageInfo;
class ConVar;
extern IPhysicsMaterial *g_Material;
extern ConVar phys_pushscale;
extern ConVar phys_timescale;
struct objectparams_t;
extern IPhysicsGameTrace *physgametrace;
class IPhysicsCollisionSolver;
class IPhysicsCollisionEvent;
class IPhysicsObjectEvent;
extern IPhysicsCollisionSolver * const g_pCollisionSolver;
extern IPhysicsCollisionEvent * const g_pCollisionEventHandler;
extern IPhysicsObjectEvent * const g_pObjectEventHandler;
// HACKHACK: We treat anything >= 500kg as a special "large mass" that does more impact damage
// and has special recovery on crushing/killing other objects
// also causes screen shakes on impact with static/world objects
const float VPHYSICS_LARGE_OBJECT_MASS = 500.0f;
struct gamevcollisionevent_t : public vcollisionevent_t
{
Vector preVelocity[2];
Vector postVelocity[2];
AngularImpulse preAngularVelocity[2];
CBaseEntity *pEntities[2];
void Init( vcollisionevent_t *pEvent )
{
*((vcollisionevent_t *)this) = *pEvent;
pEntities[0] = NULL;
pEntities[1] = NULL;
}
};
struct triggerevent_t
{
CBaseEntity *pTriggerEntity;
IPhysicsObject *pTriggerPhysics;
CBaseEntity *pEntity;
IPhysicsObject *pObject;
bool bStart;
inline void Init( CBaseEntity *triggerEntity, IPhysicsObject *triggerPhysics, CBaseEntity *entity, IPhysicsObject *object, bool startTouch )
{
pTriggerEntity = triggerEntity;
pTriggerPhysics= triggerPhysics;
pEntity = entity;
pObject = object;
bStart = startTouch;
}
inline void Clear()
{
memset( this, 0, sizeof(*this) );
}
};
// parse solid parameter overrides out of a string
void PhysSolidOverride( solid_t &solid, string_t overrideScript );
extern CEntityList *g_pShadowEntities;
void PhysAddShadow( CBaseEntity *pEntity );
void PhysRemoveShadow( CBaseEntity *pEntity );
bool PhysHasShadow( CBaseEntity *pEntity );
void PhysEnableFloating( IPhysicsObject *pObject, bool bEnable );
void PhysCollisionSound( CBaseEntity *pEntity, IPhysicsObject *pPhysObject, int channel, int surfaceProps, int surfacePropsHit, float deltaTime, float speed );
void PhysCollisionScreenShake( gamevcollisionevent_t *pEvent, int index );
void PhysCollisionDust( gamevcollisionevent_t *pEvent, surfacedata_t *phit );
#if HL2_EPISODIC
void PhysCollisionWarpEffect( gamevcollisionevent_t *pEvent, surfacedata_t *phit );
#endif
void PhysBreakSound( CBaseEntity *pEntity, IPhysicsObject *pPhysObject, Vector vecOrigin );
// plays the impact sound for a particular material
void PhysicsImpactSound( CBaseEntity *pEntity, IPhysicsObject *pPhysObject, int channel, int surfaceProps, int surfacePropsHit, float volume, float impactSpeed );
void PhysCallbackDamage( CBaseEntity *pEntity, const CTakeDamageInfo &info );
void PhysCallbackDamage( CBaseEntity *pEntity, const CTakeDamageInfo &info, gamevcollisionevent_t &event, int hurtIndex );
// Applies force impulses at a later time
void PhysCallbackImpulse( IPhysicsObject *pPhysicsObject, const Vector &vecCenterForce, const AngularImpulse &vecCenterTorque );
// Sets the velocity at a later time
void PhysCallbackSetVelocity( IPhysicsObject *pPhysicsObject, const Vector &vecVelocity );
// queue up a delete on this object
void PhysCallbackRemove(IServerNetworkable *pRemove);
bool PhysGetDamageInflictorVelocityStartOfFrame( IPhysicsObject *pInflictor, Vector &velocity, AngularImpulse &angVelocity );
// force a physics entity to sleep immediately
void PhysForceEntityToSleep( CBaseEntity *pEntity, IPhysicsObject *pObject );
// teleport an entity to it's position relative to an object it's constrained to
void PhysTeleportConstrainedEntity( CBaseEntity *pTeleportSource, IPhysicsObject *pObject0, IPhysicsObject *pObject1, const Vector &prevPosition, const QAngle &prevAngles, bool physicsRotate );
void PhysGetListOfPenetratingEntities( CBaseEntity *pSearch, CUtlVector<CBaseEntity *> &list );
bool PhysShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1 );
// returns true when processing a callback - so we can defer things that can't be done inside a callback
bool PhysIsInCallback();
bool PhysIsFinalTick();
bool PhysGetTriggerEvent( triggerevent_t *pEvent, CBaseEntity *pTrigger );
// note: pErrorEntity is used to report errors (object not found, more than one found). It can be NULL
IPhysicsObject *FindPhysicsObjectByName( const char *pName, CBaseEntity *pErrorEntity );
bool PhysFindOrAddVehicleScript( const char *pScriptName, struct vehicleparams_t *pParams, struct vehiclesounds_t *pSounds );
void PhysFlushVehicleScripts();
// this is called to flush all queues when the delete list is cleared
void PhysOnCleanupDeleteList();
struct masscenteroverride_t
{
enum align_type
{
ALIGN_POINT = 0,
ALIGN_AXIS = 1,
};
void Defaults()
{
entityName = NULL_STRING;
}
void SnapToPoint( string_t name, const Vector &pointWS )
{
entityName = name;
center = pointWS;
axis.Init();
alignType = ALIGN_POINT;
}
void SnapToAxis( string_t name, const Vector &axisStartWS, const Vector &unitAxisDirWS )
{
entityName = name;
center = axisStartWS;
axis = unitAxisDirWS;
alignType = ALIGN_AXIS;
}
Vector center;
Vector axis;
int alignType;
string_t entityName;
};
void PhysSetMassCenterOverride( masscenteroverride_t &override );
// NOTE: this removes the entry from the table as well as retrieving it
void PhysGetMassCenterOverride( CBaseEntity *pEntity, vcollide_t *pCollide, solid_t &solidOut );
float PhysGetEntityMass( CBaseEntity *pEntity );
void PhysSetEntityGameFlags( CBaseEntity *pEntity, unsigned short flags );
void DebugDrawContactPoints(IPhysicsObject *pPhysics);
#endif // PHYSICS_H
| 412 | 0.82907 | 1 | 0.82907 | game-dev | MEDIA | 0.986262 | game-dev | 0.602708 | 1 | 0.602708 |
realms-mud/core-lib | 12,625 | lib/modules/research/activeResearchItem.c | //*****************************************************************************
// Class: activeResearchItem
// File Name: activeResearchItem.c
//
// Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See
// the accompanying LICENSE file for details.
//*****************************************************************************
virtual inherit "/lib/modules/research/researchItem.c";
/////////////////////////////////////////////////////////////////////////////
protected void Setup()
{
}
/////////////////////////////////////////////////////////////////////////////
public void create()
{
addSpecification("type", "active");
Setup();
}
/////////////////////////////////////////////////////////////////////////////
protected int addSpecification(string type, mixed value)
{
int ret = 0;
switch(type)
{
case "hit point cost":
case "spell point cost":
case "stamina point cost":
case "repeat effect":
case "cooldown":
{
if(intp(value) && (value > 0))
{
specificationData[type] = value;
ret = 1;
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be an integer greater than 0.\n",
type));
}
break;
}
case "cooldown modifiers":
{
if(mappingp(value) && (sizeof(value) == sizeof(filter(value,
(: intp($2) && ($2 < query("cooldown")) :)))))
{
specificationData[type] = value;
ret = 1;
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be a valid cooldown modifier mapping.\n",
type));
}
break;
}
case "hit point cost modifiers":
case "spell point cost modifiers":
case "stamina point cost modifiers":
{
string cost = regreplace(type, "(.*) modifiers", "\\1", 1);
if(mappingp(value) && (sizeof(value) == sizeof(filter(value,
(: intp($2) && ($2 < query($3)) :), cost))))
{
specificationData[type] = value;
ret = 1;
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be a valid cost modifier mapping.\n",
type));
}
break;
}
case "composite research":
case "composite type":
case "composite class":
case "default composite description":
case "event handler":
case "cooldown group":
case "use composite message":
case "use ability message":
case "repeated ability message":
case "use ability fail message":
case "use ability cooldown message":
case "use combination message":
{
if (value && stringp(value))
{
specificationData[type] = value;
ret = 1;
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be a string.\n",
type));
}
break;
}
case "command template":
{
if(value && stringp(value))
{
specificationData[type] = value;
ret = addCommandTemplate(value);
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be a string.\n",
type));
}
break;
}
case "consumables":
{
if (mappingp(value) && (sizeof(value) == sizeof(filter(value,
(: (stringp($1) && intp($2)) :)))))
{
specificationData[type] = value;
ret = 1;
}
else
{
raise_error(sprintf("ERROR - activeResearchItem: the '%s'"
" specification must be a valid mapping.\n",
type));
}
break;
}
default:
{
ret = researchItem::addSpecification(type, value);
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
public int cooldown(object initiator)
{
int ret = query("cooldown");
mapping modifiers = query("cooldown modifiers");
if (mappingp(modifiers) && objectp(initiator))
{
modifiers = filter(modifiers, (: $3->isResearched($1) :), initiator);
foreach(string item in modifiers)
{
ret -= modifiers[item];
}
if (ret < 2)
{
ret = 2;
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeOnSelf(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeOnTarget(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeInArea(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeOnEnvironment(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeOnRegion(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
protected int executeGlobally(string unparsedCommand, object owner,
string researchName)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
private nomask int applyToScope(string command, object owner,
string researchName)
{
int ret = 0;
if(member(specificationData, "scope"))
{
switch(specificationData["scope"])
{
case "self":
{
ret = executeOnSelf(command, owner, researchName);
break;
}
case "targeted":
{
ret = executeOnTarget(command, owner, researchName);
break;
}
case "area":
{
ret = executeInArea(command, owner, researchName);
break;
}
case "environmental":
{
ret = executeOnEnvironment(command, owner, researchName);
break;
}
case "region":
{
ret = executeOnRegion(command, owner, researchName);
break;
}
case "global":
{
ret = executeGlobally(command, owner, researchName);
break;
}
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
public nomask void repeatEffect(int timesRemaining, string command,
object owner, string researchName)
{
int ret = applyToScope(command, owner, researchName);
if (ret && (timesRemaining > 1))
{
call_out("repeatEffect", 2, timesRemaining - 1,
command, owner, researchName);
}
}
/////////////////////////////////////////////////////////////////////////////
private nomask int useConsumables(object initiator)
{
int ret = 1;
if (member(specificationData, "consumables"))
{
object *potentialConsumables = all_inventory(initiator) +
all_inventory(environment(initiator));
mapping itemsToConsume = ([]);
foreach(string item in m_indices(specificationData["consumables"]))
{
for (int i = 0; i < specificationData["consumables"][item]; i++)
{
object *consumables = filter(potentialConsumables,
(: ($1->id($2) &&
!(($1->query("quantity") <= itemsToConsume[$1]) &&
$1->doNotDestroyWhenConsumed())) :), item);
if (sizeof(consumables))
{
if (member(itemsToConsume, consumables[0]))
{
itemsToConsume[consumables[0]]++;
}
else
{
itemsToConsume[consumables[0]] = 1;
}
}
else
{
ret = 0;
itemsToConsume = ([]);
break;
}
}
}
if (ret)
{
foreach(object item in m_indices(itemsToConsume))
{
if (item->query("quantity") > 0)
{
int newQty = item->query("quantity") - itemsToConsume[item];
item->set("quantity", newQty);
}
if ((item->query("quantity") < 1) &&
!item->doNotDestroyWhenConsumed())
{
destruct(item);
}
}
}
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
public nomask int execute(string command, object initiator)
{
int ret = 0;
string researchName = program_name(this_object());
string compositeResearch = member(specificationData, "composite research") ?
specificationData["composite research"] : 0;
if(initiator && objectp(initiator) &&
(canExecuteCommand(command) || (compositeResearch == command)) &&
function_exists("isResearched", initiator) &&
initiator->isResearched(researchName))
{
notify_fail("");
ret = 1;
if(initiator->blockedByCooldown(researchName))
{
string coolDownMessage =
(member(specificationData, "use ability cooldown message") &&
stringp(specificationData["use ability cooldown message"])) ?
specificationData["use ability cooldown message"] :
sprintf("You must wait longer before you use '%s' again.\n",
member(specificationData, "name") ? specificationData["name"] :
"that skill");
displayMessageToSelf(coolDownMessage, initiator);
ret = 0;
}
mapping costs = getUsageCosts(command, initiator);
if(ret && ((costs["hit point cost"] > initiator->hitPoints()) ||
(costs["spell point cost"] > initiator->spellPoints()) ||
(costs["stamina point cost"] > initiator->staminaPoints())))
{
string costsTooMuch = sprintf("You do not have the required "
"energy reserve to use '%s'.\n", member(specificationData, "name") ?
specificationData["name"] : "that skill");
displayMessageToSelf(costsTooMuch, initiator);
ret = 0;
}
if(ret && (!initiator->spellAction() || compositeResearch))
{
ret = useConsumables(initiator) &&
applyToScope(command, initiator, researchName);
if (member(specificationData, "repeat effect"))
{
call_out("repeatEffect", 2, specificationData["repeat effect"],
command, initiator, researchName);
}
if(ret)
{
if(costs["hit point cost"])
{
initiator->hitPoints(-costs["hit point cost"]);
}
if(costs["spell point cost"])
{
initiator->spellPoints(-costs["spell point cost"]);
}
if(costs["stamina point cost"])
{
initiator->staminaPoints(-costs["stamina point cost"]);
}
}
initiator->spellAction(1);
}
}
return ret;
}
| 412 | 0.899437 | 1 | 0.899437 | game-dev | MEDIA | 0.726427 | game-dev | 0.854571 | 1 | 0.854571 |
DeltaV-Station/Delta-v | 8,721 | Content.Server/Objectives/Systems/PickObjectiveTargetSystem.cs | using Content.Server.Objectives.Components;
using Content.Shared.Mind;
using Content.Shared.Objectives.Components;
using Content.Shared.Roles; // DeltaV
using Content.Shared.Roles.Jobs; // DeltaV
using Content.Server.GameTicking.Rules;
using Content.Server.Revolutionary.Components;
using Robust.Shared.Prototypes; // DeltaV
using Robust.Shared.Random;
using System.Linq;
namespace Content.Server.Objectives.Systems;
/// <summary>
/// Handles assinging a target to an objective entity with <see cref="TargetObjectiveComponent"/> using different components.
/// These can be combined with condition components for objective completions in order to create a variety of objectives.
/// </summary>
public sealed class PickObjectiveTargetSystem : EntitySystem
{
[Dependency] private readonly TargetObjectiveSystem _target = default!;
[Dependency] private readonly SharedMindSystem _mind = default!;
[Dependency] private readonly SharedRoleSystem _role = default!; // DeltaV
[Dependency] private readonly IPrototypeManager _proto = default!; // DeltaV
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly TraitorRuleSystem _traitorRule = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PickSpecificPersonComponent, ObjectiveAssignedEvent>(OnSpecificPersonAssigned);
SubscribeLocalEvent<PickRandomPersonComponent, ObjectiveAssignedEvent>(OnRandomPersonAssigned);
SubscribeLocalEvent<PickRandomHeadComponent, ObjectiveAssignedEvent>(OnRandomHeadAssigned);
SubscribeLocalEvent<RandomTraitorProgressComponent, ObjectiveAssignedEvent>(OnRandomTraitorProgressAssigned);
SubscribeLocalEvent<RandomTraitorAliveComponent, ObjectiveAssignedEvent>(OnRandomTraitorAliveAssigned);
}
private void OnSpecificPersonAssigned(Entity<PickSpecificPersonComponent> ent, ref ObjectiveAssignedEvent args)
{
// invalid objective prototype
if (!TryComp<TargetObjectiveComponent>(ent.Owner, out var target))
{
args.Cancelled = true;
return;
}
// target already assigned
if (target.Target != null)
return;
if (args.Mind.OwnedEntity == null)
{
args.Cancelled = true;
return;
}
var user = args.Mind.OwnedEntity.Value;
if (!TryComp<TargetOverrideComponent>(user, out var targetComp) || targetComp.Target == null)
{
args.Cancelled = true;
return;
}
_target.SetTarget(ent.Owner, targetComp.Target.Value);
}
private void OnRandomPersonAssigned(Entity<PickRandomPersonComponent> ent, ref ObjectiveAssignedEvent args)
{
// Begin DeltaV Changes - replaced copy pasta with this
Predicate<EntityUid> pred = ent.Comp.OnlyChoosableJobs
? mindId =>
_role.MindHasRole<JobRoleComponent>(mindId, out var role) &&
role?.Comp1.JobPrototype is {} jobId &&
_proto.Index(jobId).SetPreference
: _ => true;
AssignRandomTarget(ent, ref args, pred);
// End DeltaV Changes - replaced copy pasta with this
}
private void OnRandomHeadAssigned(Entity<PickRandomHeadComponent> ent, ref ObjectiveAssignedEvent args)
{
// Begin DeltaV Changes - replaced copy pasta with this
AssignRandomTarget(ent, ref args, mindId =>
TryComp<MindComponent>(mindId, out var mind) &&
mind.OwnedEntity is { } ownedEnt &&
HasComp<CommandStaffComponent>(ownedEnt));
// End DeltaV Changes - replaced copy pasta with this
}
/// <summary>
/// DeltaV - Common code deduplicated from above functions.
/// Filters all alive humans and picks a target from them.
/// </summary>
private void AssignRandomTarget(EntityUid uid, ref ObjectiveAssignedEvent args, Predicate<EntityUid> filter, bool fallbackToAny = true)
{
// invalid prototype
if (!TryComp<TargetObjectiveComponent>(uid, out var target))
{
args.Cancelled = true;
return;
}
// target already assigned
if (target.Target != null)
return;
// Get all alive humans, filter out any with TargetObjectiveImmuneComponent
var allHumans = _mind.GetAliveHumans(args.MindId)
.Where(mindId =>
{
if (!TryComp<MindComponent>(mindId, out var mindComp) || mindComp.OwnedEntity == null)
return false;
return !HasComp<TargetObjectiveImmuneComponent>(mindComp.OwnedEntity.Value);
})
.ToList();
// Can't have multiple objectives to kill the same person
foreach (var objective in args.Mind.Objectives)
{
if (HasComp<KillPersonConditionComponent>(objective) && TryComp<TargetObjectiveComponent>(objective, out var kill))
{
allHumans.RemoveAll(x => x.Owner == kill.Target);
}
}
// Filter out targets based on the filter
var filteredHumans = allHumans.Where(mind => filter(mind)).ToList();
// There's no humans and we can't fall back to any other target
if (filteredHumans.Count == 0 && !fallbackToAny)
{
args.Cancelled = true;
return;
}
// Pick between humans matching our filter or fall back to all humans alive
var selectedHumans = filteredHumans.Count > 0 ? filteredHumans : allHumans;
// Still no valid targets even after the fallback
if (selectedHumans.Count == 0)
{
args.Cancelled = true;
return;
}
_target.SetTarget(uid, _random.Pick(selectedHumans), target);
}
private void OnRandomTraitorProgressAssigned(Entity<RandomTraitorProgressComponent> ent, ref ObjectiveAssignedEvent args)
{
// invalid prototype
if (!TryComp<TargetObjectiveComponent>(ent.Owner, out var target))
{
args.Cancelled = true;
return;
}
var traitors = _traitorRule.GetOtherTraitorMindsAliveAndConnected(args.Mind).ToHashSet();
// cant help anyone who is tasked with helping:
// 1. thats boring
// 2. no cyclic progress dependencies!!!
foreach (var traitor in traitors)
{
// TODO: replace this with TryComp<ObjectivesComponent>(traitor) or something when objectives are moved out of mind
if (!TryComp<MindComponent>(traitor.Id, out var mind))
continue;
foreach (var objective in mind.Objectives)
{
if (HasComp<HelpProgressConditionComponent>(objective))
traitors.RemoveWhere(x => x.Mind == mind);
}
}
// Can't have multiple objectives to help/save the same person
foreach (var objective in args.Mind.Objectives)
{
if (HasComp<RandomTraitorAliveComponent>(objective) || HasComp<RandomTraitorProgressComponent>(objective))
{
if (TryComp<TargetObjectiveComponent>(objective, out var help))
{
traitors.RemoveWhere(x => x.Id == help.Target);
}
}
}
// no more helpable traitors
if (traitors.Count == 0)
{
args.Cancelled = true;
return;
}
_target.SetTarget(ent.Owner, _random.Pick(traitors).Id, target);
}
private void OnRandomTraitorAliveAssigned(Entity<RandomTraitorAliveComponent> ent, ref ObjectiveAssignedEvent args)
{
// invalid prototype
if (!TryComp<TargetObjectiveComponent>(ent.Owner, out var target))
{
args.Cancelled = true;
return;
}
var traitors = _traitorRule.GetOtherTraitorMindsAliveAndConnected(args.Mind).ToHashSet();
// Can't have multiple objectives to help/save the same person
foreach (var objective in args.Mind.Objectives)
{
if (HasComp<RandomTraitorAliveComponent>(objective) || HasComp<RandomTraitorProgressComponent>(objective))
{
if (TryComp<TargetObjectiveComponent>(objective, out var help))
{
traitors.RemoveWhere(x => x.Id == help.Target);
}
}
}
// You are the first/only traitor.
if (traitors.Count == 0)
{
args.Cancelled = true;
return;
}
_target.SetTarget(ent.Owner, _random.Pick(traitors).Id, target);
}
}
| 412 | 0.903929 | 1 | 0.903929 | game-dev | MEDIA | 0.927817 | game-dev | 0.905646 | 1 | 0.905646 |
reduz/larvita3 | 1,197 | types/script/script_language.h | //
// C++ Interface: script_language
//
// Description:
//
//
// Author: Juan Linietsky <reduzio@gmail.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef SCRIPT_LANGUAGE_H
#define SCRIPT_LANGUAGE_H
#include "script.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class ScriptLanguage;
class ScriptServer {
friend class ScriptLanguage;
enum {
MAX_LANGUAGES=4
};
static ScriptLanguage *_languages[MAX_LANGUAGES];
public:
static IRef<Script> create(String p_type);
static IRef<Script> load(String p_path);
static IRef<Script> parse(String p_text,String p_type);
static Error load_code(String p_path);
static Error parse_code(String p_text,String p_type);
};
class ScriptLanguage {
public:
virtual IRef<Script> create_script()=0; ///< Create a script object for instance
virtual Error parse_code(String p_text)=0; ///< Parse code from text
virtual Error load_code(String p_path)=0; ///M Parse code from a file
virtual String get_type() const=0; ///< "lua"/"python"/"brainfuck"/etc
virtual String get_extension() const=0; ///< ".lua"/".py"/".bf"
ScriptLanguage();
virtual ~ScriptLanguage();
};
#endif
| 412 | 0.560029 | 1 | 0.560029 | game-dev | MEDIA | 0.617407 | game-dev | 0.639005 | 1 | 0.639005 |
Disservin/Smallbrain | 2,732 | src/tests/testFenRepetition.h | #pragma once
#include "../str_utils.h"
#include "../uci.h"
#include "tests.h"
namespace tests {
inline bool testFenRepetition(const std::string &input) {
Board board;
std::vector<std::string> tokens = str_util::splitString(input, ' ');
bool hasMoves = str_util::contains(tokens, "moves");
if (tokens[1] == "fen")
board.setFen(input.substr(input.find("fen") + 4), false);
else
board.setFen(DEFAULT_POS, false);
if (hasMoves) {
std::size_t index = std::find(tokens.begin(), tokens.end(), "moves") - tokens.begin();
index++;
for (; index < tokens.size(); index++) {
Move move = uci::uciToMove(board, tokens[index]);
board.makeMove<false>(move);
}
}
board.refreshNNUE(board.getAccumulator());
return board.isRepetition(2);
}
inline void repetition1() {
std::string input =
"position fen r2qk2r/pp3pp1/2nbpn1p/8/6b1/2NP1N2/PPP1BPPP/R1BQ1RK1 w - - 0 1 moves h2h3 "
"g4f5 d3d4 e8h8 e2d3 "
"f5d3 d1d3 a8c8 a2a3 f8e8 f1e1 e6e5 d4e5 c6e5 f3e5 d6e5 d3d8 c8d8 c3d1 f6e4 d1e3 e5d4 g1f1 "
"d4c5 e1d1 d8d1 e3d1 "
"c5f2 d1f2 e4g3 f1g1 e8e1 g1h2 g3f1 h2g1 f1g3 g1h2 g3f1 h2g1 f1g3 ";
expect(testFenRepetition(input), true, "Repetition 1");
}
inline void repetition2() {
std::string input =
"position fen 6Q1/1p1k3p/3b2p1/p6r/3P1PR1/1PR2NK1/P3q2P/4r3 b - - 14 37 moves e1f1 f3e5 "
"d6e5 g8f7 d7d8 "
"f7f8 d8d7 f8f7 d7d8 f7f8 d8d7 f8f7";
expect(testFenRepetition(input), true, "Repetition 2");
}
inline void repetition3() {
std::string input =
"position fen rn2k1nr/pp2bppp/2p5/q3p3/2B5/P1N2b1P/1PPP1PP1/R1BQ1RK1 w - - 0 1 moves d1f3 "
"g8f6 c3e2 e8h8 "
"e2g3 b8d7 d2d3 a5c7 g3f5 e7d8 c4a2 a7a5 f3g3 f6h5 g3f3 h5f6 f3g3 f6h5 g3f3 h5f6";
expect(testFenRepetition(input), true, "Repetition 3");
}
inline void repetition4() {
std::string input =
"position fen rnbqk2r/1pp2ppp/p2bpn2/8/2NP1B2/3B1N2/PPP2PPP/R2QK2R w - - 0 1 moves c4d6 "
"c7d6 c2c4 e8h8 "
"e1h1 b7b6 f1e1 c8b7 f4g3 f8e8 a1c1 h7h6 d3b1 b6b5 b2b3 b5c4 b3c4 d8b6 c4c5 d6c5 d4c5 b6c6 "
"b1c2 c6d5 g3d6 "
"e8c8 c2b3 d5d1 e1d1 a6a5 f3d4 a5a4 b3c4 b7d5 a2a3 b8c6 c4d5 f6d5 d4c6 c8c6 c1c4 d5c7 d1b1 "
"c7e8 d6f4 a8c8 "
"b1b8 c8b8 f4b8 f7f6 g1f1 g8f7 f2f4 g7g5 g2g3 f7g6 f1e2 c6c8 b8a7 e8c7 e2d3 c8d8 d3e4 f6f5 "
"e4e3 d8a8 a7b6 "
"c7d5 e3d4 a8a6 b6d8 a6a8 d8b6 a8a6 b6d8 a6a8 d8b6";
expect(testFenRepetition(input), true, "Repetition 4");
}
inline void testAllFenRepetitions() {
repetition1();
repetition2();
repetition3();
repetition4();
}
} // namespace tests
| 412 | 0.851075 | 1 | 0.851075 | game-dev | MEDIA | 0.362966 | game-dev | 0.88319 | 1 | 0.88319 |
quiverteam/Engine | 1,547 | src/game/server/hl2/weapon_tripwire.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: TRIPWIRE
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#ifndef WEAPONTRIPWIRE_H
#define WEAPONTRIPWIRE_H
#include "basegrenade_shared.h"
#include "basehlcombatweapon.h"
enum TripwireState_t
{
TRIPWIRE_TRIPMINE_READY,
TRIPWIRE_SATCHEL_THROW,
TRIPWIRE_SATCHEL_ATTACH,
};
class CWeapon_Tripwire : public CBaseHLCombatWeapon
{
public:
DECLARE_CLASS( CWeapon_Tripwire, CBaseHLCombatWeapon );
DECLARE_SERVERCLASS();
bool m_bNeedReload;
bool m_bClearReload;
bool m_bAttachTripwire;
void Spawn( void );
void Precache( void );
int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; }
void PrimaryAttack( void );
void SecondaryAttack( void );
void WeaponIdle( void );
void WeaponSwitch( void );
void SetPickupTouch( void );
void TripwireTouch( CBaseEntity *pOther ); // default weapon touch
void ItemPostFrame( void );
bool Reload( void );
bool CanAttachTripwire(void); // In position where can attach TRIPWIRE?
void StartTripwireAttach( void );
void TripwireAttach( void );
bool Deploy( void );
bool Holster( CBaseCombatWeapon *pSwitchingTo = NULL );
CWeapon_Tripwire();
DECLARE_ACTTABLE();
DECLARE_DATADESC();
};
#endif //WEAPONTRIPWIRE_H
| 412 | 0.931404 | 1 | 0.931404 | game-dev | MEDIA | 0.940209 | game-dev | 0.555977 | 1 | 0.555977 |
pret/pokeheartgold | 3,699 | files/fielddata/script/scr_seq/scr_seq_0260_R47.s | #include "constants/scrcmd.h"
#include "fielddata/script/scr_seq/event_R47.h"
#include "msgdata/msg/msg_0407_R47.h"
.include "asm/macros/script.inc"
.rodata
scrdef scr_seq_R47_000
scrdef scr_seq_R47_001
scrdef scr_seq_R47_002
scrdef scr_seq_R47_003
scrdef scr_seq_R47_004
scrdef_end
scr_seq_R47_000:
setvar VAR_UNK_40EB, 1
setflag FLAG_UNK_9C9
get_game_version VAR_TEMP_x4000
compare VAR_TEMP_x4000, 7
goto_if_ne _004F
move_warp 4, 87, 385
move_warp 5, 87, 389
move_warp 6, 87, 385
goto _0067
_004F:
move_warp 4, 87, 389
move_warp 5, 87, 385
move_warp 6, 87, 385
_0067:
compare VAR_SCENE_EMBEDDED_TOWER, 2
goto_if_eq _00E6
compare VAR_SCENE_EMBEDDED_TOWER, 3
goto_if_eq _00E6
compare VAR_SCENE_EMBEDDED_TOWER, 5
goto_if_ge _00EC
goto_if_unset FLAG_UNK_189, _009F
clearflag FLAG_UNK_189
end
_009F:
goto_if_set FLAG_GAME_CLEAR, _00B2
goto _00E6
end
_00B2:
get_phone_book_rematch PHONE_CONTACT_CHUCK, VAR_TEMP_x4001
compare VAR_TEMP_x4001, 0
goto_if_ne _00E6
get_weekday VAR_TEMP_x4002
compare VAR_TEMP_x4002, 0
goto_if_ne _00E0
clearflag FLAG_HIDE_ROUTE_47_CHUCK
goto _00E4
_00E0:
setflag FLAG_HIDE_ROUTE_47_CHUCK
_00E4:
end
_00E6:
setflag FLAG_HIDE_ROUTE_47_CHUCK
end
_00EC:
move_warp 4, 87, 385
move_warp 5, 87, 385
move_warp 6, 87, 389
goto _00E6
end
scr_seq_R47_002:
compare VAR_SCENE_EMBEDDED_TOWER, 5
goto_if_ge _0162
get_game_version VAR_TEMP_x4000
compare VAR_TEMP_x4000, 7
goto_if_ne _0148
move_warp 4, 87, 385
move_warp 5, 87, 389
move_warp 6, 87, 385
goto _0160
_0148:
move_warp 4, 87, 389
move_warp 5, 87, 385
move_warp 6, 87, 385
_0160:
end
_0162:
move_warp 4, 87, 385
move_warp 5, 87, 385
move_warp 6, 87, 389
end
scr_seq_R47_001:
play_se SEQ_SE_DP_SELECT
lockall
faceplayer
goto_if_set FLAG_MET_ROUTE_47_EMBEDDED_TOWER_HIKER, _019E
npc_msg msg_0407_R47_00000
wait_button_or_walk_away
closemsg
setflag FLAG_MET_ROUTE_47_EMBEDDED_TOWER_HIKER
releaseall
end
_019E:
npc_msg msg_0407_R47_00001
wait_button_or_walk_away
closemsg
releaseall
end
scr_seq_R47_003:
play_se SEQ_SE_DP_SELECT
lockall
faceplayer
goto_if_set FLAG_UNK_157, _0210
npc_msg msg_0407_R47_00002
apply_movement obj_R47_leader3, _022C
wait_movement
npc_msg msg_0407_R47_00003
get_player_facing VAR_SPECIAL_RESULT
compare VAR_SPECIAL_RESULT, 0
goto_if_ne _01EB
apply_movement obj_R47_leader3, _0234
goto _020E
_01EB:
compare VAR_SPECIAL_RESULT, 3
goto_if_ne _0206
apply_movement obj_R47_leader3, _023C
goto _020E
_0206:
apply_movement obj_R47_leader3, _0244
_020E:
wait_movement
_0210:
buffer_players_name 0
npc_msg msg_0407_R47_00004
closemsg
apply_movement obj_R47_leader3, _022C
wait_movement
setflag FLAG_UNK_157
releaseall
end
.balign 4, 0
_022C:
step 32, 1
step_end
.balign 4, 0
_0234:
step 33, 1
step_end
.balign 4, 0
_023C:
step 34, 1
step_end
.balign 4, 0
_0244:
step 35, 1
step_end
scr_seq_R47_004:
play_se SEQ_SE_DP_SELECT
lockall
faceplayer
npc_msg msg_0407_R47_00005
touchscreen_menu_hide
getmenuchoice VAR_SPECIAL_RESULT
touchscreen_menu_show
compare VAR_SPECIAL_RESULT, 1
goto_if_eq _02B5
photo_album_is_full VAR_SPECIAL_RESULT
compare VAR_SPECIAL_RESULT, 1
goto_if_eq _02C0
npc_msg msg_0407_R47_00006
closemsg
setflag FLAG_UNK_189
fade_screen 6, 1, 0, RGB_BLACK
wait_fade
cameron_photo 91
faceplayer
lockall
fade_screen 6, 1, 1, RGB_BLACK
wait_fade
clearflag FLAG_UNK_189
npc_msg msg_0407_R47_00007
wait_button_or_walk_away
closemsg
releaseall
end
_02B5:
npc_msg msg_0407_R47_00008
wait_button_or_walk_away
closemsg
releaseall
end
_02C0:
npc_msg msg_0407_R47_00009
wait_button_or_walk_away
closemsg
releaseall
end
.balign 4, 0
| 412 | 0.624699 | 1 | 0.624699 | game-dev | MEDIA | 0.927192 | game-dev | 0.676921 | 1 | 0.676921 |
oiuv/mud | 2,961 | kungfu/skill/qiufeng-chenfa.c | // qiufeng-chenfa.c 秋风拂尘
#include <ansi.h>
inherit SKILL;
mapping *action = ({
([ "action": "$N端坐不动,一招「秋风拂叶」,手中$w带着一股劲风,击向$n的脸颊",
"force" : 40,
"dodge" : 20,
"damage": 20,
"lvl" : 0,
"skill_name" : "秋风拂叶",
"damage_type": "刮伤"
]),
([ "action": "$N单臂一挥,一招「玉带围腰」,手中$w直绕向$n的身后",
"force" : 70,
"dodge" : 15,
"damage": 30,
"lvl" : 20,
"skill_name" : "玉带围腰",
"damage_type": "内伤"
]),
([ "action": "$N身形一转,一招「流云断川」,手中$w如矫龙般腾空一卷,猛地向$n劈头打下",
"force" : 80,
"dodge" : 25,
"damage": 35,
"lvl" : 40,
"skill_name" : "流云断川",
"damage_type": "劈伤"
]),
([ "action": "$N力贯尘梢,一招「春风化雨」,手中$w舞出满天幻影,排山倒海般扫向$n全身",
"force" : 100,
"dodge" : 15,
"damage": 50,
"lvl" : 50,
"skill_name" : "春风化雨",
"damage_type": "刺伤"
]),
([ "action": "$N忽的向前一跃,一招「野马分鬃」,手中$w分击$n左右",
"force" : 110,
"dodge" : 30,
"damage": 55,
"lvl" : 60,
"skill_name" : "野马分鬃",
"damage_type": "刺伤"
]),
([ "action": "$N慢步上前,一招「竹影扫阶」,手中$w缓缓罩向$n前胸",
"force" : 130,
"dodge" : 20,
"damage": 60,
"lvl" : 70,
"skill_name" : "竹影扫阶",
"damage_type": "内伤"
])
});
int valid_enable(string usage) { return (usage == "whip") || (usage == "parry"); }
int valid_learn(object me)
{
object weapon;
if ( !objectp(weapon = me->query_temp("weapon"))
|| ( string)weapon->query("skill_type") != "whip" )
return notify_fail("你必须先找一条拂尘才能练尘法。\n");
if( (int)me->query("max_neili") < 300 )
return notify_fail("你的内力不足,没有办法练秋风尘法, 多练些内力再来吧。\n");
if ((int)me->query_skill("force") < 60)
return notify_fail("你的内功火候太浅。\n");
if ((int)me->query_skill("whip", 1) < (int)me->query_skill("qiufeng-chenfa", 1))
return notify_fail("你的基本鞭法火候不足,难以领会更高深的秋风尘法。\n");
return 1;
}
string query_skill_name(int level)
{
int i;
for (i = sizeof(action)-1; i >= 0; i--)
if (level >= action[i]["lvl"])
return action[i]["skill_name"];
}
mapping query_action(object me, object weapon)
{
int i, level;
level = (int) me->query_skill("qiufeng-chenfa", 1);
for (i = sizeof(action); i > 0; i--)
if (level > action[i-1]["lvl"])
return action[NewRandom(i, 20, level / 5)];
}
int practice_skill(object me)
{
object weapon;
if (!objectp(weapon = me->query_temp("weapon"))
|| (string)weapon->query("skill_type") != "whip")
return notify_fail("你使用的武器不对。\n");
if ((int)me->query("qi") < 50)
return notify_fail("你的体力不够练秋风尘法。\n");
if ((int)me->query("neili") < 30)
return notify_fail("你的体力不够练秋风尘法。\n");
me->receive_damage("qi", 35);
me->add("neili", -10);
return 1;
}
string perform_action_file(string action)
{
if ( this_player()->query_skill("qiufeng-chenfa", 1) >= 40 )
return __DIR__"qiufeng-chenfa/" + action;
}
| 412 | 0.885155 | 1 | 0.885155 | game-dev | MEDIA | 0.937775 | game-dev | 0.788643 | 1 | 0.788643 |
liady/solar-hands | 1,672 | src/detectors/orbitDetector.js | import { findAngleBetweenPoints, range } from "../common/util";
import events from "../common/events";
const orbitCandidate = { right: false, left: false };
export function detectOrbit(hand, handness) {
const fingers = ["index_finger", "middle_finger", "ring_finger"];
const startOrbit = fingers.every((fingerName) =>
isStraightAndVertical(hand, handness, fingerName)
);
if (startOrbit) {
const prev = orbitCandidate[handness];
if (prev) {
const current = hand.index_finger_tip;
const deltaX = current.x - prev.x;
const deltaY = current.y - prev.y;
const sensitivity = 2;
if (Math.abs(deltaX) > sensitivity && Math.abs(deltaY) > sensitivity) {
events.publish("orbit", {
hand,
handness,
deltaX,
deltaY,
});
orbitCandidate[handness] = hand.index_finger_tip;
}
} else {
orbitCandidate[handness] = hand.index_finger_tip;
}
} else {
orbitCandidate[handness] = false;
}
}
function isStraightAndVertical(hand, handness, fingerName) {
const topAngle = findAngleBetweenPoints(
hand[`${fingerName}_tip`],
hand[`${fingerName}_dip`]
);
const middleAngle = findAngleBetweenPoints(
hand[`${fingerName}_dip`],
hand[`${fingerName}_pip`]
);
const bottomAngle = findAngleBetweenPoints(
hand[`${fingerName}_pip`],
hand[`${fingerName}_mcp`]
);
const STRAIGHT_THRES = handness === "right" ? 90 : 88;
const anglesRange = range([topAngle, middleAngle, bottomAngle]);
const straight = Math.abs(anglesRange) < 15;
const vertical = Math.abs(bottomAngle - STRAIGHT_THRES) < 10;
return straight && vertical;
}
| 412 | 0.71701 | 1 | 0.71701 | game-dev | MEDIA | 0.519665 | game-dev | 0.76088 | 1 | 0.76088 |
stohrendorf/CroftEngine | 6,059 | src/engine/objects/pickupobject.cpp | #include "pickupobject.h"
#include "core/angle.h"
#include "core/boundingbox.h"
#include "core/genericvec.h"
#include "core/id.h"
#include "core/units.h"
#include "core/vec.h"
#include "engine/inventory.h"
#include "engine/items_tr1.h"
#include "engine/objectmanager.h"
#include "engine/objects/spriteobject.h"
#include "engine/player.h"
#include "engine/presenter.h"
#include "engine/skeletalmodelnode.h"
#include "engine/world/skeletalmodeltype.h"
#include "engine/world/world.h"
#include "hid/actions.h"
#include "hid/inputhandler.h"
#include "laraobject.h"
#include "loader/file/larastateid.h"
#include "object.h"
#include "objectstate.h"
#include "qs/quantity.h"
#include "render/scene/node.h"
#include "serialization/serialization.h"
#include <boost/assert.hpp>
#include <memory>
#include <vector>
namespace engine::objects
{
void PickupObject::collide(CollisionInfo& /*collisionInfo*/)
{
m_state.rotation.Y = getWorld().getObjectManager().getLara().m_state.rotation.Y;
m_state.rotation.Z = 0_deg;
if(getWorld().getObjectManager().getLara().isDiving())
{
static const InteractionLimits limits{
core::BoundingBox{{-512_len, -512_len, -512_len}, {512_len, 512_len, 512_len}},
{-45_deg, -45_deg, -45_deg},
{+45_deg, +45_deg, +45_deg}};
m_state.rotation.X = -25_deg;
if(!limits.canInteract(m_state, getWorld().getObjectManager().getLara().m_state))
{
return;
}
static const core::GenericVec<core::Speed> aimSpeed{0_spd, -200_spd, -350_spd};
if(getWorld().getObjectManager().getLara().getCurrentAnimState() == loader::file::LaraStateId::PickUp)
{
if(getWorld().getObjectManager().getLara().getSkeleton()->getFrame() == 2970_frame)
{
m_state.triggerState = TriggerState::Invisible;
++getWorld().getPlayer().pickups;
const auto oldType = m_state.type;
const auto oldSprite = getSprite();
const auto count = getWorld().getPlayer().getInventory().put(m_state.type, &getWorld());
getWorld().addPickupWidget(getSprite(), count);
if(oldType != m_state.type)
getWorld().addPickupWidget(oldSprite, 1);
getNode()->clear();
m_state.collidable = false;
return;
}
}
else if(getWorld().getPresenter().getInputHandler().hasAction(hid::Action::Action)
&& getWorld().getObjectManager().getLara().getCurrentAnimState()
== loader::file::LaraStateId::UnderwaterStop
&& getWorld().getObjectManager().getLara().alignTransform(aimSpeed, *this))
{
getWorld().getObjectManager().getLara().setGoalAnimState(loader::file::LaraStateId::PickUp);
do
{
getWorld().getObjectManager().getLara().advanceFrame();
} while(getWorld().getObjectManager().getLara().getCurrentAnimState() != loader::file::LaraStateId::PickUp);
getWorld().getObjectManager().getLara().setGoalAnimState(loader::file::LaraStateId::UnderwaterStop);
}
}
else if(getWorld().getObjectManager().getLara().isOnLand())
{
static const InteractionLimits limits{
core::BoundingBox{{-256_len, -100_len, -256_len}, {256_len, 100_len, 100_len}},
{-10_deg, 0_deg, 0_deg},
{+10_deg, 0_deg, 0_deg}};
m_state.rotation.X = 0_deg;
if(!limits.canInteract(m_state, getWorld().getObjectManager().getLara().m_state))
{
return;
}
if(getWorld().getObjectManager().getLara().getCurrentAnimState() != loader::file::LaraStateId::PickUp)
{
if(getWorld().getPresenter().getInputHandler().hasAction(hid::Action::Action)
&& getWorld().getObjectManager().getLara().getHandStatus() == HandStatus::None
&& !getWorld().getObjectManager().getLara().m_state.falling
&& getWorld().getObjectManager().getLara().getCurrentAnimState() == loader::file::LaraStateId::Stop)
{
getWorld().getObjectManager().getLara().alignForInteraction(core::TRVec{0_len, 0_len, -100_len}, m_state);
getWorld().getObjectManager().getLara().setGoalAnimState(loader::file::LaraStateId::PickUp);
do
{
getWorld().getObjectManager().getLara().advanceFrame();
} while(getWorld().getObjectManager().getLara().getCurrentAnimState() != loader::file::LaraStateId::PickUp);
getWorld().getObjectManager().getLara().setGoalAnimState(loader::file::LaraStateId::Stop);
getWorld().getObjectManager().getLara().setHandStatus(HandStatus::Grabbing);
}
}
else if(const auto& laraSkeleton = getWorld().getObjectManager().getLara().getSkeleton();
laraSkeleton->getFrame() == 3443_frame)
{
if(m_state.type == TR1ItemId::ShotgunSprite)
{
const auto& shotgunLara = *getWorld().getWorldGeometry().findAnimatedModelForType(TR1ItemId::LaraShotgunAnim);
BOOST_ASSERT(shotgunLara.bones.size() == laraSkeleton->getBoneCount());
laraSkeleton->setMesh(7, shotgunLara.bones[7].mesh);
laraSkeleton->rebuildMesh();
}
m_state.triggerState = TriggerState::Invisible;
++getWorld().getPlayer().pickups;
const auto oldType = m_state.type;
const auto oldSprite = getSprite();
const auto count = getWorld().getPlayer().getInventory().put(m_state.type, &getWorld());
getWorld().addPickupWidget(getSprite(), count);
if(oldType != m_state.type)
getWorld().addPickupWidget(oldSprite, 1);
getNode()->clear();
m_state.collidable = false;
}
}
}
void PickupObject::serialize(const serialization::Serializer<world::World>& ser) const
{
SpriteObject::serialize(ser);
}
void PickupObject::deserialize(const serialization::Deserializer<world::World>& ser)
{
SpriteObject::deserialize(ser);
// need a double-dispatch because the node is already lazily associated with its room
ser << [this](const serialization::Deserializer<world::World>& ser)
{
ser << [this](const serialization::Deserializer<world::World>& /*ser*/)
{
if(!m_state.collidable)
getNode()->clear();
};
};
}
} // namespace engine::objects
| 412 | 0.94328 | 1 | 0.94328 | game-dev | MEDIA | 0.93382 | game-dev | 0.952216 | 1 | 0.952216 |
D363N6UY/MapleStory-v113-Server-Eimulator | 3,695 | Libs/scripts/npc/9120034.js | /*
Noran
*/
var status = -1;
function start() {
cm.sendSimple("How can I help you? \r #b#L0#I want to release seal on Sealed Warrior Stone.#l \r #L1#I want to create item.#l");
}
function action(mode, type, selection) {
if (mode == 1) {
status++;
} else if (status == 1) {
status--;
selection = 0;
} else {
cm.dispose();
return;
}
switch (status) {
case 0:
if (selection == 0) {
cm.sendNext("My name is Noran, technical personnel. Here, everyone is talking about you. If you could defeat mechanic monster, I wish to help you too. With blaze technology, more powerful item can be created.")
} else {
status = 9;
cm.sendSimple("How can I help you? \r #b#L0#Magic Throwing Knife#l \r #L1#Armor-Piercing Bullet#l");
}
break;
case 1:
cm.sendNextPrev("It's been said that Blaze has succeeded to collect energy floating in universe. If this is true, massive energy can be obtained. Small portion of this energy can be extracted from Sealed Warrior Stone but it must be unsealed in order to be used. Bring it to me and i will release it's seal.");
break;
case 2:
cm.sendSimple("Give me the sealed stone \r #b#L0#Give Sealed Warrior Stone and service fee. 1,000 Silver Coin#l \r #L1#Give Sealed Wiseman Stone and service fee. 1,000 Silver Coin#l \r #L2#Give Sealed Saint Stone and service fee. 1,000 Silver Coin#l");
break;
case 3:
if (selection == 0) {
if (cm.haveItem(4020010, 1) && cm.haveItem(4032181, 1000)) {
cm.gainItem(4032169, 1);
cm.gainItem(4020010, -1);
cm.gainItem(4032181, -1000);
} else {
cm.sendNext("Eh? You don't have required materials. \n\r You need Sealed Warrior Stone and 1,000 Silver Coin to create Warrior Stone.");
}
} else if (selection == 1) {
if (cm.haveItem(4020011, 1) && cm.haveItem(4032181, 1000)) {
cm.gainItem(4032170, 1);
cm.gainItem(4020011, -1);
cm.gainItem(4032181, -1000);
} else {
cm.sendNext("Eh? You don't have required materials. \n\r You need Sealed Wiseman Stone and 1,000 Silver Coin to create Wiseman Stone.");
}
} else {
if (cm.haveItem(4020012, 1) && cm.haveItem(4032181, 1000)) {
cm.gainItem(4032171, 1);
cm.gainItem(4020011, -1);
cm.gainItem(4032181, -1000);
} else {
cm.sendNext("Eh? You don't have required materials. \n\r You need Sealed Saint Stone and 1,000 Silver Coin to create Saint stone.");
}
}
cm.dispose();
break;
case 10:
if (selection == 0) {
if (cm.haveItem(4032168, 1) && cm.haveItem(4032181, 2500) && cm.haveItem(4032171, 1) && cm.haveItem(2070006, 1) && (cm.getMeso() >= 500000000)) {
cm.gainItem(4032171, -1);
cm.gainItem(4032168, -1);
cm.gainItem(2070006, -1);
cm.gainItem(4032181, -2500);
cm.gainMeso(-500000000);
cm.gainItem(2070019, 1);
} else {
cm.sendNext("Eh? You don't have required materials.\n\r You need Nano Plant (Omega), Wiseman Stone, 1 Ilbi Throwing-Stars, Silver Coin 2,500 Pieces and 500,000,000 meso to create Magic Throwing Knife.");
}
} else {
if (cm.haveItem(4032168, 1) && cm.haveItem(4032181, 2500) && cm.haveItem(4032170, 1) && cm.haveItem(2330003, 1) && (cm.getMeso() >= 500000000)) {
cm.gainItem(4032170, -1);
cm.gainItem(4032168, -1);
cm.gainItem(2330003, -1);
cm.gainItem(4032181, -2500);
cm.gainMeso(-500000000);
cm.gainItem(2330007, 1);
} else {
cm.sendNext("Eh? You don't have required materials.\n\r You need Nano Plant (Omega), Saint Stone, 1 Vital Bullet, Silver Coin 2,500 Pieces and 500,000,000 meso to create Armor Piercing bullet.");
}
}
cm.dispose();
break;
}
} | 412 | 0.655141 | 1 | 0.655141 | game-dev | MEDIA | 0.967828 | game-dev | 0.850384 | 1 | 0.850384 |
thegatesbrowser/thegates-old | 9,632 | thirdparty/icu4c/common/brkeng.cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
************************************************************************************
* Copyright (C) 2006-2016, International Business Machines Corporation
* and others. All Rights Reserved.
************************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_BREAK_ITERATION
#include "unicode/uchar.h"
#include "unicode/uniset.h"
#include "unicode/chariter.h"
#include "unicode/ures.h"
#include "unicode/udata.h"
#include "unicode/putil.h"
#include "unicode/ustring.h"
#include "unicode/uscript.h"
#include "unicode/ucharstrie.h"
#include "unicode/bytestrie.h"
#include "brkeng.h"
#include "cmemory.h"
#include "dictbe.h"
#include "lstmbe.h"
#include "charstr.h"
#include "dictionarydata.h"
#include "mutex.h"
#include "uvector.h"
#include "umutex.h"
#include "uresimp.h"
#include "ubrkimpl.h"
U_NAMESPACE_BEGIN
/*
******************************************************************
*/
LanguageBreakEngine::LanguageBreakEngine() {
}
LanguageBreakEngine::~LanguageBreakEngine() {
}
/*
******************************************************************
*/
LanguageBreakFactory::LanguageBreakFactory() {
}
LanguageBreakFactory::~LanguageBreakFactory() {
}
/*
******************************************************************
*/
UnhandledEngine::UnhandledEngine(UErrorCode &status) : fHandled(nullptr) {
(void)status;
}
UnhandledEngine::~UnhandledEngine() {
delete fHandled;
fHandled = nullptr;
}
UBool
UnhandledEngine::handles(UChar32 c) const {
return fHandled && fHandled->contains(c);
}
int32_t
UnhandledEngine::findBreaks( UText *text,
int32_t /* startPos */,
int32_t endPos,
UVector32 &/*foundBreaks*/,
UBool /* isPhraseBreaking */,
UErrorCode &status) const {
if (U_FAILURE(status)) return 0;
UChar32 c = utext_current32(text);
while((int32_t)utext_getNativeIndex(text) < endPos && fHandled->contains(c)) {
utext_next32(text); // TODO: recast loop to work with post-increment operations.
c = utext_current32(text);
}
return 0;
}
void
UnhandledEngine::handleCharacter(UChar32 c) {
if (fHandled == nullptr) {
fHandled = new UnicodeSet();
if (fHandled == nullptr) {
return;
}
}
if (!fHandled->contains(c)) {
UErrorCode status = U_ZERO_ERROR;
// Apply the entire script of the character.
int32_t script = u_getIntPropertyValue(c, UCHAR_SCRIPT);
fHandled->applyIntPropertyValue(UCHAR_SCRIPT, script, status);
}
}
/*
******************************************************************
*/
ICULanguageBreakFactory::ICULanguageBreakFactory(UErrorCode &/*status*/) {
fEngines = 0;
}
ICULanguageBreakFactory::~ICULanguageBreakFactory() {
if (fEngines != 0) {
delete fEngines;
}
}
U_NAMESPACE_END
U_CDECL_BEGIN
static void U_CALLCONV _deleteEngine(void *obj) {
delete (const icu::LanguageBreakEngine *) obj;
}
U_CDECL_END
U_NAMESPACE_BEGIN
const LanguageBreakEngine *
ICULanguageBreakFactory::getEngineFor(UChar32 c) {
const LanguageBreakEngine *lbe = nullptr;
UErrorCode status = U_ZERO_ERROR;
static UMutex gBreakEngineMutex;
Mutex m(&gBreakEngineMutex);
if (fEngines == nullptr) {
LocalPointer<UStack> engines(new UStack(_deleteEngine, nullptr, status), status);
if (U_FAILURE(status) ) {
// Note: no way to return error code to caller.
return nullptr;
}
fEngines = engines.orphan();
} else {
int32_t i = fEngines->size();
while (--i >= 0) {
lbe = (const LanguageBreakEngine *)(fEngines->elementAt(i));
if (lbe != nullptr && lbe->handles(c)) {
return lbe;
}
}
}
// We didn't find an engine. Create one.
lbe = loadEngineFor(c);
if (lbe != nullptr) {
fEngines->push((void *)lbe, status);
}
return U_SUCCESS(status) ? lbe : nullptr;
}
const LanguageBreakEngine *
ICULanguageBreakFactory::loadEngineFor(UChar32 c) {
UErrorCode status = U_ZERO_ERROR;
UScriptCode code = uscript_getScript(c, &status);
if (U_SUCCESS(status)) {
const LanguageBreakEngine *engine = nullptr;
// Try to use LSTM first
const LSTMData *data = CreateLSTMDataForScript(code, status);
if (U_SUCCESS(status)) {
if (data != nullptr) {
engine = CreateLSTMBreakEngine(code, data, status);
if (U_SUCCESS(status) && engine != nullptr) {
return engine;
}
if (engine != nullptr) {
delete engine;
engine = nullptr;
} else {
DeleteLSTMData(data);
}
}
}
status = U_ZERO_ERROR; // fallback to dictionary based
DictionaryMatcher *m = loadDictionaryMatcherFor(code);
if (m != nullptr) {
switch(code) {
case USCRIPT_THAI:
engine = new ThaiBreakEngine(m, status);
break;
case USCRIPT_LAO:
engine = new LaoBreakEngine(m, status);
break;
case USCRIPT_MYANMAR:
engine = new BurmeseBreakEngine(m, status);
break;
case USCRIPT_KHMER:
engine = new KhmerBreakEngine(m, status);
break;
#if !UCONFIG_NO_NORMALIZATION
// CJK not available w/o normalization
case USCRIPT_HANGUL:
engine = new CjkBreakEngine(m, kKorean, status);
break;
// use same BreakEngine and dictionary for both Chinese and Japanese
case USCRIPT_HIRAGANA:
case USCRIPT_KATAKANA:
case USCRIPT_HAN:
engine = new CjkBreakEngine(m, kChineseJapanese, status);
break;
#if 0
// TODO: Have to get some characters with script=common handled
// by CjkBreakEngine (e.g. U+309B). Simply subjecting
// them to CjkBreakEngine does not work. The engine has to
// special-case them.
case USCRIPT_COMMON:
{
UBlockCode block = ublock_getCode(code);
if (block == UBLOCK_HIRAGANA || block == UBLOCK_KATAKANA)
engine = new CjkBreakEngine(dict, kChineseJapanese, status);
break;
}
#endif
#endif
default:
break;
}
if (engine == nullptr) {
delete m;
}
else if (U_FAILURE(status)) {
delete engine;
engine = nullptr;
}
return engine;
}
}
return nullptr;
}
DictionaryMatcher *
ICULanguageBreakFactory::loadDictionaryMatcherFor(UScriptCode script) {
UErrorCode status = U_ZERO_ERROR;
// open root from brkitr tree.
UResourceBundle *b = ures_open(U_ICUDATA_BRKITR, "", &status);
b = ures_getByKeyWithFallback(b, "dictionaries", b, &status);
int32_t dictnlength = 0;
const char16_t *dictfname =
ures_getStringByKeyWithFallback(b, uscript_getShortName(script), &dictnlength, &status);
if (U_FAILURE(status)) {
ures_close(b);
return nullptr;
}
CharString dictnbuf;
CharString ext;
const char16_t *extStart = u_memrchr(dictfname, 0x002e, dictnlength); // last dot
if (extStart != nullptr) {
int32_t len = (int32_t)(extStart - dictfname);
ext.appendInvariantChars(UnicodeString(false, extStart + 1, dictnlength - len - 1), status);
dictnlength = len;
}
dictnbuf.appendInvariantChars(UnicodeString(false, dictfname, dictnlength), status);
ures_close(b);
UDataMemory *file = udata_open(U_ICUDATA_BRKITR, ext.data(), dictnbuf.data(), &status);
if (U_SUCCESS(status)) {
// build trie
const uint8_t *data = (const uint8_t *)udata_getMemory(file);
const int32_t *indexes = (const int32_t *)data;
const int32_t offset = indexes[DictionaryData::IX_STRING_TRIE_OFFSET];
const int32_t trieType = indexes[DictionaryData::IX_TRIE_TYPE] & DictionaryData::TRIE_TYPE_MASK;
DictionaryMatcher *m = nullptr;
if (trieType == DictionaryData::TRIE_TYPE_BYTES) {
const int32_t transform = indexes[DictionaryData::IX_TRANSFORM];
const char *characters = (const char *)(data + offset);
m = new BytesDictionaryMatcher(characters, transform, file);
}
else if (trieType == DictionaryData::TRIE_TYPE_UCHARS) {
const char16_t *characters = (const char16_t *)(data + offset);
m = new UCharsDictionaryMatcher(characters, file);
}
if (m == nullptr) {
// no matcher exists to take ownership - either we are an invalid
// type or memory allocation failed
udata_close(file);
}
return m;
} else if (dictfname != nullptr) {
// we don't have a dictionary matcher.
// returning nullptr here will cause us to fail to find a dictionary break engine, as expected
status = U_ZERO_ERROR;
return nullptr;
}
return nullptr;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
| 412 | 0.91178 | 1 | 0.91178 | game-dev | MEDIA | 0.435243 | game-dev | 0.89287 | 1 | 0.89287 |
glKarin/com.n0n3m4.diii4a | 14,179 | Q3E/src/main/jni/gzdoom/src/doomdef.h | //-----------------------------------------------------------------------------
//
// Copyright 1993-1996 id Software
// Copyright 1999-2016 Randy Heit
// Copyright 2002-2016 Christoph Oelckers
//
// 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/
//
//-----------------------------------------------------------------------------
//
// DESCRIPTION:
// Internally used data structures for virtually everything,
// key definitions, lots of other stuff.
//
//-----------------------------------------------------------------------------
#ifndef __DOOMDEF_H__
#define __DOOMDEF_H__
#include <stdio.h>
#include <string.h>
//
// Global parameters/defines.
//
// Game mode handling - identify IWAD version
// to handle IWAD dependend animations etc.
typedef enum
{
shareware, // DOOM 1 shareware, E1, M9
registered, // DOOM 1 registered, E3, M27
commercial, // DOOM 2 retail, E1 M34
// DOOM 2 german edition not handled
retail, // DOOM 1 retail, E4, M36
undetermined // Well, no IWAD found.
} GameMode_t;
// If rangecheck is undefined, most parameter validation debugging code
// will not be compiled
#ifndef NORANGECHECKING
#ifndef RANGECHECK
#define RANGECHECK
#endif
#endif
// State updates, number of tics / second.
constexpr int TICRATE = 35;
// Global constants that were defines.
enum
{
// The maximum number of players, multiplayer/networking.
MAXPLAYERS = 8,
// Amount of damage done by a telefrag.
TELEFRAG_DAMAGE = 1000000
};
inline int Tics2Seconds(int tics)
{
return tics / TICRATE;
}
typedef float skill_t;
/*
enum ESkillLevels
{
sk_baby,
sk_easy,
sk_medium,
sk_hard,
sk_nightmare
};
*/
#define TELEFOGHEIGHT (gameinfo.telefogheight)
//
// DOOM keyboard definition. Everything below 0x100 matches
// a mode 1 keyboard scan code.
//
#include "keydef.h"
// [RH] dmflags bits (based on Q2's)
enum : unsigned
{
DF_NO_HEALTH = 1 << 0, // Do not spawn health items (DM)
DF_NO_ITEMS = 1 << 1, // Do not spawn powerups (DM)
DF_WEAPONS_STAY = 1 << 2, // Leave weapons around after pickup (DM)
DF_FORCE_FALLINGZD = 1 << 3, // Falling too far hurts (old ZDoom style)
DF_FORCE_FALLINGHX = 2 << 3, // Falling too far hurts (Hexen style)
DF_FORCE_FALLINGST = 3 << 3, // Falling too far hurts (Strife style)
// 1 << 5 -- this space left blank --
DF_SAME_LEVEL = 1 << 6, // Stay on the same map when someone exits (DM)
DF_SPAWN_FARTHEST = 1 << 7, // Spawn players as far as possible from other players (DM)
DF_FORCE_RESPAWN = 1 << 8, // Automatically respawn dead players after respawn_time is up (DM)
DF_NO_ARMOR = 1 << 9, // Do not spawn armor (DM)
DF_NO_EXIT = 1 << 10, // Kill anyone who tries to exit the level (DM)
DF_INFINITE_AMMO = 1 << 11, // Don't use up ammo when firing
DF_NO_MONSTERS = 1 << 12, // Don't spawn monsters (replaces -nomonsters parm)
DF_MONSTERS_RESPAWN = 1 << 13, // Monsters respawn sometime after their death (replaces -respawn parm)
DF_ITEMS_RESPAWN = 1 << 14, // Items other than invuln. and invis. respawn
DF_FAST_MONSTERS = 1 << 15, // Monsters are fast (replaces -fast parm)
DF_NO_JUMP = 1 << 16, // Don't allow jumping
DF_YES_JUMP = 2 << 16,
DF_NO_FREELOOK = 1 << 18, // Don't allow freelook
DF_YES_FREELOOK = 2 << 18,
DF_NO_FOV = 1 << 20, // Only let the arbitrator set FOV (for all players)
DF_NO_COOP_WEAPON_SPAWN = 1 << 21, // Don't spawn multiplayer weapons in coop games
DF_NO_CROUCH = 1 << 22, // Don't allow crouching
DF_YES_CROUCH = 2 << 22, //
DF_COOP_LOSE_INVENTORY = 1 << 24, // Lose all your old inventory when respawning in coop
DF_COOP_LOSE_KEYS = 1 << 25, // Lose keys when respawning in coop
DF_COOP_LOSE_WEAPONS = 1 << 26, // Lose weapons when respawning in coop
DF_COOP_LOSE_ARMOR = 1 << 27, // Lose armor when respawning in coop
DF_COOP_LOSE_POWERUPS = 1 << 28, // Lose powerups when respawning in coop
DF_COOP_LOSE_AMMO = 1 << 29, // Lose ammo when respawning in coop
DF_COOP_HALVE_AMMO = 1 << 30, // Lose half your ammo when respawning in coop (but not less than the normal starting amount)
DF_INSTANT_REACTION = 1u << 31, // Monsters react instantly
};
// [BC] More dmflags. w00p!
enum : unsigned
{
// DF2_YES_IMPALING = 1 << 0, // Player gets impaled on MF2_IMPALE items
DF2_YES_WEAPONDROP = 1 << 1, // Drop current weapon upon death
// DF2_NO_RUNES = 1 << 2, // Don't spawn runes
// DF2_INSTANT_RETURN = 1 << 3, // Instantly return flags and skulls when player carrying it dies (ST/CTF)
DF2_NO_TEAM_SWITCH = 1 << 4, // Do not allow players to switch teams in teamgames
// DF2_NO_TEAM_SELECT = 1 << 5, // Player is automatically placed on a team.
DF2_YES_DOUBLEAMMO = 1 << 6, // Double amount of ammo that items give you like skill 1 and 5 do
DF2_YES_DEGENERATION = 1 << 7, // Player slowly loses health when over 100% (Quake-style)
DF2_NO_FREEAIMBFG = 1 << 8, // Disallow BFG freeaiming. Prevents cheap BFG frags by aiming at floor or ceiling
DF2_BARRELS_RESPAWN = 1 << 9, // Barrels respawn (duh)
DF2_YES_RESPAWN_INVUL = 1 << 10, // Player is temporarily invulnerable when respawned
// DF2_COOP_SHOTGUNSTART = 1 << 11, // All playres start with a shotgun when they respawn
DF2_SAME_SPAWN_SPOT = 1 << 12, // Players respawn in the same place they died (co-op)
DF2_YES_KEEPFRAGS = 1 << 13, // Don't clear frags after each level
DF2_NO_RESPAWN = 1 << 14, // Player cannot respawn
DF2_YES_LOSEFRAG = 1 << 15, // Lose a frag when killed. More incentive to try to not get yerself killed
DF2_INFINITE_INVENTORY = 1 << 16, // Infinite inventory.
DF2_KILL_MONSTERS = 1 << 17, // All monsters must be killed before the level exits.
DF2_NO_AUTOMAP = 1 << 18, // Players are allowed to see the automap.
DF2_NO_AUTOMAP_ALLIES = 1 << 19, // Allies can been seen on the automap.
DF2_DISALLOW_SPYING = 1 << 20, // You can spy on your allies.
DF2_CHASECAM = 1 << 21, // Players can use the chasecam cheat.
DF2_NOSUICIDE = 1 << 22, // Players are not allowed to suicide.
DF2_NOAUTOAIM = 1 << 23, // Players cannot use autoaim.
DF2_DONTCHECKAMMO = 1 << 24, // Don't Check ammo when switching weapons.
DF2_KILLBOSSMONST = 1 << 25, // Kills all monsters spawned by a boss cube when the boss dies
DF2_NOCOUNTENDMONST = 1 << 26, // Do not count monsters in 'end level when dying' sectors towards kill count
DF2_RESPAWN_SUPER = 1 << 27, // Respawn invulnerability and invisibility
DF2_NO_COOP_THING_SPAWN = 1 << 28, // Don't spawn multiplayer things in coop games
DF2_ALWAYS_SPAWN_MULTI = 1 << 29, // Always spawn multiplayer items
DF2_NOVERTSPREAD = 1 << 30, // Don't allow vertical spread for hitscan weapons (excluding ssg)
DF2_NO_EXTRA_AMMO = 1u << 31, // Don't add extra ammo when picking up weapons (like in original Doom)
};
// [Nash] dmflags3 in 2023 let's gooooo
enum : unsigned
{
DF3_NO_PLAYER_CLIP = 1 << 0, // Players can walk through and shoot through each other
DF3_COOP_SHARE_KEYS = 1 << 1, // Keys and other core items will be given to all players in coop
DF3_LOCAL_ITEMS = 1 << 2, // Items are picked up client-side rather than fully taken by the client who picked it up
DF3_NO_LOCAL_DROPS = 1 << 3, // Drops from Actors aren't picked up locally
DF3_NO_COOP_ONLY_ITEMS = 1 << 4, // Items that only appear in co-op are disabled
DF3_NO_COOP_ONLY_THINGS = 1 << 5, // Any Actor that only appears in co-op is disabled
DF3_REMEMBER_LAST_WEAP = 1 << 6, // When respawning in co-op, keep the last used weapon out instead of switching to the best new one.
DF3_PISTOL_START = 1 << 7, // Take player inventory when exiting to the next level.
};
// [RH] Compatibility flags.
enum : unsigned int
{
COMPATF_SHORTTEX = 1 << 0, // Use Doom's shortest texture around behavior?
COMPATF_STAIRINDEX = 1 << 1, // Don't fix loop index for stair building?
COMPATF_LIMITPAIN = 1 << 2, // Pain elemental is limited to 20 lost souls?
COMPATF_SILENTPICKUP = 1 << 3, // Pickups are only heard locally?
COMPATF_NO_PASSMOBJ = 1 << 4, // Pretend every actor is infinitely tall?
COMPATF_MAGICSILENCE = 1 << 5, // Limit actors to one sound at a time?
COMPATF_WALLRUN = 1 << 6, // Enable buggier wall clipping so players can wallrun?
COMPATF_NOTOSSDROPS = 1 << 7, // Spawn dropped items directly on the floor?
COMPATF_USEBLOCKING = 1 << 8, // Any special line can block a use line
COMPATF_NODOORLIGHT = 1 << 9, // Don't do the BOOM local door light effect
COMPATF_RAVENSCROLL = 1 << 10, // Raven's scrollers use their original carrying speed
COMPATF_SOUNDTARGET = 1 << 11, // Use sector based sound target code.
COMPATF_DEHHEALTH = 1 << 12, // Limit deh.MaxHealth to the health bonus (as in Doom2.exe)
COMPATF_TRACE = 1 << 13, // Trace ignores lines with the same sector on both sides
COMPATF_DROPOFF = 1 << 14, // Monsters cannot move when hanging over a dropoff
COMPATF_BOOMSCROLL = 1 << 15, // Scrolling sectors are additive like in Boom
COMPATF_INVISIBILITY = 1 << 16, // Monsters can see semi-invisible players
COMPATF_SILENT_INSTANT_FLOORS = 1<<17, // Instantly moving floors are not silent
COMPATF_SECTORSOUNDS = 1 << 18, // Sector sounds use original method for sound origin.
COMPATF_MISSILECLIP = 1 << 19, // Use original Doom heights for clipping against projectiles
COMPATF_CROSSDROPOFF = 1 << 20, // monsters can't be pushed over dropoffs
COMPATF_ANYBOSSDEATH = 1 << 21, // [GZ] Any monster which calls BOSSDEATH counts for level specials
COMPATF_MINOTAUR = 1 << 22, // Minotaur's floor flame is exploded immediately when feet are clipped
COMPATF_MUSHROOM = 1 << 23, // Force original velocity calculations for A_Mushroom in Dehacked mods.
COMPATF_MBFMONSTERMOVE = 1 << 24, // Monsters are affected by friction and pushers/pullers.
COMPATF_VILEGHOSTS = 1 << 25, // Crushed monsters are resurrected as ghosts.
COMPATF_NOBLOCKFRIENDS = 1 << 26, // Friendly monsters aren't blocked by monster-blocking lines.
COMPATF_SPRITESORT = 1 << 27, // Invert sprite sorting order for sprites of equal distance
COMPATF_HITSCAN = 1 << 28, // Hitscans use original blockmap and hit check code.
COMPATF_LIGHT = 1 << 29, // Find neighboring light level like Doom
COMPATF_POLYOBJ = 1 << 30, // Draw polyobjects the old fashioned way
COMPATF_MASKEDMIDTEX = 1u << 31, // Ignore compositing when drawing masked midtextures
COMPATF2_BADANGLES = 1 << 0, // It is impossible to face directly NSEW.
COMPATF2_FLOORMOVE = 1 << 1, // Use the same floor motion behavior as Doom.
COMPATF2_SOUNDCUTOFF = 1 << 2, // Cut off sounds when an actor vanishes instead of making it owner-less
COMPATF2_POINTONLINE = 1 << 3, // Use original but buggy P_PointOnLineSide() and P_PointOnDivlineSideCompat()
COMPATF2_MULTIEXIT = 1 << 4, // Level exit can be triggered multiple times (required by Daedalus's travel tubes, thanks to a faulty script)
COMPATF2_TELEPORT = 1 << 5, // Don't let indirect teleports trigger sector actions
COMPATF2_PUSHWINDOW = 1 << 6, // Disable the window check in CheckForPushSpecial()
COMPATF2_CHECKSWITCHRANGE = 1 << 7, // Enable buggy CheckSwitchRange behavior
COMPATF2_EXPLODE1 = 1 << 8, // No vertical explosion thrust
COMPATF2_EXPLODE2 = 1 << 9, // Use original explosion code throughout.
COMPATF2_RAILING = 1 << 10, // Bugged Strife railings.
COMPATF2_SCRIPTWAIT = 1 << 11, // Use old scriptwait implementation where it doesn't wait on a non-running script.
COMPATF2_AVOID_HAZARDS = 1 << 12, // another MBF thing.
COMPATF2_STAYONLIFT = 1 << 13, // yet another MBF thing.
COMPATF2_NOMBF21 = 1 << 14, // disable MBF21 features that may clash with certain maps
COMPATF2_VOODOO_ZOMBIES = 1 << 15, // [RL0] allow playerinfo, playerpawn, and voodoo health to all be different, and skip killing the player's mobj if a voodoo doll dies to allow voodoo zombies
COMPATF2_FDTELEPORT = 1 << 16, // Emulate Final Doom's teleporter z glitch.
COMPATF2_NOACSARGCHECK = 1 << 17, // Disable arg count checking for ACS
};
// Emulate old bugs for select maps. These are not exposed by a cvar
// or mapinfo because we do not want new maps to use these bugs.
enum
{
BCOMPATF_SETSLOPEOVERFLOW = 1 << 0, // SetSlope things can overflow
BCOMPATF_RESETPLAYERSPEED = 1 << 1, // Set player speed to 1.0 when changing maps
BCOMPATF_BADTELEPORTERS = 1 << 3, // Ignore tags on Teleport specials
BCOMPATF_BADPORTALS = 1 << 4, // Restores the old unstable portal behavior
BCOMPATF_REBUILDNODES = 1 << 5, // Force node rebuild
BCOMPATF_LINKFROZENPROPS = 1 << 6, // Clearing PROP_TOTALLYFROZEN or PROP_FROZEN also clears the other
BCOMPATF_FLOATBOB = 1 << 8, // Use Hexen's original method of preventing floatbobbing items from falling down
BCOMPATF_NOSLOPEID = 1 << 9, // disable line IDs on slopes.
BCOMPATF_CLIPMIDTEX = 1 << 10, // Always Clip midtex's in the software renderer (required to run certain GZDoom maps, has no effect in the hardware renderer)
BCOMPATF_NOSECTIONMERGE = 1 << 11, // (for IWAD maps) keep separate sections for sectors with intra-sector linedefs.
BCOMPATF_NOMIRRORS = 1 << 12, // disable mirrors, for maps that have broken setups.
};
// phares 3/20/98:
//
// Player friction is variable, based on controlling
// linedefs. More friction can create mud, sludge,
// magnetized floors, etc. Less friction can create ice.
#define MORE_FRICTION_VELOCITY (15000/65536.) // mud factor based on velocity
#define ORIG_FRICTION (0xE800/65536.) // original value
#define ORIG_FRICTION_FACTOR (2048/65536.) // original value
#define FRICTION_LOW (0xf900/65536.)
#define FRICTION_FLY (0xeb00/65536.)
#define BLINKTHRESHOLD (4*32)
#endif // __DOOMDEF_H__
| 412 | 0.896016 | 1 | 0.896016 | game-dev | MEDIA | 0.99902 | game-dev | 0.678038 | 1 | 0.678038 |
etternagame/etterna | 18,139 | src/Etterna/Models/Lua/LuaBinding.h | /* LuaBinding - helpers to expose Lua bindings for C++ classes. */
#ifndef LuaBinding_H
#define LuaBinding_H
#include "Etterna/Singletons/LuaManager.h"
class LuaReference;
class LuaBinding
{
public:
LuaBinding();
virtual ~LuaBinding();
void Register(lua_State* L);
static void RegisterTypes(lua_State* L);
[[nodiscard]] auto IsDerivedClass() const -> bool
{
return GetClassName() != GetBaseClassName();
}
[[nodiscard]] virtual auto GetClassName() const -> const std::string& = 0;
[[nodiscard]] virtual auto GetBaseClassName() const
-> const std::string& = 0;
static void ApplyDerivedType(Lua* L,
const std::string& sClassname,
void* pSelf);
static auto CheckLuaObjectType(lua_State* L,
int narg,
std::string const& szType) -> bool;
protected:
virtual void Register(Lua* L, int iMethods, int iMetatable) = 0;
static void CreateMethodsTable(lua_State* L, const std::string& szName);
static auto GetPointerFromStack(Lua* L, const std::string& sType, int iArg)
-> void*;
static auto Equal(lua_State* L) -> bool;
static auto PushEqual(lua_State* L) -> int;
};
/** @brief Allow the binding of Lua to various classes. */
template<typename Type>
class Luna : public LuaBinding
{
protected:
using T = Type;
using binding_t = int(T*, lua_State*);
struct RegType
{
std::string regName;
binding_t* mfunc;
};
void Register(Lua* L, int iMethods, int iMetatable) override
{
lua_pushcfunction(L, tostring_T);
lua_setfield(L, iMetatable, "__tostring");
// fill method table with methods from class T
for (auto const& m : m_aMethods) {
lua_pushlightuserdata(L, reinterpret_cast<void*>(m.mfunc));
lua_pushcclosure(L, thunk, 1);
lua_setfield(L, iMethods, m.regName.c_str());
}
}
public:
[[nodiscard]] auto GetClassName() const -> const std::string& override
{
return m_sClassName;
}
[[nodiscard]] auto GetBaseClassName() const -> const std::string& override
{
return m_sBaseClassName;
}
static std::string m_sClassName;
static std::string m_sBaseClassName;
// Get userdata from the Lua stack and return a pointer to T object.
static auto check(lua_State* L, int narg, bool bIsSelf = false) -> T*
{
if (!LuaBinding::CheckLuaObjectType(L, narg, m_sClassName)) {
if (bIsSelf) {
luaL_typerror(L, narg, m_sClassName.c_str());
} else {
LuaHelpers::TypeError(L, narg, m_sClassName);
}
}
return get(L, narg);
}
static auto get(lua_State* L, int narg) -> T*
{
return reinterpret_cast<T*>(GetPointerFromStack(L, m_sClassName, narg));
}
/* Push a table or userdata for the given object. This is called on the
* base class, so we pick up the instance of the base class, if any. */
static void PushObject(Lua* L, const std::string& sDerivedClassName, T* p);
protected:
void AddMethod(std::string const& regName, int (*pFunc)(T* p, lua_State* L))
{
RegType r = { regName, pFunc };
m_aMethods.push_back(r);
}
private:
// member function dispatcher
static auto thunk(Lua* L) -> int
{
// stack has userdata, followed by method args
T* obj = check(L, 1, true); // get self
lua_remove(L,
1); // remove self so member function args start at index 1
// get member function from upvalue
auto* pFunc = reinterpret_cast<binding_t*>(lua_touserdata(L, lua_upvalueindex(1)));
return pFunc(obj, L); // call member function
}
std::vector<RegType> m_aMethods;
static auto tostring_T(lua_State* L) -> int
{
char buff[32];
const void* pData = check(L, 1);
snprintf(buff, sizeof(buff), "%p", pData);
lua_pushfstring(L, "%s (%s)", m_sClassName.c_str(), buff);
return 1;
}
};
/*
* Instanced classes have an associated table, which is used as "self"
* instead of a raw userdata. This should be as lightweight as possible.
*/
#include "LuaReference.h"
class LuaClass : public LuaTable
{
public:
LuaClass() = default;
LuaClass(const LuaClass& cpy);
~LuaClass() override;
auto operator=(const LuaClass& cpy) -> LuaClass&;
};
/* Only a base class has to indicate that it's instanced (has a per-object
* Lua table). Derived classes simply call the base class's Push function,
* specifying a different class name, so they don't need to know about it. */
#define LUA_REGISTER_INSTANCED_BASE_CLASS(T) \
template<> \
void Luna<T>::PushObject( \
Lua* L, const std::string& sDerivedClassName, T* p) \
{ \
p->m_pLuaInstance->PushSelf(L); \
LuaBinding::ApplyDerivedType(L, sDerivedClassName, p); \
} \
LUA_REGISTER_CLASS_BASIC(T, T)
#define LUA_REGISTER_CLASS(T) \
template<> \
void Luna<T>::PushObject( \
Lua* L, const std::string& sDerivedClassName, T* p) \
{ \
void** pData = (void**)lua_newuserdata(L, sizeof(void*)); \
*pData = p; \
LuaBinding::ApplyDerivedType(L, sDerivedClassName, p); \
} \
LUA_REGISTER_CLASS_BASIC(T, T)
#define LUA_REGISTER_DERIVED_CLASS(T, B) \
template<> \
void Luna<T>::PushObject( \
Lua* L, const std::string& sDerivedClassName, T* p) \
{ \
Luna<B>::PushObject(L, sDerivedClassName, p); \
} \
LUA_REGISTER_CLASS_BASIC(T, B)
#define LUA_REGISTER_CLASS_BASIC(T, B) \
template<> \
std::string Luna<T>::m_sClassName = #T; \
template<> \
std::string Luna<T>::m_sBaseClassName = #B; \
void T::PushSelf(lua_State* L) \
{ \
Luna<B>::PushObject(L, Luna<T>::m_sClassName, this); \
} \
static Luna##T registera##T; \
/* Call PushSelf, so we always call the derived Luna<T>::Push. */ \
namespace LuaHelpers { \
template<> \
void Push<T*>(lua_State * L, T* const& pObject) \
{ \
if (pObject == nullptr) \
lua_pushnil(L); \
else \
pObject->PushSelf(L); \
} \
}
#define DEFINE_METHOD(method_name, expr) \
static int method_name(T* p, lua_State* L) \
{ \
LuaHelpers::Push(L, p->expr); \
return 1; \
}
#define COMMON_RETURN_SELF \
p->PushSelf(L); \
return 1;
#define GET_SET_BOOL_METHOD(method_name, bool_name) \
\
static int get_##method_name(T* p, lua_State* L) \
\
{ \
lua_pushboolean(L, p->bool_name); \
return 1; \
} \
\
static int set_##method_name(T* p, lua_State* L) \
\
{ \
p->bool_name = lua_toboolean(L, 1) != 0; \
COMMON_RETURN_SELF; \
}
#define GETTER_SETTER_BOOL_METHOD(bool_name) \
\
static int get_##bool_name(T* p, lua_State* L) \
\
{ \
lua_pushboolean(L, p->get_##bool_name()); \
return 1; \
} \
\
static int set_##bool_name(T* p, lua_State* L) \
\
{ \
p->set_##bool_name(lua_toboolean(L, 1) != 0); \
COMMON_RETURN_SELF; \
}
#define GET_SET_FLOAT_METHOD(method_name, float_name) \
\
static int get_##method_name(T* p, lua_State* L) \
\
{ \
lua_pushnumber(L, p->float_name); \
return 1; \
} \
\
static int set_##method_name(T* p, lua_State* L) \
\
{ \
p->float_name = FArg(1); \
COMMON_RETURN_SELF; \
}
#define GET_SET_INT_METHOD(method_name, int_name) \
\
static int get_##method_name(T* p, lua_State* L) \
\
{ \
lua_pushinteger(L, p->int_name); \
return 1; \
} \
\
static int set_##method_name(T* p, lua_State* L) \
\
{ \
p->int_name = IArg(1); \
COMMON_RETURN_SELF; \
}
#define GETTER_SETTER_FLOAT_METHOD(float_name) \
\
static int get_##float_name(T* p, lua_State* L) \
\
{ \
lua_pushnumber(L, p->get_##float_name()); \
return 1; \
} \
\
static int set_##float_name(T* p, lua_State* L) \
\
{ \
p->set_##float_name(FArg(1)); \
COMMON_RETURN_SELF; \
}
#define GET_SET_ENUM_METHOD(method_name, enum_name, val_name) \
\
static int get_##method_name(T* p, lua_State* L) \
\
{ \
Enum::Push(L, p->val_name); \
return 1; \
} \
\
static int set_##method_name(T* p, lua_State* L) \
\
{ \
p->val_name = Enum::Check<enum_name>(L, 1); \
COMMON_RETURN_SELF; \
}
#define GETTER_SETTER_ENUM_METHOD(enum_name, val_name) \
\
static int get_##val_name(T* p, lua_State* L) \
\
{ \
Enum::Push(L, p->get_##val_name()); \
return 1; \
} \
\
static int set_##val_name(T* p, lua_State* L) \
\
{ \
p->set_##val_name(Enum::Check<enum_name>(L, 1)); \
COMMON_RETURN_SELF; \
}
#define ADD_METHOD(method_name) AddMethod(#method_name, method_name)
#define ADD_GET_SET_METHODS(method_name) \
ADD_METHOD(get_##method_name); \
ADD_METHOD(set_##method_name);
#define LUA_SET_MEMBER(member, arg_conv) \
\
static int set_##member(T* p, lua_State* L) \
\
{ \
p->m_##member = arg_conv(1); \
COMMON_RETURN_SELF; \
}
#define GET_SET_MEMBER(member, arg_conv) \
\
DEFINE_METHOD(get_##member, m_##member); \
\
LUA_SET_MEMBER(member, arg_conv);
#define LUA_REGISTER_NAMESPACE(T) \
static void Register##T(lua_State* L) \
{ \
luaL_register(L, #T, T##Table); \
lua_pop(L, 1); \
} \
REGISTER_WITH_LUA_FUNCTION(Register##T)
#define LIST_METHOD(method_name) \
{ \
#method_name, method_name \
}
// Explicitly separates the stack into args and return values.
// This way, the stack can safely be used to store the previous values.
void
DefaultNilArgs(lua_State* L, int n);
auto
FArgGTEZero(lua_State* L, int index) -> float;
#endif
| 412 | 0.933914 | 1 | 0.933914 | game-dev | MEDIA | 0.530344 | game-dev | 0.769975 | 1 | 0.769975 |
oraxen/oraxen | 4,713 | core/src/main/java/io/th0rgal/oraxen/utils/EntityUtils.java | package io.th0rgal.oraxen.utils;
import io.th0rgal.oraxen.utils.logs.Logs;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Method;
@SuppressWarnings({"unchecked", "unused", "deprecation"})
public class EntityUtils {
private static Method spawnMethod;
public static boolean isUnderWater(Entity entity) {
if (VersionUtil.isPaperServer() && VersionUtil.atOrAbove("1.19")) {
return entity.isUnderWater();
} else return entity.isInWater();
}
public static boolean isFixed(ItemDisplay itemDisplay) {
return itemDisplay.getItemDisplayTransform() == ItemDisplay.ItemDisplayTransform.FIXED;
}
public static boolean isNone(ItemDisplay itemDisplay) {
return itemDisplay.getItemDisplayTransform() == ItemDisplay.ItemDisplayTransform.NONE;
}
public void teleport(@NotNull Location location, @NotNull Entity entity, PlayerTeleportEvent.TeleportCause cause) {
if (VersionUtil.isPaperServer() || VersionUtil.isFoliaServer() && VersionUtil.atOrAbove("1.19.4")) {
entity.teleportAsync(location, cause);
} else entity.teleport(location);
}
/**
* Teleports an entity to the given location
* Uses teleportAsync on 1.19.4+ Paper/Folia servers and teleport on all other servers
* @param location The location to teleport the entity to
* @param entity The entity to teleport
*/
public static void teleport(@NotNull Location location, @NotNull Entity entity) {
if (VersionUtil.atOrAbove("1.19.4") && (VersionUtil.isPaperServer() || VersionUtil.isFoliaServer())) {
entity.teleportAsync(location);
} else entity.teleport(location);
}
static {
try {
// Get the method based on the server version
Class<?> entitySpawnerClass = Class.forName("org.bukkit.RegionAccessor"); // Replace with actual path
if (VersionUtil.atOrAbove("1.20.2")) {
spawnMethod = entitySpawnerClass.getDeclaredMethod("spawn", Location.class, Class.class, java.util.function.Consumer.class);
} else {
spawnMethod = entitySpawnerClass.getDeclaredMethod("spawn", Location.class, Class.class, org.bukkit.util.Consumer.class);
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
Logs.logWarning(e.getMessage()); // Handle the exception according to your needs
}
}
/**
* Spawns an entity at the given location and applies the consumer to it based on server version
* @param location The location to spawn the entity at
* @param clazz The class of the entity to spawn
* @param consumer The consumer to apply to the entity
* @return The entity that was spawned
*/
public static <T> T spawnEntity(@NotNull Location location, @NotNull Class<T> clazz, EntityConsumer<T> consumer) {
try {
T entity;
World world = location.getWorld();
Object wrappedConsumer;
// Determine the consumer type and choose the appropriate spawn method
// 1.20.2> uses java.util.function.Consumer while 1.20.2< uses org.bukkit.util.Consumer
if (VersionUtil.atOrAbove("1.20.2")) wrappedConsumer = new JavaConsumerWrapper<>(consumer);
else wrappedConsumer = new BukkitConsumerWrapper<>(consumer);
entity = (T) spawnMethod.invoke(world, location, clazz, wrappedConsumer);
return entity;
} catch (Exception e) {
Logs.logWarning(e.getMessage()); // Handle the exception according to your needs
}
return null;
}
public interface EntityConsumer<T> {
void accept(T entity);
}
public static class JavaConsumerWrapper<T> implements java.util.function.Consumer<T> {
private final EntityConsumer<T> entityConsumer;
public JavaConsumerWrapper(EntityConsumer<T> entityConsumer) {
this.entityConsumer = entityConsumer;
}
@Override
public void accept(T entity) {
entityConsumer.accept(entity);
}
}
public static class BukkitConsumerWrapper<T> implements org.bukkit.util.Consumer<T> {
private final EntityConsumer<T> entityConsumer;
public BukkitConsumerWrapper(EntityConsumer<T> entityConsumer) {
this.entityConsumer = entityConsumer;
}
@Override
public void accept(T entity) {
entityConsumer.accept(entity);
}
}
}
| 412 | 0.715904 | 1 | 0.715904 | game-dev | MEDIA | 0.938491 | game-dev | 0.613468 | 1 | 0.613468 |
MikeyTheA/PokeRogueModLoader | 48,192 | src/data/arena-tag.ts | import { Arena } from "#app/field/arena";
import BattleScene from "#app/battle-scene";
import { Type } from "#app/data/type";
import { BooleanHolder, NumberHolder, toDmgValue } from "#app/utils";
import { MoveCategory, allMoves, MoveTarget, IncrementMovePriorityAttr, applyMoveAttrs } from "#app/data/move";
import { getPokemonNameWithAffix } from "#app/messages";
import Pokemon, { HitResult, PokemonMove } from "#app/field/pokemon";
import { StatusEffect } from "#app/data/status-effect";
import { BattlerIndex } from "#app/battle";
import { BlockNonDirectDamageAbAttr, ChangeMovePriorityAbAttr, InfiltratorAbAttr, ProtectStatAbAttr, applyAbAttrs } from "#app/data/ability";
import { Stat } from "#enums/stat";
import { CommonAnim, CommonBattleAnim } from "#app/data/battle-anims";
import i18next from "i18next";
import { Abilities } from "#enums/abilities";
import { ArenaTagType } from "#enums/arena-tag-type";
import { BattlerTagType } from "#enums/battler-tag-type";
import { Moves } from "#enums/moves";
import { MoveEffectPhase } from "#app/phases/move-effect-phase";
import { PokemonHealPhase } from "#app/phases/pokemon-heal-phase";
import { ShowAbilityPhase } from "#app/phases/show-ability-phase";
import { StatStageChangePhase } from "#app/phases/stat-stage-change-phase";
import { CommonAnimPhase } from "#app/phases/common-anim-phase";
export enum ArenaTagSide {
BOTH,
PLAYER,
ENEMY
}
export abstract class ArenaTag {
constructor(
public tagType: ArenaTagType,
public turnCount: number,
public sourceMove?: Moves,
public sourceId?: number,
public side: ArenaTagSide = ArenaTagSide.BOTH
) {}
apply(arena: Arena, simulated: boolean, ...args: unknown[]): boolean {
return true;
}
onAdd(arena: Arena, quiet: boolean = false): void { }
onRemove(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:arenaOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: this.getMoveName() }));
}
}
onOverlap(arena: Arena): void { }
lapse(arena: Arena): boolean {
return this.turnCount < 1 || !!(--this.turnCount);
}
getMoveName(): string | null {
return this.sourceMove
? allMoves[this.sourceMove].name
: null;
}
/**
* When given a arena tag or json representing one, load the data for it.
* This is meant to be inherited from by any arena tag with custom attributes
* @param {ArenaTag | any} source An arena tag
*/
loadTag(source : ArenaTag | any) : void {
this.turnCount = source.turnCount;
this.sourceMove = source.sourceMove;
this.sourceId = source.sourceId;
this.side = source.side;
}
/**
* Helper function that retrieves the source Pokemon
* @param scene medium to retrieve the source Pokemon
* @returns The source {@linkcode Pokemon} or `null` if none is found
*/
public getSourcePokemon(scene: BattleScene): Pokemon | null {
return this.sourceId ? scene.getPokemonById(this.sourceId) : null;
}
/**
* Helper function that retrieves the Pokemon affected
* @param scene - medium to retrieve the involved Pokemon
* @returns list of PlayerPokemon or EnemyPokemon on the field
*/
public getAffectedPokemon(scene: BattleScene): Pokemon[] {
switch (this.side) {
case ArenaTagSide.PLAYER:
return scene.getPlayerField() ?? [];
case ArenaTagSide.ENEMY:
return scene.getEnemyField() ?? [];
case ArenaTagSide.BOTH:
default:
return scene.getField(true) ?? [];
}
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Mist_(move) Mist}.
* Prevents Pokémon on the opposing side from lowering the stats of the Pokémon in the Mist.
*/
export class MistTag extends ArenaTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.MIST, turnCount, Moves.MIST, sourceId, side);
}
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
if (this.sourceId) {
const source = arena.scene.getPokemonById(this.sourceId);
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:mistOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
} else if (!quiet) {
console.warn("Failed to get source for MistTag onAdd");
}
}
}
/**
* Cancels the lowering of stats
* @param arena the {@linkcode Arena} containing this effect
* @param simulated `true` if the effect should be applied quietly
* @param attacker the {@linkcode Pokemon} using a move into this effect.
* @param cancelled a {@linkcode BooleanHolder} whose value is set to `true`
* to flag the stat reduction as cancelled
* @returns `true` if a stat reduction was cancelled; `false` otherwise
*/
override apply(arena: Arena, simulated: boolean, attacker: Pokemon, cancelled: BooleanHolder): boolean {
// `StatStageChangePhase` currently doesn't have a reference to the source of stat drops,
// so this code currently has no effect on gameplay.
if (attacker) {
const bypassed = new BooleanHolder(false);
// TODO: Allow this to be simulated
applyAbAttrs(InfiltratorAbAttr, attacker, null, false, bypassed);
if (bypassed.value) {
return false;
}
}
cancelled.value = true;
if (!simulated) {
arena.scene.queueMessage(i18next.t("arenaTag:mistApply"));
}
return true;
}
}
/**
* Reduces the damage of specific move categories in the arena.
* @extends ArenaTag
*/
export class WeakenMoveScreenTag extends ArenaTag {
protected weakenedCategories: MoveCategory[];
/**
* Creates a new instance of the WeakenMoveScreenTag class.
*
* @param tagType - The type of the arena tag.
* @param turnCount - The number of turns the tag is active.
* @param sourceMove - The move that created the tag.
* @param sourceId - The ID of the source of the tag.
* @param side - The side (player or enemy) the tag affects.
* @param weakenedCategories - The categories of moves that are weakened by this tag.
*/
constructor(tagType: ArenaTagType, turnCount: number, sourceMove: Moves, sourceId: number, side: ArenaTagSide, weakenedCategories: MoveCategory[]) {
super(tagType, turnCount, sourceMove, sourceId, side);
this.weakenedCategories = weakenedCategories;
}
/**
* Applies the weakening effect to the move.
*
* @param arena the {@linkcode Arena} where the move is applied.
* @param simulated n/a
* @param attacker the attacking {@linkcode Pokemon}
* @param moveCategory the attacking move's {@linkcode MoveCategory}.
* @param damageMultiplier A {@linkcode NumberHolder} containing the damage multiplier
* @returns `true` if the attacking move was weakened; `false` otherwise.
*/
override apply(arena: Arena, simulated: boolean, attacker: Pokemon, moveCategory: MoveCategory, damageMultiplier: NumberHolder): boolean {
if (this.weakenedCategories.includes(moveCategory)) {
const bypassed = new BooleanHolder(false);
applyAbAttrs(InfiltratorAbAttr, attacker, null, false, bypassed);
if (bypassed.value) {
return false;
}
damageMultiplier.value = arena.scene.currentBattle.double ? 2732 / 4096 : 0.5;
return true;
}
return false;
}
}
/**
* Reduces the damage of physical moves.
* Used by {@linkcode Moves.REFLECT}
*/
class ReflectTag extends WeakenMoveScreenTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.REFLECT, turnCount, Moves.REFLECT, sourceId, side, [ MoveCategory.PHYSICAL ]);
}
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:reflectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
/**
* Reduces the damage of special moves.
* Used by {@linkcode Moves.LIGHT_SCREEN}
*/
class LightScreenTag extends WeakenMoveScreenTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.LIGHT_SCREEN, turnCount, Moves.LIGHT_SCREEN, sourceId, side, [ MoveCategory.SPECIAL ]);
}
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:lightScreenOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
/**
* Reduces the damage of physical and special moves.
* Used by {@linkcode Moves.AURORA_VEIL}
*/
class AuroraVeilTag extends WeakenMoveScreenTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.AURORA_VEIL, turnCount, Moves.AURORA_VEIL, sourceId, side, [ MoveCategory.SPECIAL, MoveCategory.PHYSICAL ]);
}
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:auroraVeilOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
type ProtectConditionFunc = (arena: Arena, moveId: Moves) => boolean;
/**
* Class to implement conditional team protection
* applies protection based on the attributes of incoming moves
*/
export class ConditionalProtectTag extends ArenaTag {
/** The condition function to determine which moves are negated */
protected protectConditionFunc: ProtectConditionFunc;
/** Does this apply to all moves, including those that ignore other forms of protection? */
protected ignoresBypass: boolean;
constructor(tagType: ArenaTagType, sourceMove: Moves, sourceId: number, side: ArenaTagSide, condition: ProtectConditionFunc, ignoresBypass: boolean = false) {
super(tagType, 1, sourceMove, sourceId, side);
this.protectConditionFunc = condition;
this.ignoresBypass = ignoresBypass;
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:conditionalProtectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: super.getMoveName() }));
}
// Removes default message for effect removal
onRemove(arena: Arena): void { }
/**
* Checks incoming moves against the condition function
* and protects the target if conditions are met
* @param arena the {@linkcode Arena} containing this tag
* @param simulated `true` if the tag is applied quietly; `false` otherwise.
* @param isProtected a {@linkcode BooleanHolder} used to flag if the move is protected against
* @param attacker the attacking {@linkcode Pokemon}
* @param defender the defending {@linkcode Pokemon}
* @param moveId the {@linkcode Moves | identifier} for the move being used
* @param ignoresProtectBypass a {@linkcode BooleanHolder} used to flag if a protection effect supercedes effects that ignore protection
* @returns `true` if this tag protected against the attack; `false` otherwise
*/
override apply(arena: Arena, simulated: boolean, isProtected: BooleanHolder, attacker: Pokemon, defender: Pokemon,
moveId: Moves, ignoresProtectBypass: BooleanHolder): boolean {
if ((this.side === ArenaTagSide.PLAYER) === defender.isPlayer()
&& this.protectConditionFunc(arena, moveId)) {
if (!isProtected.value) {
isProtected.value = true;
if (!simulated) {
attacker.stopMultiHit(defender);
new CommonBattleAnim(CommonAnim.PROTECT, defender).play(arena.scene);
arena.scene.queueMessage(i18next.t("arenaTag:conditionalProtectApply", { moveName: super.getMoveName(), pokemonNameWithAffix: getPokemonNameWithAffix(defender) }));
}
}
ignoresProtectBypass.value = ignoresProtectBypass.value || this.ignoresBypass;
return true;
}
return false;
}
}
/**
* Condition function for {@link https://bulbapedia.bulbagarden.net/wiki/Quick_Guard_(move) Quick Guard's}
* protection effect.
* @param arena {@linkcode Arena} The arena containing the protection effect
* @param moveId {@linkcode Moves} The move to check against this condition
* @returns `true` if the incoming move's priority is greater than 0. This includes
* moves with modified priorities from abilities (e.g. Prankster)
*/
const QuickGuardConditionFunc: ProtectConditionFunc = (arena, moveId) => {
const move = allMoves[moveId];
const priority = new NumberHolder(move.priority);
const effectPhase = arena.scene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase) {
const attacker = effectPhase.getUserPokemon()!;
applyMoveAttrs(IncrementMovePriorityAttr, attacker, null, move, priority);
applyAbAttrs(ChangeMovePriorityAbAttr, attacker, null, false, move, priority);
}
return priority.value > 0;
};
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Quick_Guard_(move) Quick Guard}
* Condition: The incoming move has increased priority.
*/
class QuickGuardTag extends ConditionalProtectTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.QUICK_GUARD, Moves.QUICK_GUARD, sourceId, side, QuickGuardConditionFunc);
}
}
/**
* Condition function for {@link https://bulbapedia.bulbagarden.net/wiki/Wide_Guard_(move) Wide Guard's}
* protection effect.
* @param arena {@linkcode Arena} The arena containing the protection effect
* @param moveId {@linkcode Moves} The move to check against this condition
* @returns `true` if the incoming move is multi-targeted (even if it's only used against one Pokemon).
*/
const WideGuardConditionFunc: ProtectConditionFunc = (arena, moveId) : boolean => {
const move = allMoves[moveId];
switch (move.moveTarget) {
case MoveTarget.ALL_ENEMIES:
case MoveTarget.ALL_NEAR_ENEMIES:
case MoveTarget.ALL_OTHERS:
case MoveTarget.ALL_NEAR_OTHERS:
return true;
}
return false;
};
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Wide_Guard_(move) Wide Guard}
* Condition: The incoming move can target multiple Pokemon. The move's source
* can be an ally or enemy.
*/
class WideGuardTag extends ConditionalProtectTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.WIDE_GUARD, Moves.WIDE_GUARD, sourceId, side, WideGuardConditionFunc);
}
}
/**
* Condition function for {@link https://bulbapedia.bulbagarden.net/wiki/Mat_Block_(move) Mat Block's}
* protection effect.
* @param arena {@linkcode Arena} The arena containing the protection effect.
* @param moveId {@linkcode Moves} The move to check against this condition.
* @returns `true` if the incoming move is not a Status move.
*/
const MatBlockConditionFunc: ProtectConditionFunc = (arena, moveId) : boolean => {
const move = allMoves[moveId];
return move.category !== MoveCategory.STATUS;
};
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Mat_Block_(move) Mat Block}
* Condition: The incoming move is a Physical or Special attack move.
*/
class MatBlockTag extends ConditionalProtectTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.MAT_BLOCK, Moves.MAT_BLOCK, sourceId, side, MatBlockConditionFunc);
}
onAdd(arena: Arena) {
if (this.sourceId) {
const source = arena.scene.getPokemonById(this.sourceId);
if (source) {
arena.scene.queueMessage(i18next.t("arenaTag:matBlockOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
} else {
console.warn("Failed to get source for MatBlockTag onAdd");
}
}
}
}
/**
* Condition function for {@link https://bulbapedia.bulbagarden.net/wiki/Crafty_Shield_(move) Crafty Shield's}
* protection effect.
* @param arena {@linkcode Arena} The arena containing the protection effect
* @param moveId {@linkcode Moves} The move to check against this condition
* @returns `true` if the incoming move is a Status move, is not a hazard, and does not target all
* Pokemon or sides of the field.
*/
const CraftyShieldConditionFunc: ProtectConditionFunc = (arena, moveId) => {
const move = allMoves[moveId];
return move.category === MoveCategory.STATUS
&& move.moveTarget !== MoveTarget.ENEMY_SIDE
&& move.moveTarget !== MoveTarget.BOTH_SIDES
&& move.moveTarget !== MoveTarget.ALL;
};
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Crafty_Shield_(move) Crafty Shield}
* Condition: The incoming move is a Status move, is not a hazard, and does
* not target all Pokemon or sides of the field.
*/
class CraftyShieldTag extends ConditionalProtectTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.CRAFTY_SHIELD, Moves.CRAFTY_SHIELD, sourceId, side, CraftyShieldConditionFunc, true);
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Lucky_Chant_(move) Lucky Chant}.
* Prevents critical hits against the tag's side.
*/
export class NoCritTag extends ArenaTag {
/**
* Constructor method for the NoCritTag class
* @param turnCount `number` the number of turns this effect lasts
* @param sourceMove {@linkcode Moves} the move that created this effect
* @param sourceId `number` the ID of the {@linkcode Pokemon} that created this effect
* @param side {@linkcode ArenaTagSide} the side to which this effect belongs
*/
constructor(turnCount: number, sourceMove: Moves, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.NO_CRIT, turnCount, sourceMove, sourceId, side);
}
/** Queues a message upon adding this effect to the field */
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:noCritOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : "Enemy"}`, {
moveName: this.getMoveName()
}));
}
/** Queues a message upon removing this effect from the field */
onRemove(arena: Arena): void {
const source = arena.scene.getPokemonById(this.sourceId!); // TODO: is this bang correct?
arena.scene.queueMessage(i18next.t("arenaTag:noCritOnRemove", {
pokemonNameWithAffix: getPokemonNameWithAffix(source ?? undefined),
moveName: this.getMoveName()
}));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Wish_(move) Wish}.
* Heals the Pokémon in the user's position the turn after Wish is used.
*/
class WishTag extends ArenaTag {
private battlerIndex: BattlerIndex;
private triggerMessage: string;
private healHp: number;
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.WISH, turnCount, Moves.WISH, sourceId, side);
}
onAdd(arena: Arena): void {
if (this.sourceId) {
const user = arena.scene.getPokemonById(this.sourceId);
if (user) {
this.battlerIndex = user.getBattlerIndex();
this.triggerMessage = i18next.t("arenaTag:wishTagOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(user) });
this.healHp = toDmgValue(user.getMaxHp() / 2);
} else {
console.warn("Failed to get source for WishTag onAdd");
}
}
}
onRemove(arena: Arena): void {
const target = arena.scene.getField()[this.battlerIndex];
if (target?.isActive(true)) {
arena.scene.queueMessage(this.triggerMessage);
arena.scene.unshiftPhase(new PokemonHealPhase(target.scene, target.getBattlerIndex(), this.healHp, null, true, false));
}
}
}
/**
* Abstract class to implement weakened moves of a specific type.
*/
export class WeakenMoveTypeTag extends ArenaTag {
private weakenedType: Type;
/**
* Creates a new instance of the WeakenMoveTypeTag class.
*
* @param tagType - The type of the arena tag.
* @param turnCount - The number of turns the tag is active.
* @param type - The type being weakened from this tag.
* @param sourceMove - The move that created the tag.
* @param sourceId - The ID of the source of the tag.
*/
constructor(tagType: ArenaTagType, turnCount: number, type: Type, sourceMove: Moves, sourceId: number) {
super(tagType, turnCount, sourceMove, sourceId);
this.weakenedType = type;
}
/**
* Reduces an attack's power by 0.33x if it matches this tag's weakened type.
* @param arena n/a
* @param simulated n/a
* @param type the attack's {@linkcode Type}
* @param power a {@linkcode NumberHolder} containing the attack's power
* @returns `true` if the attack's power was reduced; `false` otherwise.
*/
override apply(arena: Arena, simulated: boolean, type: Type, power: NumberHolder): boolean {
if (type === this.weakenedType) {
power.value *= 0.33;
return true;
}
return false;
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Mud_Sport_(move) Mud Sport}.
* Weakens Electric type moves for a set amount of turns, usually 5.
*/
class MudSportTag extends WeakenMoveTypeTag {
constructor(turnCount: number, sourceId: number) {
super(ArenaTagType.MUD_SPORT, turnCount, Type.ELECTRIC, Moves.MUD_SPORT, sourceId);
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:mudSportOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:mudSportOnRemove"));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Water_Sport_(move) Water Sport}.
* Weakens Fire type moves for a set amount of turns, usually 5.
*/
class WaterSportTag extends WeakenMoveTypeTag {
constructor(turnCount: number, sourceId: number) {
super(ArenaTagType.WATER_SPORT, turnCount, Type.FIRE, Moves.WATER_SPORT, sourceId);
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:waterSportOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:waterSportOnRemove"));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Ion_Deluge_(move) | Ion Deluge}
* and the secondary effect of {@link https://bulbapedia.bulbagarden.net/wiki/Plasma_Fists_(move) | Plasma Fists}.
* Converts Normal-type moves to Electric type for the rest of the turn.
*/
export class IonDelugeTag extends ArenaTag {
constructor(sourceMove?: Moves) {
super(ArenaTagType.ION_DELUGE, 1, sourceMove);
}
/** Queues an on-add message */
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:plasmaFistsOnAdd"));
}
onRemove(arena: Arena): void { } // Removes default on-remove message
/**
* Converts Normal-type moves to Electric type
* @param arena n/a
* @param simulated n/a
* @param moveType a {@linkcode NumberHolder} containing a move's {@linkcode Type}
* @returns `true` if the given move type changed; `false` otherwise.
*/
override apply(arena: Arena, simulated: boolean, moveType: NumberHolder): boolean {
if (moveType.value === Type.NORMAL) {
moveType.value = Type.ELECTRIC;
return true;
}
return false;
}
}
/**
* Abstract class to implement arena traps.
*/
export class ArenaTrapTag extends ArenaTag {
public layers: number;
public maxLayers: number;
/**
* Creates a new instance of the ArenaTrapTag class.
*
* @param tagType - The type of the arena tag.
* @param sourceMove - The move that created the tag.
* @param sourceId - The ID of the source of the tag.
* @param side - The side (player or enemy) the tag affects.
* @param maxLayers - The maximum amount of layers this tag can have.
*/
constructor(tagType: ArenaTagType, sourceMove: Moves, sourceId: number, side: ArenaTagSide, maxLayers: number) {
super(tagType, 0, sourceMove, sourceId, side);
this.layers = 1;
this.maxLayers = maxLayers;
}
onOverlap(arena: Arena): void {
if (this.layers < this.maxLayers) {
this.layers++;
this.onAdd(arena);
}
}
/**
* Activates the hazard effect onto a Pokemon when it enters the field
* @param arena the {@linkcode Arena} containing this tag
* @param simulated if `true`, only checks if the hazard would activate.
* @param pokemon the {@linkcode Pokemon} triggering this hazard
* @returns `true` if this hazard affects the given Pokemon; `false` otherwise.
*/
override apply(arena: Arena, simulated: boolean, pokemon: Pokemon): boolean {
if ((this.side === ArenaTagSide.PLAYER) !== pokemon.isPlayer()) {
return false;
}
return this.activateTrap(pokemon, simulated);
}
activateTrap(pokemon: Pokemon, simulated: boolean): boolean {
return false;
}
getMatchupScoreMultiplier(pokemon: Pokemon): number {
return pokemon.isGrounded() ? 1 : Phaser.Math.Linear(0, 1 / Math.pow(2, this.layers), Math.min(pokemon.getHpRatio(), 0.5) * 2);
}
loadTag(source: any): void {
super.loadTag(source);
this.layers = source.layers;
this.maxLayers = source.maxLayers;
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Spikes_(move) Spikes}.
* Applies up to 3 layers of Spikes, dealing 1/8th, 1/6th, or 1/4th of the the Pokémon's HP
* in damage for 1, 2, or 3 layers of Spikes respectively if they are summoned into this trap.
*/
class SpikesTag extends ArenaTrapTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.SPIKES, Moves.SPIKES, sourceId, side, 3);
}
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:spikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
override activateTrap(pokemon: Pokemon, simulated: boolean): boolean {
if (pokemon.isGrounded()) {
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
if (simulated) {
return !cancelled.value;
}
if (!cancelled.value) {
const damageHpRatio = 1 / (10 - 2 * this.layers);
const damage = toDmgValue(pokemon.getMaxHp() * damageHpRatio);
pokemon.scene.queueMessage(i18next.t("arenaTag:spikesActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.damageAndUpdate(damage, HitResult.OTHER);
if (pokemon.turnData) {
pokemon.turnData.damageTaken += damage;
}
return true;
}
}
return false;
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Toxic_Spikes_(move) Toxic Spikes}.
* Applies up to 2 layers of Toxic Spikes, poisoning or badly poisoning any Pokémon who is
* summoned into this trap if 1 or 2 layers of Toxic Spikes respectively are up. Poison-type
* Pokémon summoned into this trap remove it entirely.
*/
class ToxicSpikesTag extends ArenaTrapTag {
private neutralized: boolean;
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.TOXIC_SPIKES, Moves.TOXIC_SPIKES, sourceId, side, 2);
this.neutralized = false;
}
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:toxicSpikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
onRemove(arena: Arena): void {
if (!this.neutralized) {
super.onRemove(arena);
}
}
override activateTrap(pokemon: Pokemon, simulated: boolean): boolean {
if (pokemon.isGrounded()) {
if (simulated) {
return true;
}
if (pokemon.isOfType(Type.POISON)) {
this.neutralized = true;
if (pokemon.scene.arena.removeTag(this.tagType)) {
pokemon.scene.queueMessage(i18next.t("arenaTag:toxicSpikesActivateTrapPoison", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
return true;
}
} else if (!pokemon.status) {
const toxic = this.layers > 1;
if (pokemon.trySetStatus(!toxic ? StatusEffect.POISON : StatusEffect.TOXIC, true, null, 0, this.getMoveName())) {
return true;
}
}
}
return false;
}
getMatchupScoreMultiplier(pokemon: Pokemon): number {
if (pokemon.isGrounded() || !pokemon.canSetStatus(StatusEffect.POISON, true)) {
return 1;
}
if (pokemon.isOfType(Type.POISON)) {
return 1.25;
}
return super.getMatchupScoreMultiplier(pokemon);
}
}
/**
* Arena Tag class for delayed attacks, such as {@linkcode Moves.FUTURE_SIGHT} or {@linkcode Moves.DOOM_DESIRE}.
* Delays the attack's effect by a set amount of turns, usually 3 (including the turn the move is used),
* and deals damage after the turn count is reached.
*/
class DelayedAttackTag extends ArenaTag {
public targetIndex: BattlerIndex;
constructor(tagType: ArenaTagType, sourceMove: Moves | undefined, sourceId: number, targetIndex: BattlerIndex) {
super(tagType, 3, sourceMove, sourceId);
this.targetIndex = targetIndex;
}
lapse(arena: Arena): boolean {
const ret = super.lapse(arena);
if (!ret) {
arena.scene.unshiftPhase(new MoveEffectPhase(arena.scene, this.sourceId!, [ this.targetIndex ], new PokemonMove(this.sourceMove!, 0, 0, true))); // TODO: are those bangs correct?
}
return ret;
}
onRemove(arena: Arena): void { }
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Stealth_Rock_(move) Stealth Rock}.
* Applies up to 1 layer of Stealth Rocks, dealing percentage-based damage to any Pokémon
* who is summoned into the trap, based on the Rock type's type effectiveness.
*/
class StealthRockTag extends ArenaTrapTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.STEALTH_ROCK, Moves.STEALTH_ROCK, sourceId, side, 1);
}
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:stealthRockOnAdd", { opponentDesc: source.getOpponentDescriptor() }));
}
}
getDamageHpRatio(pokemon: Pokemon): number {
const effectiveness = pokemon.getAttackTypeEffectiveness(Type.ROCK, undefined, true);
let damageHpRatio: number = 0;
switch (effectiveness) {
case 0:
damageHpRatio = 0;
break;
case 0.25:
damageHpRatio = 0.03125;
break;
case 0.5:
damageHpRatio = 0.0625;
break;
case 1:
damageHpRatio = 0.125;
break;
case 2:
damageHpRatio = 0.25;
break;
case 4:
damageHpRatio = 0.5;
break;
}
return damageHpRatio;
}
override activateTrap(pokemon: Pokemon, simulated: boolean): boolean {
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
if (cancelled.value) {
return false;
}
const damageHpRatio = this.getDamageHpRatio(pokemon);
if (damageHpRatio) {
if (simulated) {
return true;
}
const damage = toDmgValue(pokemon.getMaxHp() * damageHpRatio);
pokemon.scene.queueMessage(i18next.t("arenaTag:stealthRockActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.damageAndUpdate(damage, HitResult.OTHER);
if (pokemon.turnData) {
pokemon.turnData.damageTaken += damage;
}
return true;
}
return false;
}
getMatchupScoreMultiplier(pokemon: Pokemon): number {
const damageHpRatio = this.getDamageHpRatio(pokemon);
return Phaser.Math.Linear(super.getMatchupScoreMultiplier(pokemon), 1, 1 - Math.pow(damageHpRatio, damageHpRatio));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Sticky_Web_(move) Sticky Web}.
* Applies up to 1 layer of Sticky Web, which lowers the Speed by one stage
* to any Pokémon who is summoned into this trap.
*/
class StickyWebTag extends ArenaTrapTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.STICKY_WEB, Moves.STICKY_WEB, sourceId, side, 1);
}
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:stickyWebOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
override activateTrap(pokemon: Pokemon, simulated: boolean): boolean {
if (pokemon.isGrounded()) {
const cancelled = new BooleanHolder(false);
applyAbAttrs(ProtectStatAbAttr, pokemon, cancelled);
if (simulated) {
return !cancelled.value;
}
if (!cancelled.value) {
pokemon.scene.queueMessage(i18next.t("arenaTag:stickyWebActivateTrap", { pokemonName: pokemon.getNameToRender() }));
const stages = new NumberHolder(-1);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), false, [ Stat.SPD ], stages.value));
return true;
}
}
return false;
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Trick_Room_(move) Trick Room}.
* Reverses the Speed stats for all Pokémon on the field as long as this arena tag is up,
* also reversing the turn order for all Pokémon on the field as well.
*/
export class TrickRoomTag extends ArenaTag {
constructor(turnCount: number, sourceId: number) {
super(ArenaTagType.TRICK_ROOM, turnCount, Moves.TRICK_ROOM, sourceId);
}
/**
* Reverses Speed-based turn order for all Pokemon on the field
* @param arena n/a
* @param simulated n/a
* @param speedReversed a {@linkcode BooleanHolder} used to flag if Speed-based
* turn order should be reversed.
* @returns `true` if turn order is successfully reversed; `false` otherwise
*/
override apply(arena: Arena, simulated: boolean, speedReversed: BooleanHolder): boolean {
speedReversed.value = !speedReversed.value;
return true;
}
onAdd(arena: Arena): void {
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
if (source) {
arena.scene.queueMessage(i18next.t("arenaTag:trickRoomOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
}
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:trickRoomOnRemove"));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Gravity_(move) Gravity}.
* Grounds all Pokémon on the field, including Flying-types and those with
* {@linkcode Abilities.LEVITATE} for the duration of the arena tag, usually 5 turns.
*/
export class GravityTag extends ArenaTag {
constructor(turnCount: number) {
super(ArenaTagType.GRAVITY, turnCount, Moves.GRAVITY);
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:gravityOnAdd"));
arena.scene.getField(true).forEach((pokemon) => {
if (pokemon !== null) {
pokemon.removeTag(BattlerTagType.FLOATING);
pokemon.removeTag(BattlerTagType.TELEKINESIS);
if (pokemon.getTag(BattlerTagType.FLYING)) {
pokemon.addTag(BattlerTagType.INTERRUPTED);
}
}
});
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:gravityOnRemove"));
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Tailwind_(move) Tailwind}.
* Doubles the Speed of the Pokémon who created this arena tag, as well as all allied Pokémon.
* Applies this arena tag for 4 turns (including the turn the move was used).
*/
class TailwindTag extends ArenaTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.TAILWIND, turnCount, Moves.TAILWIND, sourceId, side);
}
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:tailwindOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
const source = arena.scene.getPokemonById(this.sourceId!); //TODO: this bang is questionable!
const party = (source?.isPlayer() ? source.scene.getPlayerField() : source?.scene.getEnemyField()) ?? [];
for (const pokemon of party) {
// Apply the CHARGED tag to party members with the WIND_POWER ability
if (pokemon.hasAbility(Abilities.WIND_POWER) && !pokemon.getTag(BattlerTagType.CHARGED)) {
pokemon.addTag(BattlerTagType.CHARGED);
pokemon.scene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
}
// Raise attack by one stage if party member has WIND_RIDER ability
if (pokemon.hasAbility(Abilities.WIND_RIDER)) {
pokemon.scene.unshiftPhase(new ShowAbilityPhase(pokemon.scene, pokemon.getBattlerIndex()));
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.ATK ], 1, true));
}
}
}
onRemove(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:tailwindOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
/**
* Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Happy_Hour_(move) Happy Hour}.
* Doubles the prize money from trainers and money moves like {@linkcode Moves.PAY_DAY} and {@linkcode Moves.MAKE_IT_RAIN}.
*/
class HappyHourTag extends ArenaTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.HAPPY_HOUR, turnCount, Moves.HAPPY_HOUR, sourceId, side);
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:happyHourOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:happyHourOnRemove"));
}
}
class SafeguardTag extends ArenaTag {
constructor(turnCount: number, sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.SAFEGUARD, turnCount, Moves.SAFEGUARD, sourceId, side);
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:safeguardOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:safeguardOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
class NoneTag extends ArenaTag {
constructor() {
super(ArenaTagType.NONE, 0);
}
}
/**
* This arena tag facilitates the application of the move Imprison
* Imprison remains in effect as long as the source Pokemon is active and present on the field.
* Imprison will apply to any opposing Pokemon that switch onto the field as well.
*/
class ImprisonTag extends ArenaTrapTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.IMPRISON, Moves.IMPRISON, sourceId, side, 1);
}
/**
* This function applies the effects of Imprison to the opposing Pokemon already present on the field.
* @param arena
*/
override onAdd({ scene }: Arena) {
const source = this.getSourcePokemon(scene);
if (source) {
const party = this.getAffectedPokemon(scene);
party?.forEach((p: Pokemon ) => {
if (p.isAllowedInBattle()) {
p.addTag(BattlerTagType.IMPRISON, 1, Moves.IMPRISON, this.sourceId);
}
});
scene.queueMessage(i18next.t("battlerTags:imprisonOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
}
}
/**
* Checks if the source Pokemon is still active on the field
* @param _arena
* @returns `true` if the source of the tag is still active on the field | `false` if not
*/
override lapse({ scene }: Arena): boolean {
const source = this.getSourcePokemon(scene);
return source ? source.isActive(true) : false;
}
/**
* This applies the effects of Imprison to any opposing Pokemon that switch into the field while the source Pokemon is still active
* @param {Pokemon} pokemon the Pokemon Imprison is applied to
* @returns `true`
*/
override activateTrap(pokemon: Pokemon): boolean {
const source = this.getSourcePokemon(pokemon.scene);
if (source && source.isActive(true) && pokemon.isAllowedInBattle()) {
pokemon.addTag(BattlerTagType.IMPRISON, 1, Moves.IMPRISON, this.sourceId);
}
return true;
}
/**
* When the arena tag is removed, it also attempts to remove any related Battler Tags if they haven't already been removed from the affected Pokemon
* @param arena
*/
override onRemove({ scene }: Arena): void {
const party = this.getAffectedPokemon(scene);
party?.forEach((p: Pokemon) => {
p.removeTag(BattlerTagType.IMPRISON);
});
}
}
/**
* Arena Tag implementing the "sea of fire" effect from the combination
* of {@link https://bulbapedia.bulbagarden.net/wiki/Fire_Pledge_(move) | Fire Pledge}
* and {@link https://bulbapedia.bulbagarden.net/wiki/Grass_Pledge_(move) | Grass Pledge}.
* Damages all non-Fire-type Pokemon on the given side of the field at the end
* of each turn for 4 turns.
*/
class FireGrassPledgeTag extends ArenaTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.FIRE_GRASS_PLEDGE, 4, Moves.FIRE_PLEDGE, sourceId, side);
}
override onAdd(arena: Arena): void {
// "A sea of fire enveloped your/the opposing team!"
arena.scene.queueMessage(i18next.t(`arenaTag:fireGrassPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
override lapse(arena: Arena): boolean {
const field: Pokemon[] = (this.side === ArenaTagSide.PLAYER)
? arena.scene.getPlayerField()
: arena.scene.getEnemyField();
field.filter(pokemon => !pokemon.isOfType(Type.FIRE)).forEach(pokemon => {
// "{pokemonNameWithAffix} was hurt by the sea of fire!"
pokemon.scene.queueMessage(i18next.t("arenaTag:fireGrassPledgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
// TODO: Replace this with a proper animation
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.MAGMA_STORM));
pokemon.damageAndUpdate(toDmgValue(pokemon.getMaxHp() / 8));
});
return super.lapse(arena);
}
}
/**
* Arena Tag implementing the "rainbow" effect from the combination
* of {@link https://bulbapedia.bulbagarden.net/wiki/Water_Pledge_(move) | Water Pledge}
* and {@link https://bulbapedia.bulbagarden.net/wiki/Fire_Pledge_(move) | Fire Pledge}.
* Doubles the secondary effect chance of moves from Pokemon on the
* given side of the field for 4 turns.
*/
class WaterFirePledgeTag extends ArenaTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.WATER_FIRE_PLEDGE, 4, Moves.WATER_PLEDGE, sourceId, side);
}
override onAdd(arena: Arena): void {
// "A rainbow appeared in the sky on your/the opposing team's side!"
arena.scene.queueMessage(i18next.t(`arenaTag:waterFirePledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
/**
* Doubles the chance for the given move's secondary effect(s) to trigger
* @param arena the {@linkcode Arena} containing this tag
* @param simulated n/a
* @param moveChance a {@linkcode NumberHolder} containing
* the move's current effect chance
* @returns `true` if the move's effect chance was doubled (currently always `true`)
*/
override apply(arena: Arena, simulated: boolean, moveChance: NumberHolder): boolean {
moveChance.value *= 2;
return true;
}
}
/**
* Arena Tag implementing the "swamp" effect from the combination
* of {@link https://bulbapedia.bulbagarden.net/wiki/Grass_Pledge_(move) | Grass Pledge}
* and {@link https://bulbapedia.bulbagarden.net/wiki/Water_Pledge_(move) | Water Pledge}.
* Quarters the Speed of Pokemon on the given side of the field for 4 turns.
*/
class GrassWaterPledgeTag extends ArenaTag {
constructor(sourceId: number, side: ArenaTagSide) {
super(ArenaTagType.GRASS_WATER_PLEDGE, 4, Moves.GRASS_PLEDGE, sourceId, side);
}
override onAdd(arena: Arena): void {
// "A swamp enveloped your/the opposing team!"
arena.scene.queueMessage(i18next.t(`arenaTag:grassWaterPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
// TODO: swap `sourceMove` and `sourceId` and make `sourceMove` an optional parameter
export function getArenaTag(tagType: ArenaTagType, turnCount: number, sourceMove: Moves | undefined, sourceId: number, targetIndex?: BattlerIndex, side: ArenaTagSide = ArenaTagSide.BOTH): ArenaTag | null {
switch (tagType) {
case ArenaTagType.MIST:
return new MistTag(turnCount, sourceId, side);
case ArenaTagType.QUICK_GUARD:
return new QuickGuardTag(sourceId, side);
case ArenaTagType.WIDE_GUARD:
return new WideGuardTag(sourceId, side);
case ArenaTagType.MAT_BLOCK:
return new MatBlockTag(sourceId, side);
case ArenaTagType.CRAFTY_SHIELD:
return new CraftyShieldTag(sourceId, side);
case ArenaTagType.NO_CRIT:
return new NoCritTag(turnCount, sourceMove!, sourceId, side); // TODO: is this bang correct?
case ArenaTagType.MUD_SPORT:
return new MudSportTag(turnCount, sourceId);
case ArenaTagType.WATER_SPORT:
return new WaterSportTag(turnCount, sourceId);
case ArenaTagType.ION_DELUGE:
return new IonDelugeTag(sourceMove);
case ArenaTagType.SPIKES:
return new SpikesTag(sourceId, side);
case ArenaTagType.TOXIC_SPIKES:
return new ToxicSpikesTag(sourceId, side);
case ArenaTagType.FUTURE_SIGHT:
case ArenaTagType.DOOM_DESIRE:
return new DelayedAttackTag(tagType, sourceMove, sourceId, targetIndex!); // TODO:questionable bang
case ArenaTagType.WISH:
return new WishTag(turnCount, sourceId, side);
case ArenaTagType.STEALTH_ROCK:
return new StealthRockTag(sourceId, side);
case ArenaTagType.STICKY_WEB:
return new StickyWebTag(sourceId, side);
case ArenaTagType.TRICK_ROOM:
return new TrickRoomTag(turnCount, sourceId);
case ArenaTagType.GRAVITY:
return new GravityTag(turnCount);
case ArenaTagType.REFLECT:
return new ReflectTag(turnCount, sourceId, side);
case ArenaTagType.LIGHT_SCREEN:
return new LightScreenTag(turnCount, sourceId, side);
case ArenaTagType.AURORA_VEIL:
return new AuroraVeilTag(turnCount, sourceId, side);
case ArenaTagType.TAILWIND:
return new TailwindTag(turnCount, sourceId, side);
case ArenaTagType.HAPPY_HOUR:
return new HappyHourTag(turnCount, sourceId, side);
case ArenaTagType.SAFEGUARD:
return new SafeguardTag(turnCount, sourceId, side);
case ArenaTagType.IMPRISON:
return new ImprisonTag(sourceId, side);
case ArenaTagType.FIRE_GRASS_PLEDGE:
return new FireGrassPledgeTag(sourceId, side);
case ArenaTagType.WATER_FIRE_PLEDGE:
return new WaterFirePledgeTag(sourceId, side);
case ArenaTagType.GRASS_WATER_PLEDGE:
return new GrassWaterPledgeTag(sourceId, side);
default:
return null;
}
}
/**
* When given a battler tag or json representing one, creates an actual ArenaTag object with the same data.
* @param {ArenaTag | any} source An arena tag
* @return {ArenaTag} The valid arena tag
*/
export function loadArenaTag(source: ArenaTag | any): ArenaTag {
const tag = getArenaTag(source.tagType, source.turnCount, source.sourceMove, source.sourceId, source.targetIndex, source.side)
?? new NoneTag();
tag.loadTag(source);
return tag;
}
| 412 | 0.979441 | 1 | 0.979441 | game-dev | MEDIA | 0.900832 | game-dev | 0.943935 | 1 | 0.943935 |
ggnkua/Atari_ST_Sources | 28,889 | C/Christophe Fontanel/ReDMCSB_Release2/SOURCE/ENGINE/DIALOG.C | #include "DEFS.H"
/*_Global variables_*/
#ifdef C09_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_CSB20EN_CSB21EN /* CHANGE4_00_LOCALIZATION Translation to German language */
#ifdef C02_COMPILE_DM10aEN_DM10bEN_DM11EN /* CHANGE3_16_OPTIMIZATION Variables reordered */
char* G548_pc_D096_PUTTHEGAMESAVEDISKIN = "PUT GAME SAVE DISK IN DRIVE A:";
#endif
char* G536_pc_D084_GAMELOADEDREADYTOPLAY = "GAME LOADED, READY TO PLAY.";
#ifdef C03_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G537_pc_D085_CANTMODIFYGAMEDISK = "CAN'T MODIFY DUNGEON MASTER DISK!";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G537_pc_D085_CANTMODIFYGAMEDISK = "CAN'T MODIFY CHAOS STRIKES BACK DISK!";
#endif
#ifdef C02_COMPILE_DM10aEN_DM10bEN_DM11EN /* CHANGE3_16_OPTIMIZATION Variables reordered */
char* G549_pc_D097_PUTTHEGAMEDISKIN = "PUT DUNGEON MASTER DISK IN A:";
#endif
char* G538_pc_D086_THATSNOTTHEMASTERDISK = "THAT'S NOT THE MASTER DISK!";
#ifdef C02_COMPILE_DM10aEN_DM10bEN_DM11EN /* CHANGE3_16_OPTIMIZATION Variables reordered */
char* G550_pc_D098_PUTABLANKDISKIN = "PUT A BLANK DISK IN DRIVE A:";
#endif
char* G539_pc_D087_CANTFINDSAVEDGAME = "CAN'T FIND SAVED GAME!";
char* G540_pc_D088_UNABLETOSAVEGAME = "UNABLE TO SAVE GAME!";
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_31_IMPROVEMENT */
char* G541_pc_D089_UNABLETOFORMATDISK = "UNABLE TO FORMAT DISK!";
#endif
#ifdef C03_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G542_pc_D090_THATSTHEGAMEDISK = "THAT'S THE DUNGEON MASTER DISK!";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G542_pc_D090_THATSTHEGAMEDISK = "THAT'S THE CHAOS STRIKES BACK DISK!";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_31_IMPROVEMENT */
char* G543_pc_D091_THATSAGAMESAVEDISK = "THAT'S A GAME SAVE DISK!";
#endif
char* G544_pc_D092_THATDISKISWRITEPROTECTED = "THAT DISK IS WRITE-PROTECTED!";
#ifdef C03_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G545_pc_D093_THATDISKISUNREADABLE = "THAT DISK IS UNREADABLE.";
char* G546_pc_D094_THATSNOTTHESAMEGAME = "THAT'S NOT THE SAME GAME.";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G545_pc_D093_THATDISKISUNREADABLE = "THAT DISK IS UNREADABLE";
char* G546_pc_D094_THATSNOTTHESAMEGAME = "THAT'S NOT THE SAME GAME";
#endif
#ifdef C20_COMPILE_DM12EN_CSB20EN_CSB21EN /* CHANGE3_17_IMPROVEMENT */
char* G547_pc_D095_SAVEDGAMEDAMAGED = "SAVED GAME DAMAGED!";
#endif
#ifdef C16_COMPILE_DM12EN /* CHANGE3_16_OPTIMIZATION Variables reordered */
char* G548_pc_D096_PUTTHEGAMESAVEDISKIN = "PUT GAME SAVE DISK IN DRIVE A:";
char* G549_pc_D097_PUTTHEGAMEDISKIN = "PUT DUNGEON MASTER DISK IN A:";
char* G550_pc_D098_PUTABLANKDISKIN = "PUT A BLANK DISK IN DRIVE A:";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_03_IMPROVEMENT Support for two floppy disk drives CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G548_pc_D096_PUTTHEGAMESAVEDISKIN = "PUT THE GAME SAVE DISK IN ~";
char* G549_pc_D097_PUTTHEGAMEDISKIN = "PUT THE CHAOS STRIKES BACK DISK IN ~";
char* G550_pc_D098_PUTABLANKDISKIN = "PUT A BLANK DISK IN ~";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_07_LOCALIZATION Translation to English language (differences with original Dungeon Master) */
char* G551_pc_D099_SAVINGGAME = "SAVING GAME . . .";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_32_IMPROVEMENT */
char* G552_pc_D100_LOADINGGAME = "LOADING GAME . . .";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_31_IMPROVEMENT */
char* G553_pc_D101_FORMATTINGDISK = "FORMATTING DISK . . .";
char* G554_pc_D102_FORMATDISKANYWAY = "FORMAT DISK ANYWAY?";
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_31_IMPROVEMENT CHANGE7_32_IMPROVEMENT CHANGE7_33_IMPROVEMENT */
char* G555_pc_D103_THEREISNODISKIN = "THERE IS NO DISK IN ~!";
#endif
char* G556_pc_D104_LOADSAVEDGAME = "LOAD SAVED GAME";
char* G557_pc_D105_SAVEANDPLAY = "SAVE AND PLAY";
char* G558_pc_D106_SAVEANDQUIT = "SAVE AND QUIT";
char* G559_pc_D107_FORMATFLOPPY = "FORMAT FLOPPY";
char* G560_pc_D108_OK = "OK";
char* G561_pc_D109_CANCEL = "CANCEL";
#endif
#ifdef C21_COMPILE_DM12GE /* CHANGE4_00_LOCALIZATION Translation to German language */
char* G536_pc_D084_GAMELOADEDREADYTOPLAY = "SPIEL GELADEN, STARTBEREIT.";
char* G537_pc_D085_CANTMODIFYGAMEDISK = "DM KANN NICHT GEAENDERT WERDEN!";
char* G538_pc_D086_THATSNOTTHEMASTERDISK = "DIES IST NICHT DIE ORIGINALDISK!";
char* G539_pc_D087_CANTFINDSAVEDGAME = "GESICHERTES SPIEL NICHT ZU FINDEN";
char* G540_pc_D088_UNABLETOSAVEGAME = "KEIN SICHERN MOEGLICH!";
char* G542_pc_D090_THATSTHEGAMEDISK = "DIES IST DIE DM-ORIGINALDISKETTE!";
char* G544_pc_D092_THATDISKISWRITEPROTECTED = "DISKETTE IST SCHREIBGESCHUETZT!";
char* G545_pc_D093_THATDISKISUNREADABLE = "DISKETTE NICHT LESBAR.";
char* G546_pc_D094_THATSNOTTHESAMEGAME = "DIES IST NICHT DASSELBE SPIEL.";
char* G547_pc_D095_SAVEDGAMEDAMAGED = "SAVED GAME DAMAGED!";
char* G548_pc_D096_PUTTHEGAMESAVEDISKIN = "ARCHIV-DISK IN A LAUFWERK A LEGEN";
char* G549_pc_D097_PUTTHEGAMEDISKIN = "DM-DISK IN A EINLEGEN";
char* G550_pc_D098_PUTABLANKDISKIN = "LEERE DISKETTE IN A EINLEGEN";
char* G556_pc_D104_LOADSAVEDGAME = "ARCHIVIERTES SPIEL LADEN";
char* G557_pc_D105_SAVEANDPLAY = "SICHERN/SPIEL";
char* G558_pc_D106_SAVEANDQUIT = "SICHERN/ENDEN";
char* G559_pc_D107_FORMATFLOPPY = "FORMATIEREN";
char* G560_pc_D108_OK = "OK";
char* G561_pc_D109_CANCEL = "WIDERRUFEN";
#endif
#ifdef C23_COMPILE_DM13aFR_DM13bFR /* CHANGE5_00_LOCALIZATION Translation to French language */
char* G536_pc_D084_GAMELOADEDREADYTOPLAY = "JEU CHARGE, PRET A COMMENCER.";
char* G537_pc_D085_CANTMODIFYGAMEDISK = "DISQUE NE PEUT ETRE MODIFIE";
char* G538_pc_D086_THATSNOTTHEMASTERDISK = "CECI N'EST PAS LE DISQUE MAITRE!";
char* G539_pc_D087_CANTFINDSAVEDGAME = "JEU SAUVEGARDE EST ABSENT";
char* G540_pc_D088_UNABLETOSAVEGAME = "IMPOSSIBLE DE SAUVEGARDER LE JEU!";
char* G542_pc_D090_THATSTHEGAMEDISK = "CECI EST LE DISQUE MAITRE!";
char* G544_pc_D092_THATDISKISWRITEPROTECTED = "DISQUE BLOQUE";
char* G545_pc_D093_THATDISKISUNREADABLE = "DISQUE ILLISIBLE";
char* G546_pc_D094_THATSNOTTHESAMEGAME = "JEU DIFFERENT";
char* G547_pc_D095_SAVEDGAMEDAMAGED = "SAVED GAME DAMAGED!";
char* G548_pc_D096_PUTTHEGAMESAVEDISKIN = "DISQUE DE SAUVEGARDE DU JEU EN A:";
char* G549_pc_D097_PUTTHEGAMEDISKIN = "METTRE DISQUE MAITRE EN A:";
char* G550_pc_D098_PUTABLANKDISKIN = "METTRE UN DISQUE VIERGE EN A:";
char* G551_pc_D099_SAVINGGAME = "UN MOMENT A SAUVEGARDER DU JEU...";
char* G556_pc_D104_LOADSAVEDGAME = "CHARGER JEU SAUVEGARDE";
char* G557_pc_D105_SAVEANDPLAY = "GARDER: JOUER";
char* G558_pc_D106_SAVEANDQUIT = "GARDER: SORTIR";
char* G559_pc_D107_FORMATFLOPPY = "FORMATER A:";
char* G560_pc_D108_OK = "OK";
char* G561_pc_D109_CANCEL = "ANNULLER";
#endif
overlay "start"
#ifdef C06_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR /* CHANGE7_34_OPTIMIZATION Function calls to show and hide the mouse pointer on screen are now included in the function to get the player's choice in dialogs */
int F424_xxxx_DIALOG_GetChoice(P824_i_ChoiceCount, P825_i_DialogSetIndex)
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION */
int F424_xxxx_DIALOG_GetChoice(P824_i_ChoiceCount, P825_i_DialogSetIndex, P826_i_Unreferenced, P827_i_Useless)
#endif
int P824_i_ChoiceCount;
int P825_i_DialogSetIndex;
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION */
int P826_i_Unreferenced; /* BUG0_00 Useless code */
int P827_i_Useless; /* BUG0_00 Useless code */
#endif
{
MOUSE_INPUT* L1298_ps_PrimaryMouseInputBackup;
MOUSE_INPUT* L1299_ps_SecondaryMouseInputBackup;
KEYBOARD_INPUT* L1300_ps_PrimaryKeyboardInputBackup;
KEYBOARD_INPUT* L1301_ps_SecondaryKeyboardInputBackup;
int L1302_i_Unreferenced; /* BUG0_00 Useless code */
BOX_WORD L1303_s_BoxB;
BOX_WORD L1304_s_BoxA;
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION In previous versions, this function was always called prior to this function */
F078_xzzz_MOUSE_ShowPointer();
#endif
L1298_ps_PrimaryMouseInputBackup = G441_ps_PrimaryMouseInput;
L1299_ps_SecondaryMouseInputBackup = G442_ps_SecondaryMouseInput;
L1300_ps_PrimaryKeyboardInputBackup = G443_ps_PrimaryKeyboardInput;
L1301_ps_SecondaryKeyboardInputBackup = G444_ps_SecondaryKeyboardInput;
G442_ps_SecondaryMouseInput = G443_ps_PrimaryKeyboardInput = G444_ps_SecondaryKeyboardInput = NULL;
G441_ps_PrimaryMouseInput = G480_aaps_PrimaryMouseInput_DialogSets[P825_i_DialogSetIndex][P824_i_ChoiceCount - 1];
F357_qzzz_COMMAND_DiscardAllInput();
G335_i_SelectedDialogChoice = 99;
do {
F380_xzzz_COMMAND_ProcessQueue_COPYPROTECTIONC();
Vsync();
if ((G335_i_SelectedDialogChoice == 99) && (P824_i_ChoiceCount == 1) && Cconis() && ((int)Crawcin() == '\r')) { /* If a choice has not been made yet with the mouse and the dialog has only one possible choice and carriage return was pressed on the keyboard */
G335_i_SelectedDialogChoice = 1;
}
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION */
if (FALSE) { /* BUG0_00 Useless code */
G335_i_SelectedDialogChoice = P827_i_Useless;
}
#endif
} while (G335_i_SelectedDialogChoice == 99);
G578_B_UseByteBoxCoordinates = FALSE;
F007_aAA7_MAIN_CopyBytes(&G441_ps_PrimaryMouseInput[G335_i_SelectedDialogChoice - 1].Box, &L1304_s_BoxA, sizeof(BOX_WORD));
L1304_s_BoxA.X1 -= 3;
L1304_s_BoxA.X2 += 3;
L1304_s_BoxA.Y1 -= 3;
L1304_s_BoxA.Y2 += 4;
F077_aA39_MOUSE_HidePointer_COPYPROTECTIONE();
G297_B_DrawFloorAndCeilingRequested = TRUE;
L1303_s_BoxB.X1 = 0;
L1303_s_BoxB.Y1 = 0;
L1303_s_BoxB.Y2 = L1304_s_BoxA.Y2 - L1304_s_BoxA.Y1 + 3;
L1303_s_BoxB.X2 = L1304_s_BoxA.X2 - L1304_s_BoxA.X1 + 3;
F132_xzzz_VIDEO_Blit(G348_pl_Bitmap_LogicalScreenBase, G296_puc_Bitmap_Viewport, &L1303_s_BoxB, L1304_s_BoxA.X1, L1304_s_BoxA.Y1, C160_BYTE_WIDTH_SCREEN, C160_BYTE_WIDTH_SCREEN, CM1_COLOR_NO_TRANSPARENCY);
Vsync();
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.Y2 = L1303_s_BoxB.Y1;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C05_COLOR_LIGHT_BROWN, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.X2 = L1303_s_BoxB.X1;
L1303_s_BoxB.Y2--;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C05_COLOR_LIGHT_BROWN, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.Y2--;
L1303_s_BoxB.Y1 = (int)L1303_s_BoxB.Y2;
L1303_s_BoxB.X1 -= 2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C00_COLOR_BLACK, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.X1 = L1303_s_BoxB.X2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C00_COLOR_BLACK, C160_BYTE_WIDTH_SCREEN);
F022_aaaU_MAIN_Delay(5);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.Y1++;
L1303_s_BoxB.Y2 = (int)L1303_s_BoxB.Y1;
L1303_s_BoxB.X2 -= 2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C05_COLOR_LIGHT_BROWN, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.X1++;
L1303_s_BoxB.X2 = (int)L1303_s_BoxB.X1;
L1303_s_BoxB.Y2--;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C05_COLOR_LIGHT_BROWN, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.X2--;
L1303_s_BoxB.X1 = (int)L1303_s_BoxB.X2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C00_COLOR_BLACK, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.Y1 = L1303_s_BoxB.Y2 = L1303_s_BoxB.Y2 - 2;
L1303_s_BoxB.X1++;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C00_COLOR_BLACK, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.Y1 = L1303_s_BoxB.Y2 = L1303_s_BoxB.Y2 + 2;
L1303_s_BoxB.X1--;
L1303_s_BoxB.X2 += 2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C13_COLOR_LIGHTEST_GRAY, C160_BYTE_WIDTH_SCREEN);
F007_aAA7_MAIN_CopyBytes(&L1304_s_BoxA, &L1303_s_BoxB, sizeof(L1303_s_BoxB));
L1303_s_BoxB.X1 = L1303_s_BoxB.X2 = L1303_s_BoxB.X2 + 3;
L1303_s_BoxB.Y2 += 2;
F135_xzzz_VIDEO_FillBox(G348_pl_Bitmap_LogicalScreenBase, &L1303_s_BoxB, C13_COLOR_LIGHTEST_GRAY, C160_BYTE_WIDTH_SCREEN);
F022_aaaU_MAIN_Delay(5);
L1304_s_BoxA.X2 += 3;
L1304_s_BoxA.Y2 += 3;
F132_xzzz_VIDEO_Blit(G296_puc_Bitmap_Viewport, G348_pl_Bitmap_LogicalScreenBase, &L1304_s_BoxA, 0, 0, C160_BYTE_WIDTH_SCREEN, C160_BYTE_WIDTH_SCREEN, CM1_COLOR_NO_TRANSPARENCY);
F078_xzzz_MOUSE_ShowPointer();
G441_ps_PrimaryMouseInput = L1298_ps_PrimaryMouseInputBackup;
G442_ps_SecondaryMouseInput = L1299_ps_SecondaryMouseInputBackup;
G443_ps_PrimaryKeyboardInput = L1300_ps_PrimaryKeyboardInputBackup;
G444_ps_SecondaryKeyboardInput = L1301_ps_SecondaryKeyboardInputBackup;
F357_qzzz_COMMAND_DiscardAllInput();
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION In previous versions, this function was always called prior to this function */
F077_aA39_MOUSE_HidePointer_COPYPROTECTIONE();
#endif
return G335_i_SelectedDialogChoice;
}
VOID F425_xxxx_DIALOG_PrintCenteredChoice(P828_puc_Bitmap, P829_pc_String, P830_i_X, P831_i_Y)
unsigned char* P828_puc_Bitmap;
char* P829_pc_String;
int P830_i_X;
int P831_i_Y;
{
if (P829_pc_String != NULL) {
P830_i_X -= (strlen(P829_pc_String) * 6) >> 1;
F040_aacZ_TEXT_Print(P828_puc_Bitmap, C112_BYTE_WIDTH_VIEWPORT, P830_i_X , P831_i_Y, C09_COLOR_GOLD, C05_COLOR_LIGHT_BROWN, P829_pc_String);
}
}
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT If a text message in a dialog is too long then it is split and printed on two lines */
BOOLEAN F426_xxxx_DIALOG_IsMessageOnTwoLines(P832_pc_String, P833_pc_Part1, P834_pc_Part2)
char* P832_pc_String;
char* P833_pc_Part1;
char* P834_pc_Part2;
{
unsigned int L1305_ui_StringLength;
unsigned int L1306_ui_SplitPosition;
L1305_ui_StringLength = strlen(P832_pc_String);
if (L1305_ui_StringLength <= 30) {
return FALSE;
}
strcpy(P833_pc_Part1, P832_pc_String);
L1306_ui_SplitPosition = L1305_ui_StringLength >> 1;
while ((P833_pc_Part1[L1306_ui_SplitPosition] != ' ') && L1306_ui_SplitPosition < L1305_ui_StringLength) {
L1306_ui_SplitPosition++;
}
P833_pc_Part1[L1306_ui_SplitPosition] = '\0';
strcpy(P834_pc_Part2, &P833_pc_Part1[L1306_ui_SplitPosition + 1]);
return TRUE;
}
#endif
VOID F427_xxxx_DIALOG_Draw(P835_pc_Message1, P836_pc_Message2, P837_pc_Choice1, P838_pc_Choice2, P839_pc_Choice3, P840_pc_Choice4, P841_B_ScreenDialog, P842_B_ClearScreen, P843_B_Fading)
char* P835_pc_Message1;
char* P836_pc_Message2;
char* P837_pc_Choice1;
char* P838_pc_Choice2;
char* P839_pc_Choice3;
char* P840_pc_Choice4;
BOOLEAN P841_B_ScreenDialog;
BOOLEAN P842_B_ClearScreen;
BOOLEAN P843_B_Fading;
{
register int L1307_i_Unreferenced; /* BUG0_00 Useless code */
register int L1308_i_X;
register int L1309_i_Y;
register int L1310_i_ChoiceCount;
#ifdef C00_COMPILE_DM10aEN /* CHANGE1_00_OPTIMIZATION */
unsigned int L1311_aui_Palette_Blank[16];
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT */
char L1312_ac_StringPart1[50];
char L1313_ac_StringPart2[50];
#endif
BOX_WORD L1314_s_Box;
unsigned char* L1315_puc_Bitmap_DialogPatch;
F466_rzzz_EXPAND_GraphicToBitmap(G343_puc_Graphic_DialogBox, G296_puc_Bitmap_Viewport, 0, 0);
#ifdef C11_COMPILE_DM10bEN /* CHANGE1_01_IMPROVEMENT Engine version 1.0 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V1.0");
#endif
#ifdef C13_COMPILE_DM11EN /* CHANGE2_18_IMPROVEMENT Engine version 1.1 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V1.1");
#endif
#ifdef C17_COMPILE_DM12EN_DM12GE /* CHANGE3_18_IMPROVEMENT Engine version 1.2 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V1.2");
#endif
#ifdef C23_COMPILE_DM13aFR_DM13bFR /* CHANGE5_04_IMPROVEMENT Engine version 1.3 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V1.3");
#endif
#ifdef C26_COMPILE_CSB20EN /* CHANGE7_36_IMPROVEMENT Engine version 2.0 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V2.0");
#endif
#ifdef C28_COMPILE_CSB21EN /* CHANGE8_13_IMPROVEMENT Engine version 2.1 printed in top right corner of dialog boxes */
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, 192, 7, C02_COLOR_LIGHT_GRAY, C01_COLOR_DARK_GRAY, "V2.1");
#endif
L1310_i_ChoiceCount = 1;
if (P838_pc_Choice2 != NULL) {
L1310_i_ChoiceCount++;
}
if (P839_pc_Choice3 != NULL) {
L1310_i_ChoiceCount++;
}
if (P840_pc_Choice4 != NULL) {
L1310_i_ChoiceCount++;
}
if (P843_B_Fading) {
#ifdef C00_COMPILE_DM10aEN /* CHANGE1_00_OPTIMIZATION */
F008_aA19_MAIN_ClearBytes(L1311_aui_Palette_Blank, sizeof(L1311_aui_Palette_Blank));
F436_xxxx_STARTEND_FadeToPalette(L1311_aui_Palette_Blank);
#endif
#ifdef C12_COMPILE_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR_CSB20EN_CSB21EN /* CHANGE1_00_OPTIMIZATION Use an existing blank global variable as a blank color palette instead of a dedicated local variable */
F436_xxxx_STARTEND_FadeToPalette(G345_aui_BlankBuffer);
#endif
}
if (P842_B_ClearScreen) {
F008_aA19_MAIN_ClearBytes(G348_pl_Bitmap_LogicalScreenBase, M75_BITMAP_BYTE_COUNT(320, 200));
}
G578_B_UseByteBoxCoordinates = FALSE;
if (L1310_i_ChoiceCount == 1) {
L1315_puc_Bitmap_DialogPatch = F468_ozzz_MEMORY_Allocate((long)M75_BITMAP_BYTE_COUNT(224, 75), C0_ALLOCATION_TEMPORARY_ON_TOP_OF_HEAP);
F132_xzzz_VIDEO_Blit(G296_puc_Bitmap_Viewport, L1315_puc_Bitmap_DialogPatch, &G467_s_Graphic561_Box_Dialog1ChoicePatchA, 0, 14, C112_BYTE_WIDTH_VIEWPORT, C112_BYTE_WIDTH_VIEWPORT, CM1_COLOR_NO_TRANSPARENCY);
F020_aAA5_MAIN_BlitToViewport(L1315_puc_Bitmap_DialogPatch, &G468_s_Graphic561_Box_Dialog1ChoicePatchB, C112_BYTE_WIDTH_VIEWPORT, CM1_COLOR_NO_TRANSPARENCY);
F469_rzzz_MEMORY_FreeAtHeapTop((long)M75_BITMAP_BYTE_COUNT(224, 75));
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P837_pc_Choice1, 112, 114);
} else {
if (L1310_i_ChoiceCount == 2) {
F132_xzzz_VIDEO_Blit(G296_puc_Bitmap_Viewport, G296_puc_Bitmap_Viewport, &G469_s_Graphic561_Box_Dialog2ChoicesPatch, 102, 52, C112_BYTE_WIDTH_VIEWPORT, C112_BYTE_WIDTH_VIEWPORT, CM1_COLOR_NO_TRANSPARENCY);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P837_pc_Choice1, 112, 77);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P838_pc_Choice2, 112, 114);
} else {
if (L1310_i_ChoiceCount == 3) {
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P837_pc_Choice1, 112, 77);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P838_pc_Choice2, 59, 114);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P839_pc_Choice3, 166, 114);
} else {
if (L1310_i_ChoiceCount == 4) {
F132_xzzz_VIDEO_Blit(G296_puc_Bitmap_Viewport, G296_puc_Bitmap_Viewport, &G470_s_Graphic561_Box_Dialog4ChoicesPatch, 102, 99, C112_BYTE_WIDTH_VIEWPORT, C112_BYTE_WIDTH_VIEWPORT, CM1_COLOR_NO_TRANSPARENCY);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P837_pc_Choice1, 59, 77);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P838_pc_Choice2, 166, 77);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P839_pc_Choice3, 59, 114);
F425_xxxx_DIALOG_PrintCenteredChoice(G296_puc_Bitmap_Viewport, P840_pc_Choice4, 166, 114);
}
}
}
}
L1309_i_Y = 29;
if (P835_pc_Message1 != NULL) {
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT */
if (F426_xxxx_DIALOG_IsMessageOnTwoLines(P835_pc_Message1, L1312_ac_StringPart1, L1313_ac_StringPart2)) {
L1309_i_Y = 21;
L1308_i_X = 113 - ((strlen(L1312_ac_StringPart1) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C11_COLOR_YELLOW, C05_COLOR_LIGHT_BROWN, L1312_ac_StringPart1);
L1309_i_Y += 8;
L1308_i_X = 113 - ((strlen(L1313_ac_StringPart2) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C11_COLOR_YELLOW, C05_COLOR_LIGHT_BROWN, L1313_ac_StringPart2);
L1309_i_Y += 8;
} else {
#endif
L1308_i_X = 113 - ((strlen(P835_pc_Message1) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C11_COLOR_YELLOW, C05_COLOR_LIGHT_BROWN, P835_pc_Message1);
L1309_i_Y += 8;
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT */
}
#endif
}
if (P836_pc_Message2 != NULL) {
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT */
if (F426_xxxx_DIALOG_IsMessageOnTwoLines(P836_pc_Message2, L1312_ac_StringPart1, L1313_ac_StringPart2)) {
L1308_i_X = 113 - ((strlen(L1312_ac_StringPart1) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C09_COLOR_GOLD, C05_COLOR_LIGHT_BROWN, L1312_ac_StringPart1);
L1309_i_Y += 8;
L1308_i_X = 113 - ((strlen(L1313_ac_StringPart2) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C09_COLOR_GOLD, C05_COLOR_LIGHT_BROWN, L1313_ac_StringPart2);
} else {
#endif
L1308_i_X = 113 - ((strlen(P836_pc_Message2) * 6) >> 1);
F040_aacZ_TEXT_Print(G296_puc_Bitmap_Viewport, C112_BYTE_WIDTH_VIEWPORT, L1308_i_X, L1309_i_Y, C09_COLOR_GOLD, C05_COLOR_LIGHT_BROWN, P836_pc_Message2);
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_35_IMPROVEMENT */
}
#endif
}
if (P841_B_ScreenDialog) {
L1314_s_Box.Y1 = 33;
L1314_s_Box.Y2 = 168;
L1314_s_Box.X1 = 47;
L1314_s_Box.X2 = 270;
F077_aA39_MOUSE_HidePointer_COPYPROTECTIONE();
F021_a002_MAIN_BlitToScreen(G296_puc_Bitmap_Viewport, &L1314_s_Box, C112_BYTE_WIDTH_VIEWPORT, CM1_COLOR_NO_TRANSPARENCY);
F078_xzzz_MOUSE_ShowPointer();
} else {
F097_lzzz_DUNGEONVIEW_DrawViewport(C0_VIEWPORT_NOT_DUNGEON_VIEW);
Vsync();
}
if (P843_B_Fading) {
F436_xxxx_STARTEND_FadeToPalette(G347_aui_Palette_TopAndBottomScreen);
}
G297_B_DrawFloorAndCeilingRequested = TRUE;
}
BOOLEAN F428_AA39_DIALOG_RequireGameDiskInDrive_NoDialogDrawn(P844_B_ForceDialog, P845_B_ModalDialog)
register BOOLEAN P844_B_ForceDialog; /* If P844_B_ForceDialog = C2_FORCE_DIALOG_CSB then F452_xxxx_FLOPPY_GetDiskTypeInDrive_COPYPROTECTIONB is called twice */
register BOOLEAN P845_B_ModalDialog;
{
register BOOLEAN L1316_B_NoDialogDrawn;
#ifdef C06_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR /* CHANGE7_34_OPTIMIZATION */
register BOOLEAN L1317_B_MousePointerNotVisible;
#endif
register char* L1318_pc_Message;
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_03_IMPROVEMENT Support for two floppy disk drives */
char L1319_ac_String[80];
#endif
L1316_B_NoDialogDrawn = TRUE;
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_03_IMPROVEMENT Support for two floppy disk drives */
if (!F452_xxxx_FLOPPY_GetDiskTypeInDrive_COPYPROTECTIONB(C1_DRIVE_TYPE_GAME_DISK) && (P844_B_ForceDialog != C2_FORCE_DIALOG_CSB)) {
return L1316_B_NoDialogDrawn;
}
#endif
L1318_pc_Message = NULL;
#ifdef C06_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR /* CHANGE7_03_IMPROVEMENT */
while (P844_B_ForceDialog || F452_xxxx_FLOPPY_GetDiskTypeInDrive_COPYPROTECTIONB()) {
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_03_IMPROVEMENT Support for two floppy disk drives */
F414_xxxx_SAVEUTIL_ReplaceTildeByDriveLetterInString(L1319_ac_String, G549_pc_D097_PUTTHEGAMEDISKIN, C1_DRIVE_TYPE_GAME_DISK);
while (P844_B_ForceDialog || F452_xxxx_FLOPPY_GetDiskTypeInDrive_COPYPROTECTIONB(C1_DRIVE_TYPE_GAME_DISK)) {
#endif
L1316_B_NoDialogDrawn = P844_B_ForceDialog = FALSE;
#ifdef C06_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR /* CHANGE7_03_IMPROVEMENT */
F427_xxxx_DIALOG_Draw(L1318_pc_Message, G549_pc_D097_PUTTHEGAMEDISKIN, G560_pc_D108_OK, NULL, NULL, NULL, P845_B_ModalDialog, P845_B_ModalDialog, P845_B_ModalDialog);
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_03_IMPROVEMENT Support for two floppy disk drives */
F427_xxxx_DIALOG_Draw(L1318_pc_Message, L1319_ac_String, G560_pc_D108_OK, NULL, NULL, NULL, P845_B_ModalDialog, P845_B_ModalDialog, P845_B_ModalDialog);
#endif
#ifdef C06_COMPILE_DM10aEN_DM10bEN_DM11EN_DM12EN_DM12GE_DM13aFR_DM13bFR /* CHANGE7_34_OPTIMIZATION */
if (L1317_B_MousePointerNotVisible = !(G587_i_HideMousePointerRequestCount <= 0)) {
F078_xzzz_MOUSE_ShowPointer();
}
F424_xxxx_DIALOG_GetChoice(C1_ONE_CHOICE, P845_B_ModalDialog);
if (L1317_B_MousePointerNotVisible) {
F077_aA39_MOUSE_HidePointer_COPYPROTECTIONE();
}
#endif
#ifdef C27_COMPILE_CSB20EN_CSB21EN /* CHANGE7_34_OPTIMIZATION */
F424_xxxx_DIALOG_GetChoice(C1_ONE_CHOICE, P845_B_ModalDialog, C1_USELESS, C1_USELESS);
#endif
L1318_pc_Message = G538_pc_D086_THATSNOTTHEMASTERDISK;
}
return L1316_B_NoDialogDrawn;
}
| 412 | 0.893522 | 1 | 0.893522 | game-dev | MEDIA | 0.901269 | game-dev | 0.800834 | 1 | 0.800834 |
maraakate/q2dos | 24,851 | game/g_weapon.c | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "g_local.h"
/*
* This is a support routine used when a client is firing
* a non-instant attack weapon. It checks to see if a
* monster's dodge function should be called.
*/
void
check_dodge(edict_t *self, vec3_t start, vec3_t dir, int speed)
{
vec3_t end;
vec3_t v;
trace_t tr;
float eta;
if (!self)
{
return;
}
/* easy mode only ducks one quarter the time */
if (skill->value == 0)
{
if (random() > 0.25)
{
return;
}
}
VectorMA(start, 8192, dir, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SHOT);
if ((tr.ent) && (tr.ent->svflags & SVF_MONSTER) && (tr.ent->health > 0) &&
(tr.ent->monsterinfo.dodge) && infront(tr.ent, self))
{
VectorSubtract(tr.endpos, start, v);
eta = (VectorLength(v) - tr.ent->maxs[0]) / speed;
tr.ent->monsterinfo.dodge(tr.ent, self, eta);
}
}
/*
* Used for all impact (hit/punch/slash) attacks
*/
qboolean
fire_hit(edict_t *self, vec3_t aim, int damage, int kick)
{
trace_t tr;
vec3_t forward, right, up;
vec3_t v;
vec3_t point;
float range;
vec3_t dir;
if (!self || !self->enemy)
{
return false;
}
/* see if enemy is in range */
VectorSubtract(self->enemy->s.origin, self->s.origin, dir);
range = VectorLength(dir);
if (range > aim[0])
{
return false;
}
if ((aim[1] > self->mins[0]) && (aim[1] < self->maxs[0]))
{
/* the hit is straight on so back the
range up to the edge of their bbox */
range -= self->enemy->maxs[0];
}
else
{
/* this is a side hit so adjust the "right"
value out to the edge of their bbox */
if (aim[1] < 0)
{
aim[1] = self->enemy->mins[0];
}
else
{
aim[1] = self->enemy->maxs[0];
}
}
VectorMA(self->s.origin, range, dir, point);
tr = gi.trace(self->s.origin, NULL, NULL, point, self, MASK_SHOT);
if (tr.fraction < 1)
{
if (!tr.ent->takedamage)
{
return false;
}
/* if it will hit any client/monster
then hit the one we wanted to hit */
if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client))
{
tr.ent = self->enemy;
}
}
AngleVectors(self->s.angles, forward, right, up);
VectorMA(self->s.origin, range, forward, point);
VectorMA(point, aim[1], right, point);
VectorMA(point, aim[2], up, point);
VectorSubtract(point, self->enemy->s.origin, dir);
/* do the damage */
T_Damage(tr.ent, self, self, dir, point, vec3_origin, damage,
kick / 2, DAMAGE_NO_KNOCKBACK, MOD_HIT);
if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client))
{
return false;
}
/* do our special form of knockback here */
VectorMA(self->enemy->absmin, 0.5, self->enemy->size, v);
VectorSubtract(v, point, v);
VectorNormalize(v);
VectorMA(self->enemy->velocity, kick, v, self->enemy->velocity);
if (self->enemy->velocity[2] > 0)
{
self->enemy->groundentity = NULL;
}
return true;
}
/*
* This is an internal support routine
* used for bullet/pellet based weapons.
*/
void
fire_lead(edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick,
int te_impact, int hspread, int vspread, int mod)
{
trace_t tr;
vec3_t dir;
vec3_t forward, right, up;
vec3_t end;
float r;
float u;
vec3_t water_start;
qboolean water = false;
int content_mask = MASK_SHOT | MASK_WATER;
if (!self)
{
return;
}
tr = gi.trace(self->s.origin, NULL, NULL, start, self, MASK_SHOT);
if (!(tr.fraction < 1.0))
{
vectoangles(aimdir, dir);
AngleVectors(dir, forward, right, up);
r = crandom() * hspread;
u = crandom() * vspread;
VectorMA(start, 8192, forward, end);
VectorMA(end, r, right, end);
VectorMA(end, u, up, end);
if (gi.pointcontents(start) & MASK_WATER)
{
water = true;
VectorCopy(start, water_start);
content_mask &= ~MASK_WATER;
}
tr = gi.trace(start, NULL, NULL, end, self, content_mask);
/* see if we hit water */
if (tr.contents & MASK_WATER)
{
int color;
water = true;
VectorCopy(tr.endpos, water_start);
if (!VectorCompare(start, tr.endpos))
{
if (tr.contents & CONTENTS_WATER)
{
if (strcmp(tr.surface->name, "*brwater") == 0)
{
color = SPLASH_BROWN_WATER;
}
else
{
color = SPLASH_BLUE_WATER;
}
}
else if (tr.contents & CONTENTS_SLIME)
{
color = SPLASH_SLIME;
}
else if (tr.contents & CONTENTS_LAVA)
{
color = SPLASH_LAVA;
}
else
{
color = SPLASH_UNKNOWN;
}
if (color != SPLASH_UNKNOWN)
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_SPLASH);
gi.WriteByte(8);
gi.WritePosition(tr.endpos);
gi.WriteDir(tr.plane.normal);
gi.WriteByte(color);
gi.multicast(tr.endpos, MULTICAST_PVS);
}
/* change bullet's course when it enters water */
VectorSubtract(end, start, dir);
vectoangles(dir, dir);
AngleVectors(dir, forward, right, up);
r = crandom() * hspread * 2;
u = crandom() * vspread * 2;
VectorMA(water_start, 8192, forward, end);
VectorMA(end, r, right, end);
VectorMA(end, u, up, end);
}
/* re-trace ignoring water this time */
tr = gi.trace(water_start, NULL, NULL, end, self, MASK_SHOT);
}
}
/* send gun puff / flash */
if (!((tr.surface) && (tr.surface->flags & SURF_SKY)))
{
if (tr.fraction < 1.0)
{
if (tr.ent->takedamage)
{
T_Damage(tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal,
damage, kick, DAMAGE_BULLET, mod);
}
else
{
if (strncmp(tr.surface->name, "sky", 3) != 0)
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(te_impact);
gi.WritePosition(tr.endpos);
gi.WriteDir(tr.plane.normal);
gi.multicast(tr.endpos, MULTICAST_PVS);
if (self->client)
{
PlayerNoise(self, tr.endpos, PNOISE_IMPACT);
}
}
}
}
}
/* if went through water, determine
where the end and make a bubble trail */
if (water)
{
vec3_t pos;
VectorSubtract(tr.endpos, water_start, dir);
VectorNormalize(dir);
VectorMA(tr.endpos, -2, dir, pos);
if (gi.pointcontents(pos) & MASK_WATER)
{
VectorCopy(pos, tr.endpos);
}
else
{
tr = gi.trace(pos, NULL, NULL, water_start, tr.ent, MASK_WATER);
}
VectorAdd(water_start, tr.endpos, pos);
VectorScale(pos, 0.5, pos);
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_BUBBLETRAIL);
gi.WritePosition(water_start);
gi.WritePosition(tr.endpos);
gi.multicast(pos, MULTICAST_PVS);
}
}
/*
* Fires a single round. Used for machinegun and
* chaingun. Would be fine for pistols, rifles, etc....
*/
void
fire_bullet(edict_t *self, vec3_t start, vec3_t aimdir, int damage,
int kick, int hspread, int vspread, int mod)
{
if (!self)
{
return;
}
fire_lead(self, start, aimdir, damage, kick, TE_GUNSHOT, hspread,
vspread, mod);
}
/*
* Shoots shotgun pellets. Used
* by shotgun and super shotgun.
*/
void
fire_shotgun(edict_t *self, vec3_t start, vec3_t aimdir, int damage,
int kick, int hspread, int vspread, int count, int mod)
{
int i;
if (!self)
{
return;
}
for (i = 0; i < count; i++)
{
fire_lead(self, start, aimdir, damage, kick, TE_SHOTGUN,
hspread, vspread, mod);
}
}
/*
* Fires a single blaster bolt.
* Used by the blaster and hyper blaster.
*/
void
blaster_touch(edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
int mod;
if (!self || !other) /* plane and surf can be NULL */
{
G_FreeEdict(self);
return;
}
if (other == self->owner)
{
return;
}
if (surf && (surf->flags & SURF_SKY))
{
G_FreeEdict(self);
return;
}
if (self->owner && self->owner->client)
{
PlayerNoise(self->owner, self->s.origin, PNOISE_IMPACT);
}
if (other->takedamage)
{
if (self->spawnflags & 1)
{
mod = MOD_HYPERBLASTER;
}
else
{
mod = MOD_BLASTER;
}
if (plane)
{
T_Damage(other, self, self->owner, self->velocity, self->s.origin,
plane->normal, self->dmg, 1, DAMAGE_ENERGY, mod);
}
else
{
T_Damage(other, self, self->owner, self->velocity, self->s.origin,
vec3_origin, self->dmg, 1, DAMAGE_ENERGY, mod);
}
}
else
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_BLASTER);
gi.WritePosition(self->s.origin);
if (!plane)
{
gi.WriteDir(vec3_origin);
}
else
{
gi.WriteDir(plane->normal);
}
gi.multicast(self->s.origin, MULTICAST_PVS);
}
G_FreeEdict(self);
}
void
fire_blaster(edict_t *self, vec3_t start, vec3_t dir, int damage,
int speed, int effect, qboolean hyper)
{
edict_t *bolt;
trace_t tr;
if (!self)
{
return;
}
VectorNormalize(dir);
bolt = G_Spawn();
bolt->svflags = SVF_DEADMONSTER;
/* yes, I know it looks weird that projectiles are deadmonsters
what this means is that when prediction is used against the object
(blaster/hyperblaster shots), the player won't be solid clipped against
the object. Right now trying to run into a firing hyperblaster
is very jerky since you are predicted 'against' the shots. */
VectorCopy(start, bolt->s.origin);
VectorCopy(start, bolt->s.old_origin);
vectoangles(dir, bolt->s.angles);
VectorScale(dir, speed, bolt->velocity);
bolt->movetype = MOVETYPE_FLYMISSILE;
bolt->clipmask = MASK_SHOT;
bolt->solid = SOLID_BBOX;
bolt->s.effects |= effect;
VectorClear(bolt->mins);
VectorClear(bolt->maxs);
bolt->s.modelindex = gi.modelindex("models/objects/laser/tris.md2");
bolt->s.sound = gi.soundindex("misc/lasfly.wav");
bolt->owner = self;
bolt->touch = blaster_touch;
bolt->nextthink = level.time + 2;
bolt->think = G_FreeEdict;
bolt->dmg = damage;
bolt->classname = "bolt";
if (hyper)
{
bolt->spawnflags = 1;
}
gi.linkentity(bolt);
if (self->client)
{
check_dodge(self, bolt->s.origin, dir, speed);
}
tr = gi.trace(self->s.origin, NULL, NULL, bolt->s.origin, bolt, MASK_SHOT);
if (tr.fraction < 1.0)
{
VectorMA(bolt->s.origin, -10, dir, bolt->s.origin);
bolt->touch(bolt, tr.ent, NULL, NULL);
}
}
void
Grenade_Explode(edict_t *ent)
{
vec3_t origin;
int mod;
if (!ent)
{
return;
}
if (ent->owner && ent->owner->client)
{
PlayerNoise(ent->owner, ent->s.origin, PNOISE_IMPACT);
}
if (ent->enemy)
{
float points;
vec3_t v;
vec3_t dir;
VectorAdd(ent->enemy->mins, ent->enemy->maxs, v);
VectorMA(ent->enemy->s.origin, 0.5, v, v);
VectorSubtract(ent->s.origin, v, v);
points = ent->dmg - 0.5 * VectorLength(v);
VectorSubtract(ent->enemy->s.origin, ent->s.origin, dir);
if (ent->spawnflags & 1)
{
mod = MOD_HANDGRENADE;
}
else
{
mod = MOD_GRENADE;
}
T_Damage(ent->enemy, ent, ent->owner, dir, ent->s.origin, vec3_origin,
(int)points, (int)points, DAMAGE_RADIUS, mod);
}
if (ent->spawnflags & 2)
{
mod = MOD_HELD_GRENADE;
}
else if (ent->spawnflags & 1)
{
mod = MOD_HG_SPLASH;
}
else
{
mod = MOD_G_SPLASH;
}
T_RadiusDamage(ent, ent->owner, ent->dmg, ent->enemy, ent->dmg_radius, mod);
VectorMA(ent->s.origin, -0.02, ent->velocity, origin);
gi.WriteByte(svc_temp_entity);
if (ent->waterlevel)
{
if (ent->groundentity)
{
gi.WriteByte(TE_GRENADE_EXPLOSION_WATER);
}
else
{
gi.WriteByte(TE_ROCKET_EXPLOSION_WATER);
}
}
else
{
if (ent->groundentity)
{
gi.WriteByte(TE_GRENADE_EXPLOSION);
}
else
{
gi.WriteByte(TE_ROCKET_EXPLOSION);
}
}
gi.WritePosition(origin);
gi.multicast(ent->s.origin, MULTICAST_PHS);
G_FreeEdict(ent);
}
void
Grenade_Touch(edict_t *ent, edict_t *other, cplane_t *plane /* unused */, csurface_t *surf)
{
if (!ent || !other) /* plane is unused, surf can be NULL */
{
G_FreeEdict(ent);
return;
}
if (other == ent->owner)
{
return;
}
if (surf && (surf->flags & SURF_SKY))
{
G_FreeEdict(ent);
return;
}
if (!other->takedamage)
{
if (ent->spawnflags & 1)
{
if (random() > 0.5)
{
gi.sound(ent, CHAN_VOICE, gi.soundindex(
"weapons/hgrenb1a.wav"), 1, ATTN_NORM, 0);
}
else
{
gi.sound(ent, CHAN_VOICE, gi.soundindex(
"weapons/hgrenb2a.wav"), 1, ATTN_NORM, 0);
}
}
else
{
gi.sound(ent, CHAN_VOICE, gi.soundindex(
"weapons/grenlb1b.wav"), 1, ATTN_NORM, 0);
}
return;
}
ent->enemy = other;
Grenade_Explode(ent);
}
void
fire_grenade(edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed,
float timer, float damage_radius)
{
edict_t *grenade;
vec3_t dir;
vec3_t forward, right, up;
if (!self)
{
return;
}
vectoangles(aimdir, dir);
AngleVectors(dir, forward, right, up);
grenade = G_Spawn();
VectorCopy(start, grenade->s.origin);
VectorScale(aimdir, speed, grenade->velocity);
VectorMA(grenade->velocity, 200 + crandom() * 10.0, up, grenade->velocity);
VectorMA(grenade->velocity, crandom() * 10.0, right, grenade->velocity);
VectorSet(grenade->avelocity, 300, 300, 300);
grenade->movetype = MOVETYPE_BOUNCE;
grenade->clipmask = MASK_SHOT;
grenade->solid = SOLID_BBOX;
grenade->s.effects |= EF_GRENADE;
VectorClear(grenade->mins);
VectorClear(grenade->maxs);
grenade->s.modelindex = gi.modelindex("models/objects/grenade/tris.md2");
grenade->owner = self;
grenade->touch = Grenade_Touch;
grenade->nextthink = level.time + timer;
grenade->think = Grenade_Explode;
grenade->dmg = damage;
grenade->dmg_radius = damage_radius;
grenade->classname = "grenade";
gi.linkentity(grenade);
}
void
fire_grenade2(edict_t *self, vec3_t start, vec3_t aimdir, int damage,
int speed, float timer, float damage_radius, qboolean held)
{
edict_t *grenade;
vec3_t dir;
vec3_t forward, right, up;
if (!self)
{
return;
}
vectoangles(aimdir, dir);
AngleVectors(dir, forward, right, up);
grenade = G_Spawn();
VectorCopy(start, grenade->s.origin);
VectorScale(aimdir, speed, grenade->velocity);
VectorMA(grenade->velocity, 200 + crandom() * 10.0, up, grenade->velocity);
VectorMA(grenade->velocity, crandom() * 10.0, right, grenade->velocity);
VectorSet(grenade->avelocity, 300, 300, 300);
grenade->movetype = MOVETYPE_BOUNCE;
grenade->clipmask = MASK_SHOT;
grenade->solid = SOLID_BBOX;
grenade->s.effects |= EF_GRENADE;
VectorClear(grenade->mins);
VectorClear(grenade->maxs);
grenade->s.modelindex = gi.modelindex("models/objects/grenade2/tris.md2");
grenade->owner = self;
grenade->touch = Grenade_Touch;
grenade->nextthink = level.time + timer;
grenade->think = Grenade_Explode;
grenade->dmg = damage;
grenade->dmg_radius = damage_radius;
grenade->classname = "hgrenade";
if (held)
{
grenade->spawnflags = 3;
}
else
{
grenade->spawnflags = 1;
}
grenade->s.sound = gi.soundindex("weapons/hgrenc1b.wav");
if (timer <= 0.0)
{
Grenade_Explode(grenade);
}
else
{
gi.sound(self, CHAN_WEAPON, gi.soundindex(
"weapons/hgrent1a.wav"), 1, ATTN_NORM, 0);
gi.linkentity(grenade);
}
}
void
rocket_touch(edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
{
vec3_t origin;
int n;
if (!ent || !other) /* plane and surf can be NULL */
{
G_FreeEdict(ent);
return;
}
if (other == ent->owner)
{
return;
}
if (surf && (surf->flags & SURF_SKY))
{
G_FreeEdict(ent);
return;
}
if (ent->owner && ent->owner->client)
{
PlayerNoise(ent->owner, ent->s.origin, PNOISE_IMPACT);
}
/* calculate position for the explosion entity */
VectorMA(ent->s.origin, -0.02, ent->velocity, origin);
if (other->takedamage)
{
if (plane)
{
T_Damage(other, ent, ent->owner, ent->velocity, ent->s.origin,
plane->normal, ent->dmg, 0, 0, MOD_ROCKET);
}
else
{
T_Damage(other, ent, ent->owner, ent->velocity, ent->s.origin,
vec3_origin, ent->dmg, 0, 0, MOD_ROCKET);
}
}
else
{
/* don't throw any debris in net games */
if (!deathmatch->value && !coop->value)
{
if ((surf) && !(surf->flags &
(SURF_WARP | SURF_TRANS33 | SURF_TRANS66 | SURF_FLOWING)))
{
n = rand() % 5;
while (n--)
{
ThrowDebris(ent, "models/objects/debris2/tris.md2",
2, ent->s.origin);
}
}
}
}
T_RadiusDamage(ent, ent->owner, ent->radius_dmg, other, ent->dmg_radius,
MOD_R_SPLASH);
gi.WriteByte(svc_temp_entity);
if (ent->waterlevel)
{
gi.WriteByte(TE_ROCKET_EXPLOSION_WATER);
}
else
{
gi.WriteByte(TE_ROCKET_EXPLOSION);
}
gi.WritePosition(origin);
gi.multicast(ent->s.origin, MULTICAST_PHS);
G_FreeEdict(ent);
}
void
fire_rocket(edict_t *self, vec3_t start, vec3_t dir, int damage,
int speed, float damage_radius, int radius_damage)
{
edict_t *rocket;
if (!self)
{
return;
}
rocket = G_Spawn();
VectorCopy(start, rocket->s.origin);
VectorCopy(dir, rocket->movedir);
vectoangles(dir, rocket->s.angles);
VectorScale(dir, speed, rocket->velocity);
rocket->movetype = MOVETYPE_FLYMISSILE;
rocket->clipmask = MASK_SHOT;
rocket->solid = SOLID_BBOX;
rocket->s.effects |= EF_ROCKET;
VectorClear(rocket->mins);
VectorClear(rocket->maxs);
rocket->s.modelindex = gi.modelindex("models/objects/rocket/tris.md2");
rocket->owner = self;
rocket->touch = rocket_touch;
rocket->nextthink = level.time + 8000 / speed;
rocket->think = G_FreeEdict;
rocket->dmg = damage;
rocket->radius_dmg = radius_damage;
rocket->dmg_radius = damage_radius;
rocket->s.sound = gi.soundindex("weapons/rockfly.wav");
rocket->classname = "rocket";
if (self->client)
{
check_dodge(self, rocket->s.origin, dir, speed);
}
gi.linkentity(rocket);
}
void
fire_rail(edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick)
{
vec3_t from;
vec3_t end;
trace_t tr;
edict_t *ignore;
int mask;
qboolean water;
if (!self)
{
return;
}
VectorMA(start, 8192, aimdir, end);
VectorCopy(start, from);
ignore = self;
water = false;
mask = MASK_SHOT | CONTENTS_SLIME | CONTENTS_LAVA;
while (ignore)
{
tr = gi.trace(from, NULL, NULL, end, ignore, mask);
if (tr.contents & (CONTENTS_SLIME | CONTENTS_LAVA))
{
mask &= ~(CONTENTS_SLIME | CONTENTS_LAVA);
water = true;
}
else
{
if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client) ||
(tr.ent->solid == SOLID_BBOX))
{
ignore = tr.ent;
}
else
{
ignore = NULL;
}
if ((tr.ent != self) && (tr.ent->takedamage))
{
T_Damage(tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal,
damage, kick, 0, MOD_RAILGUN);
}
else
{
ignore = NULL;
}
}
VectorCopy(tr.endpos, from);
}
/* send gun puff / flash */
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_RAILTRAIL);
gi.WritePosition(start);
gi.WritePosition(tr.endpos);
gi.multicast(self->s.origin, MULTICAST_PHS);
if (water)
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_RAILTRAIL);
gi.WritePosition(start);
gi.WritePosition(tr.endpos);
gi.multicast(tr.endpos, MULTICAST_PHS);
}
if (self->client)
{
PlayerNoise(self, tr.endpos, PNOISE_IMPACT);
}
}
void
bfg_explode(edict_t *self)
{
edict_t *ent;
float points;
vec3_t v;
float dist;
if (!self)
{
return;
}
if (self->s.frame == 0)
{
/* the BFG effect */
ent = NULL;
while ((ent = findradius(ent, self->s.origin, self->dmg_radius)) != NULL)
{
if (!ent->takedamage)
{
continue;
}
if (ent == self->owner)
{
continue;
}
if (!CanDamage(ent, self))
{
continue;
}
if (!CanDamage(ent, self->owner))
{
continue;
}
VectorAdd(ent->mins, ent->maxs, v);
VectorMA(ent->s.origin, 0.5, v, v);
VectorSubtract(self->s.origin, v, v);
dist = VectorLength(v);
points = self->radius_dmg * (1.0 - sqrt(dist / self->dmg_radius));
if (ent == self->owner)
{
points = points * 0.5;
}
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_BFG_EXPLOSION);
gi.WritePosition(ent->s.origin);
gi.multicast(ent->s.origin, MULTICAST_PHS);
T_Damage(ent, self, self->owner, self->velocity, ent->s.origin, vec3_origin,
(int)points, 0, DAMAGE_ENERGY, MOD_BFG_EFFECT);
}
}
self->nextthink = level.time + FRAMETIME;
self->s.frame++;
if (self->s.frame == 5)
{
self->think = G_FreeEdict;
}
}
void
bfg_touch(edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
if (!self || !other) /* plane and surf can be NULL */
{
G_FreeEdict(self);
return;
}
if (other == self->owner)
{
return;
}
if (surf && (surf->flags & SURF_SKY))
{
G_FreeEdict(self);
return;
}
if (self->owner && self->owner->client)
{
PlayerNoise(self->owner, self->s.origin, PNOISE_IMPACT);
}
/* core explosion - prevents firing it into the wall/floor */
if (other->takedamage)
{
if (plane)
{
T_Damage(other, self, self->owner, self->velocity, self->s.origin,
plane->normal, 200, 0, 0, MOD_BFG_BLAST);
}
else
{
T_Damage(other, self, self->owner, self->velocity, self->s.origin,
vec3_origin, 200, 0, 0, MOD_BFG_BLAST);
}
}
T_RadiusDamage(self, self->owner, 200, other, 100, MOD_BFG_BLAST);
gi.sound(self, CHAN_VOICE, gi.soundindex(
"weapons/bfg__x1b.wav"), 1, ATTN_NORM, 0);
self->solid = SOLID_NOT;
self->touch = NULL;
VectorMA(self->s.origin, -1 * FRAMETIME, self->velocity, self->s.origin);
VectorClear(self->velocity);
self->s.modelindex = gi.modelindex("sprites/s_bfg3.sp2");
self->s.frame = 0;
self->s.sound = 0;
self->s.effects &= ~EF_ANIM_ALLFAST;
self->think = bfg_explode;
self->nextthink = level.time + FRAMETIME;
self->enemy = other;
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_BFG_BIGEXPLOSION);
gi.WritePosition(self->s.origin);
gi.multicast(self->s.origin, MULTICAST_PVS);
}
void
bfg_think(edict_t *self)
{
edict_t *ent;
edict_t *ignore;
vec3_t point;
vec3_t dir;
vec3_t start;
vec3_t end;
int dmg;
trace_t tr;
if (!self)
{
return;
}
if (deathmatch->value)
{
dmg = 5;
}
else
{
dmg = 10;
}
ent = NULL;
while ((ent = findradius(ent, self->s.origin, 256)) != NULL)
{
if (ent == self)
{
continue;
}
if (ent == self->owner)
{
continue;
}
if (!ent->takedamage)
{
continue;
}
if (!(ent->svflags & SVF_MONSTER) && (!ent->client) &&
(strcmp(ent->classname, "misc_explobox") != 0))
{
continue;
}
VectorMA(ent->absmin, 0.5, ent->size, point);
VectorSubtract(point, self->s.origin, dir);
VectorNormalize(dir);
ignore = self;
VectorCopy(self->s.origin, start);
VectorMA(start, 2048, dir, end);
while (1)
{
tr = gi.trace(start, NULL, NULL, end, ignore,
CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER);
if (!tr.ent)
{
break;
}
/* hurt it if we can */
if ((tr.ent->takedamage) && !(tr.ent->flags & FL_IMMUNE_LASER) &&
(tr.ent != self->owner))
{
T_Damage(tr.ent, self, self->owner, dir, tr.endpos, vec3_origin,
dmg, 1, DAMAGE_ENERGY, MOD_BFG_LASER);
}
/* if we hit something that's not a monster or player we're done */
if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client))
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_LASER_SPARKS);
gi.WriteByte(4);
gi.WritePosition(tr.endpos);
gi.WriteDir(tr.plane.normal);
gi.WriteByte(self->s.skinnum);
gi.multicast(tr.endpos, MULTICAST_PVS);
break;
}
ignore = tr.ent;
VectorCopy(tr.endpos, start);
}
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_BFG_LASER);
gi.WritePosition(self->s.origin);
gi.WritePosition(tr.endpos);
gi.multicast(self->s.origin, MULTICAST_PHS);
}
self->nextthink = level.time + FRAMETIME;
}
void
fire_bfg(edict_t *self, vec3_t start, vec3_t dir, int damage,
int speed, float damage_radius)
{
edict_t *bfg;
if (!self)
{
return;
}
bfg = G_Spawn();
VectorCopy(start, bfg->s.origin);
VectorCopy(dir, bfg->movedir);
vectoangles(dir, bfg->s.angles);
VectorScale(dir, speed, bfg->velocity);
bfg->movetype = MOVETYPE_FLYMISSILE;
bfg->clipmask = MASK_SHOT;
bfg->solid = SOLID_BBOX;
bfg->s.effects |= EF_BFG | EF_ANIM_ALLFAST;
VectorClear(bfg->mins);
VectorClear(bfg->maxs);
bfg->s.modelindex = gi.modelindex("sprites/s_bfg1.sp2");
bfg->owner = self;
bfg->touch = bfg_touch;
bfg->nextthink = level.time + 8000 / speed;
bfg->think = G_FreeEdict;
bfg->radius_dmg = damage;
bfg->dmg_radius = damage_radius;
bfg->classname = "bfg blast";
bfg->s.sound = gi.soundindex("weapons/bfg__l1a.wav");
bfg->think = bfg_think;
bfg->nextthink = level.time + FRAMETIME;
bfg->teammaster = bfg;
bfg->teamchain = NULL;
if (self->client)
{
check_dodge(self, bfg->s.origin, dir, speed);
}
gi.linkentity(bfg);
}
| 412 | 0.933163 | 1 | 0.933163 | game-dev | MEDIA | 0.988986 | game-dev | 0.99156 | 1 | 0.99156 |
Baystation12/Baystation12 | 8,801 | code/modules/mob/living/carbon/human/human_organs.dm | /mob/living/carbon/human/proc/update_eyes()
var/obj/item/organ/internal/eyes/eyes = internal_organs_by_name[species.vision_organ ? species.vision_organ : BP_EYES]
if(eyes)
eyes.update_colour()
regenerate_icons()
/mob/living/carbon/human/proc/get_bodypart_name(zone)
var/obj/item/organ/external/E = get_organ(zone)
if(E) . = E.name
/mob/living/carbon/human/proc/recheck_bad_external_organs()
var/damage_this_tick = getToxLoss()
for(var/obj/item/organ/external/O in organs)
damage_this_tick += O.burn_dam + O.brute_dam
if(damage_this_tick > last_dam)
. = TRUE
last_dam = damage_this_tick
// Takes care of organ related updates, such as broken and missing limbs
/mob/living/carbon/human/proc/handle_organs()
var/force_process = recheck_bad_external_organs()
if(force_process)
bad_external_organs.Cut()
for(var/obj/item/organ/external/Ex in organs)
bad_external_organs |= Ex
//processing internal organs is pretty cheap, do that first.
for(var/obj/item/organ/I in internal_organs)
I.Process()
handle_stance()
handle_grasp()
if(!force_process && !length(bad_external_organs))
return
for(var/obj/item/organ/external/E in bad_external_organs)
if(!E)
continue
if(!E.need_process())
bad_external_organs -= E
continue
else
E.Process()
if (!lying && !buckled && world.time - l_move_time < 15)
//Moving around with fractured ribs won't do you any good
if (prob(10) && !stat && can_feel_pain() && chem_effects[CE_PAINKILLER] < 50 && E.is_broken() && length(E.internal_organs))
custom_pain("Pain jolts through your broken [E.encased ? E.encased : E.name], staggering you!", 50, affecting = E)
unequip_item(loc)
Stun(2)
//Moving makes open wounds get infected much faster
for(var/datum/wound/W in E.wounds)
if (W.infection_check())
W.germ_level += 1
/mob/living/carbon/human/proc/Check_Proppable_Object()
for(var/turf/simulated/T in trange(1,src)) //we only care for non-space turfs
if(T.density) //walls work
return 1
for(var/obj/O in orange(1, src))
if(O && O.density && O.anchored)
return 1
return 0
/mob/living/carbon/human/proc/handle_stance()
// Don't need to process any of this if they aren't standing anyways
// unless their stance is damaged, and we want to check if they should stay down
if (!stance_damage && (lying || resting) && (life_tick % 4) != 0)
return
stance_damage = 0
// Buckled to a bed/chair. Stance damage is forced to 0 since they're sitting on something solid
if (istype(buckled, /obj/structure/bed))
return
// Can't fall if nothing pulls you down
if(!has_gravity())
return
var/limb_pain
for(var/limb_tag in list(BP_L_LEG, BP_R_LEG, BP_L_FOOT, BP_R_FOOT))
var/obj/item/organ/external/E = organs_by_name[limb_tag]
if(!E || !E.is_usable())
stance_damage += 2 // let it fail even if just foot&leg
else if (E.is_malfunctioning())
//malfunctioning only happens intermittently so treat it as a missing limb when it procs
stance_damage += 2
if(prob(10))
visible_message("\The [src]'s [E.name] [pick("twitches", "shudders")] and sparks!")
var/datum/effect/spark_spread/spark_system = new ()
spark_system.set_up(5, 0, src)
spark_system.attach(src)
spark_system.start()
spawn(10)
qdel(spark_system)
else if (E.is_broken())
stance_damage += 1
else if (E.is_dislocated())
stance_damage += 0.5
if(E) limb_pain = E.can_feel_pain()
// Canes and crutches help you stand (if the latter is ever added)
// One cane mitigates a broken leg+foot, or a missing foot.
// Two canes are needed for a lost leg. If you are missing both legs, canes aren't gonna help you.
if (l_hand && istype(l_hand, /obj/item/cane))
stance_damage -= 2
if (r_hand && istype(r_hand, /obj/item/cane))
stance_damage -= 2
if(MOVING_DELIBERATELY(src)) //you don't suffer as much if you aren't trying to run
var/working_pair = 2
if(!organs_by_name[BP_L_LEG] || !organs_by_name[BP_L_FOOT]) //are we down a limb?
working_pair -= 1
else if((!organs_by_name[BP_L_LEG].is_usable()) || (!organs_by_name[BP_L_FOOT].is_usable())) //if not, is it usable?
working_pair -= 1
if(!organs_by_name[BP_R_LEG] || !organs_by_name[BP_R_FOOT])
working_pair -= 1
else if((!organs_by_name[BP_R_LEG].is_usable()) || (!organs_by_name[BP_R_FOOT].is_usable()))
working_pair -= 1
if(working_pair >= 1)
stance_damage -= 1
if(Check_Proppable_Object()) //it helps to lean on something if you've got another leg to stand on
stance_damage -= 1
var/list/objects_to_sit_on = list(
/obj/item/stool,
/obj/structure/bed,
)
for(var/type in objects_to_sit_on) //things that can't be climbed but can be propped-up-on
if(locate(type) in src.loc)
return
// standing is poor
if(stance_damage >= 4 || (stance_damage >= 2 && prob(2)) || (stance_damage >= 3 && prob(8)))
if(!(lying || resting))
if(limb_pain)
emote("scream")
custom_emote(VISIBLE_MESSAGE, "collapses!")
Weaken(3) //can't emote while weakened, apparently.
/mob/living/carbon/human/proc/handle_grasp()
if (HandsEmpty())
return
// You should not be able to pick anything up, but stranger things have happened.
if(l_hand)
for(var/limb_tag in list(BP_L_HAND, BP_L_ARM))
var/obj/item/organ/external/E = get_organ(limb_tag)
if(!E)
visible_message(SPAN_DANGER("Lacking a functioning left hand, \the [src] drops \the [l_hand]."))
drop_from_inventory(l_hand)
break
if(r_hand)
for(var/limb_tag in list(BP_R_HAND, BP_R_ARM))
var/obj/item/organ/external/E = get_organ(limb_tag)
if(!E)
visible_message(SPAN_DANGER("Lacking a functioning right hand, \the [src] drops \the [r_hand]."))
drop_from_inventory(r_hand)
break
// Check again...
if (HandsEmpty())
return
for (var/obj/item/organ/external/E in organs)
if(!E || !(E.limb_flags & ORGAN_FLAG_CAN_GRASP))
continue
if(((E.is_broken() || E.is_dislocated()) && !E.splinted))
grasp_damage_disarm(E)
/mob/living/carbon/human/proc/stance_damage_prone(obj/item/organ/external/affected)
if(affected)
switch(affected.body_part)
if(FOOT_LEFT, FOOT_RIGHT)
if(!BP_IS_ROBOTIC(affected))
to_chat(src, SPAN_WARNING("You lose your footing as your [affected.name] spasms!"))
else
to_chat(src, SPAN_WARNING("You lose your footing as your [affected.name] [pick("twitches", "shudders")]!"))
if(LEG_LEFT, LEG_RIGHT)
if(!BP_IS_ROBOTIC(affected))
to_chat(src, SPAN_WARNING("Your [affected.name] buckles from the shock!"))
else
to_chat(src, SPAN_WARNING("You lose your balance as [affected.name] [pick("malfunctions", "freezes","shudders")]!"))
else
return
Weaken(4)
/mob/living/carbon/human/proc/grasp_damage_disarm(obj/item/organ/external/affected)
var/disarm_slot
switch(affected.body_part)
if(HAND_LEFT, ARM_LEFT)
disarm_slot = slot_l_hand
if(HAND_RIGHT, ARM_RIGHT)
disarm_slot = slot_r_hand
if(!disarm_slot)
return
var/obj/item/thing = get_equipped_item(disarm_slot)
if(!thing)
return
if(!unEquip(thing))
return
if(BP_IS_ROBOTIC(affected))
var/datum/pronouns/pronouns = choose_from_pronouns()
visible_message("<B>\The [src]</B> drops what they were holding, [pronouns.his] [affected.name] malfunctioning!")
var/datum/effect/spark_spread/spark_system = new /datum/effect/spark_spread()
spark_system.set_up(5, 0, src)
spark_system.attach(src)
spark_system.start()
spawn(10)
qdel(spark_system)
else
var/grasp_name = affected.name
if((affected.body_part in list(ARM_LEFT, ARM_RIGHT)) && length(affected.children))
var/obj/item/organ/external/hand = pick(affected.children)
grasp_name = hand.name
if(affected.can_feel_pain())
var/emote_scream = pick("screams in pain", "lets out a sharp cry", "cries out")
var/emote_scream_alt = pick("scream in pain", "let out a sharp cry", "cry out")
visible_message(
"<B>\The [src]</B> [emote_scream] and drops what they were holding in their [grasp_name]!",
null,
"You hear someone [emote_scream_alt]!"
)
custom_pain("The sharp pain in your [affected.name] forces you to drop [thing]!", 30)
else
visible_message("<B>\The [src]</B> drops what they were holding in their [grasp_name]!")
/mob/living/carbon/human/proc/sync_organ_dna()
var/list/all_bits = internal_organs|organs
for(var/obj/item/organ/O in all_bits)
O.set_dna(dna)
/mob/living/proc/is_asystole()
return FALSE
/mob/living/carbon/human/is_asystole()
if(isSynthetic())
var/obj/item/organ/internal/cell/C = internal_organs_by_name[BP_CELL]
if(istype(C))
if(!C.is_usable() || !C.percent())
return TRUE
else if(should_have_organ(BP_HEART))
var/obj/item/organ/internal/heart/heart = internal_organs_by_name[BP_HEART]
if(!istype(heart) || !heart.is_working())
return TRUE
return FALSE
| 412 | 0.974986 | 1 | 0.974986 | game-dev | MEDIA | 0.989126 | game-dev | 0.931268 | 1 | 0.931268 |
hhmy27/UnityGame-CardWar | 1,399 | Assets/cardwar/Behavior Designer/Runtime/Basic Tasks/Transform/GetUpVector.cs | using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityTransform
{
[TaskCategory("Basic/Transform")]
[TaskDescription("Stores the up vector of the Transform. Returns Success.")]
public class GetUpVector : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
[Tooltip("The position of the Transform")]
[RequiredField]
public SharedVector3 storeValue;
private Transform targetTransform;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
targetTransform = currentGameObject.GetComponent<Transform>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (targetTransform == null) {
Debug.LogWarning("Transform is null");
return TaskStatus.Failure;
}
storeValue.Value = targetTransform.up;
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
storeValue = Vector3.zero;
}
}
} | 412 | 0.873712 | 1 | 0.873712 | game-dev | MEDIA | 0.944187 | game-dev | 0.896069 | 1 | 0.896069 |
gamekit-developers/gamekit | 14,250 | bullet/src/Bullet3OpenCL/RigidBody/kernels/solveFriction.h | //this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project
static const char* solveFrictionCL= \
"/*\n"
"Copyright (c) 2012 Advanced Micro Devices, Inc. \n"
"This software is provided 'as-is', without any express or implied warranty.\n"
"In no event will the authors be held liable for any damages arising from the use of this software.\n"
"Permission is granted to anyone to use this software for any purpose, \n"
"including commercial applications, and to alter it and redistribute it freely, \n"
"subject to the following restrictions:\n"
"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.\n"
"2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n"
"3. This notice may not be removed or altered from any source distribution.\n"
"*/\n"
"//Originally written by Takahiro Harada\n"
"//#pragma OPENCL EXTENSION cl_amd_printf : enable\n"
"#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable\n"
"#pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable\n"
"#pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable\n"
"#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable\n"
"#ifdef cl_ext_atomic_counters_32\n"
"#pragma OPENCL EXTENSION cl_ext_atomic_counters_32 : enable\n"
"#else\n"
"#define counter32_t volatile global int*\n"
"#endif\n"
"typedef unsigned int u32;\n"
"typedef unsigned short u16;\n"
"typedef unsigned char u8;\n"
"#define GET_GROUP_IDX get_group_id(0)\n"
"#define GET_LOCAL_IDX get_local_id(0)\n"
"#define GET_GLOBAL_IDX get_global_id(0)\n"
"#define GET_GROUP_SIZE get_local_size(0)\n"
"#define GET_NUM_GROUPS get_num_groups(0)\n"
"#define GROUP_LDS_BARRIER barrier(CLK_LOCAL_MEM_FENCE)\n"
"#define GROUP_MEM_FENCE mem_fence(CLK_LOCAL_MEM_FENCE)\n"
"#define AtomInc(x) atom_inc(&(x))\n"
"#define AtomInc1(x, out) out = atom_inc(&(x))\n"
"#define AppendInc(x, out) out = atomic_inc(x)\n"
"#define AtomAdd(x, value) atom_add(&(x), value)\n"
"#define AtomCmpxhg(x, cmp, value) atom_cmpxchg( &(x), cmp, value )\n"
"#define AtomXhg(x, value) atom_xchg ( &(x), value )\n"
"#define SELECT_UINT4( b, a, condition ) select( b,a,condition )\n"
"#define mymake_float4 (float4)\n"
"//#define make_float2 (float2)\n"
"//#define make_uint4 (uint4)\n"
"//#define make_int4 (int4)\n"
"//#define make_uint2 (uint2)\n"
"//#define make_int2 (int2)\n"
"#define max2 max\n"
"#define min2 min\n"
"///////////////////////////////////////\n"
"// Vector\n"
"///////////////////////////////////////\n"
"__inline\n"
"float4 fastNormalize4(float4 v)\n"
"{\n"
" return fast_normalize(v);\n"
"}\n"
"__inline\n"
"float4 cross3(float4 a, float4 b)\n"
"{\n"
" return cross(a,b);\n"
"}\n"
"__inline\n"
"float dot3F4(float4 a, float4 b)\n"
"{\n"
" float4 a1 = mymake_float4(a.xyz,0.f);\n"
" float4 b1 = mymake_float4(b.xyz,0.f);\n"
" return dot(a1, b1);\n"
"}\n"
"__inline\n"
"float4 normalize3(const float4 a)\n"
"{\n"
" float4 n = mymake_float4(a.x, a.y, a.z, 0.f);\n"
" return fastNormalize4( n );\n"
"// float length = sqrtf(dot3F4(a, a));\n"
"// return 1.f/length * a;\n"
"}\n"
"///////////////////////////////////////\n"
"// Matrix3x3\n"
"///////////////////////////////////////\n"
"typedef struct\n"
"{\n"
" float4 m_row[3];\n"
"}Matrix3x3;\n"
"__inline\n"
"float4 mtMul1(Matrix3x3 a, float4 b);\n"
"__inline\n"
"float4 mtMul3(float4 a, Matrix3x3 b);\n"
"__inline\n"
"float4 mtMul1(Matrix3x3 a, float4 b)\n"
"{\n"
" float4 ans;\n"
" ans.x = dot3F4( a.m_row[0], b );\n"
" ans.y = dot3F4( a.m_row[1], b );\n"
" ans.z = dot3F4( a.m_row[2], b );\n"
" ans.w = 0.f;\n"
" return ans;\n"
"}\n"
"__inline\n"
"float4 mtMul3(float4 a, Matrix3x3 b)\n"
"{\n"
" float4 colx = mymake_float4(b.m_row[0].x, b.m_row[1].x, b.m_row[2].x, 0);\n"
" float4 coly = mymake_float4(b.m_row[0].y, b.m_row[1].y, b.m_row[2].y, 0);\n"
" float4 colz = mymake_float4(b.m_row[0].z, b.m_row[1].z, b.m_row[2].z, 0);\n"
" float4 ans;\n"
" ans.x = dot3F4( a, colx );\n"
" ans.y = dot3F4( a, coly );\n"
" ans.z = dot3F4( a, colz );\n"
" return ans;\n"
"}\n"
"///////////////////////////////////////\n"
"// Quaternion\n"
"///////////////////////////////////////\n"
"typedef float4 Quaternion;\n"
"#define WG_SIZE 64\n"
"typedef struct\n"
"{\n"
" float4 m_pos;\n"
" Quaternion m_quat;\n"
" float4 m_linVel;\n"
" float4 m_angVel;\n"
" u32 m_shapeIdx;\n"
" float m_invMass;\n"
" float m_restituitionCoeff;\n"
" float m_frictionCoeff;\n"
"} Body;\n"
"typedef struct\n"
"{\n"
" Matrix3x3 m_invInertia;\n"
" Matrix3x3 m_initInvInertia;\n"
"} Shape;\n"
"typedef struct\n"
"{\n"
" float4 m_linear;\n"
" float4 m_worldPos[4];\n"
" float4 m_center; \n"
" float m_jacCoeffInv[4];\n"
" float m_b[4];\n"
" float m_appliedRambdaDt[4];\n"
" float m_fJacCoeffInv[2]; \n"
" float m_fAppliedRambdaDt[2]; \n"
" u32 m_bodyA;\n"
" u32 m_bodyB;\n"
" int m_batchIdx;\n"
" u32 m_paddings[1];\n"
"} Constraint4;\n"
"typedef struct\n"
"{\n"
" int m_nConstraints;\n"
" int m_start;\n"
" int m_batchIdx;\n"
" int m_nSplit;\n"
"// int m_paddings[1];\n"
"} ConstBuffer;\n"
"typedef struct\n"
"{\n"
" int m_solveFriction;\n"
" int m_maxBatch; // long batch really kills the performance\n"
" int m_batchIdx;\n"
" int m_nSplit;\n"
"// int m_paddings[1];\n"
"} ConstBufferBatchSolve;\n"
"void setLinearAndAngular( float4 n, float4 r0, float4 r1, float4* linear, float4* angular0, float4* angular1);\n"
"void setLinearAndAngular( float4 n, float4 r0, float4 r1, float4* linear, float4* angular0, float4* angular1)\n"
"{\n"
" *linear = mymake_float4(-n.xyz,0.f);\n"
" *angular0 = -cross3(r0, n);\n"
" *angular1 = cross3(r1, n);\n"
"}\n"
"float calcRelVel( float4 l0, float4 l1, float4 a0, float4 a1, float4 linVel0, float4 angVel0, float4 linVel1, float4 angVel1 );\n"
"float calcRelVel( float4 l0, float4 l1, float4 a0, float4 a1, float4 linVel0, float4 angVel0, float4 linVel1, float4 angVel1 )\n"
"{\n"
" return dot3F4(l0, linVel0) + dot3F4(a0, angVel0) + dot3F4(l1, linVel1) + dot3F4(a1, angVel1);\n"
"}\n"
"float calcJacCoeff(const float4 linear0, const float4 linear1, const float4 angular0, const float4 angular1,\n"
" float invMass0, const Matrix3x3* invInertia0, float invMass1, const Matrix3x3* invInertia1);\n"
"float calcJacCoeff(const float4 linear0, const float4 linear1, const float4 angular0, const float4 angular1,\n"
" float invMass0, const Matrix3x3* invInertia0, float invMass1, const Matrix3x3* invInertia1)\n"
"{\n"
" // linear0,1 are normlized\n"
" float jmj0 = invMass0;//dot3F4(linear0, linear0)*invMass0;\n"
" float jmj1 = dot3F4(mtMul3(angular0,*invInertia0), angular0);\n"
" float jmj2 = invMass1;//dot3F4(linear1, linear1)*invMass1;\n"
" float jmj3 = dot3F4(mtMul3(angular1,*invInertia1), angular1);\n"
" return -1.f/(jmj0+jmj1+jmj2+jmj3);\n"
"}\n"
"void btPlaneSpace1 (const float4* n, float4* p, float4* q);\n"
" void btPlaneSpace1 (const float4* n, float4* p, float4* q)\n"
"{\n"
" if (fabs(n[0].z) > 0.70710678f) {\n"
" // choose p in y-z plane\n"
" float a = n[0].y*n[0].y + n[0].z*n[0].z;\n"
" float k = 1.f/sqrt(a);\n"
" p[0].x = 0;\n"
" p[0].y = -n[0].z*k;\n"
" p[0].z = n[0].y*k;\n"
" // set q = n x p\n"
" q[0].x = a*k;\n"
" q[0].y = -n[0].x*p[0].z;\n"
" q[0].z = n[0].x*p[0].y;\n"
" }\n"
" else {\n"
" // choose p in x-y plane\n"
" float a = n[0].x*n[0].x + n[0].y*n[0].y;\n"
" float k = 1.f/sqrt(a);\n"
" p[0].x = -n[0].y*k;\n"
" p[0].y = n[0].x*k;\n"
" p[0].z = 0;\n"
" // set q = n x p\n"
" q[0].x = -n[0].z*p[0].y;\n"
" q[0].y = n[0].z*p[0].x;\n"
" q[0].z = a*k;\n"
" }\n"
"}\n"
"void solveFrictionConstraint(__global Body* gBodies, __global Shape* gShapes, __global Constraint4* ldsCs);\n"
"void solveFrictionConstraint(__global Body* gBodies, __global Shape* gShapes, __global Constraint4* ldsCs)\n"
"{\n"
" float frictionCoeff = ldsCs[0].m_linear.w;\n"
" int aIdx = ldsCs[0].m_bodyA;\n"
" int bIdx = ldsCs[0].m_bodyB;\n"
" float4 posA = gBodies[aIdx].m_pos;\n"
" float4 linVelA = gBodies[aIdx].m_linVel;\n"
" float4 angVelA = gBodies[aIdx].m_angVel;\n"
" float invMassA = gBodies[aIdx].m_invMass;\n"
" Matrix3x3 invInertiaA = gShapes[aIdx].m_invInertia;\n"
" float4 posB = gBodies[bIdx].m_pos;\n"
" float4 linVelB = gBodies[bIdx].m_linVel;\n"
" float4 angVelB = gBodies[bIdx].m_angVel;\n"
" float invMassB = gBodies[bIdx].m_invMass;\n"
" Matrix3x3 invInertiaB = gShapes[bIdx].m_invInertia;\n"
" \n"
" {\n"
" float maxRambdaDt[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};\n"
" float minRambdaDt[4] = {0.f,0.f,0.f,0.f};\n"
" float sum = 0;\n"
" for(int j=0; j<4; j++)\n"
" {\n"
" sum +=ldsCs[0].m_appliedRambdaDt[j];\n"
" }\n"
" frictionCoeff = 0.7f;\n"
" for(int j=0; j<4; j++)\n"
" {\n"
" maxRambdaDt[j] = frictionCoeff*sum;\n"
" minRambdaDt[j] = -maxRambdaDt[j];\n"
" }\n"
" \n"
"// solveFriction( ldsCs, posA, &linVelA, &angVelA, invMassA, invInertiaA,\n"
"// posB, &linVelB, &angVelB, invMassB, invInertiaB, maxRambdaDt, minRambdaDt );\n"
" \n"
" \n"
" {\n"
" \n"
" __global Constraint4* cs = ldsCs;\n"
" \n"
" if( cs->m_fJacCoeffInv[0] == 0 && cs->m_fJacCoeffInv[0] == 0 ) return;\n"
" const float4 center = cs->m_center;\n"
" \n"
" float4 n = -cs->m_linear;\n"
" \n"
" float4 tangent[2];\n"
" btPlaneSpace1(&n,&tangent[0],&tangent[1]);\n"
" float4 angular0, angular1, linear;\n"
" float4 r0 = center - posA;\n"
" float4 r1 = center - posB;\n"
" for(int i=0; i<2; i++)\n"
" {\n"
" setLinearAndAngular( tangent[i], r0, r1, &linear, &angular0, &angular1 );\n"
" float rambdaDt = calcRelVel(linear, -linear, angular0, angular1,\n"
" linVelA, angVelA, linVelB, angVelB );\n"
" rambdaDt *= cs->m_fJacCoeffInv[i];\n"
" \n"
" {\n"
" float prevSum = cs->m_fAppliedRambdaDt[i];\n"
" float updated = prevSum;\n"
" updated += rambdaDt;\n"
" updated = max2( updated, minRambdaDt[i] );\n"
" updated = min2( updated, maxRambdaDt[i] );\n"
" rambdaDt = updated - prevSum;\n"
" cs->m_fAppliedRambdaDt[i] = updated;\n"
" }\n"
" \n"
" float4 linImp0 = invMassA*linear*rambdaDt;\n"
" float4 linImp1 = invMassB*(-linear)*rambdaDt;\n"
" float4 angImp0 = mtMul1(invInertiaA, angular0)*rambdaDt;\n"
" float4 angImp1 = mtMul1(invInertiaB, angular1)*rambdaDt;\n"
" \n"
" linVelA += linImp0;\n"
" angVelA += angImp0;\n"
" linVelB += linImp1;\n"
" angVelB += angImp1;\n"
" }\n"
" { // angular damping for point constraint\n"
" float4 ab = normalize3( posB - posA );\n"
" float4 ac = normalize3( center - posA );\n"
" if( dot3F4( ab, ac ) > 0.95f || (invMassA == 0.f || invMassB == 0.f))\n"
" {\n"
" float angNA = dot3F4( n, angVelA );\n"
" float angNB = dot3F4( n, angVelB );\n"
" \n"
" angVelA -= (angNA*0.1f)*n;\n"
" angVelB -= (angNB*0.1f)*n;\n"
" }\n"
" }\n"
" }\n"
" \n"
" \n"
" }\n"
" if (gBodies[aIdx].m_invMass)\n"
" {\n"
" gBodies[aIdx].m_linVel = linVelA;\n"
" gBodies[aIdx].m_angVel = angVelA;\n"
" } else\n"
" {\n"
" gBodies[aIdx].m_linVel = mymake_float4(0,0,0,0);\n"
" gBodies[aIdx].m_angVel = mymake_float4(0,0,0,0);\n"
" }\n"
" if (gBodies[bIdx].m_invMass)\n"
" {\n"
" gBodies[bIdx].m_linVel = linVelB;\n"
" gBodies[bIdx].m_angVel = angVelB;\n"
" } else\n"
" {\n"
" gBodies[bIdx].m_linVel = mymake_float4(0,0,0,0);\n"
" gBodies[bIdx].m_angVel = mymake_float4(0,0,0,0);\n"
" }\n"
" \n"
"}\n"
"typedef struct \n"
"{\n"
" int m_valInt0;\n"
" int m_valInt1;\n"
" int m_valInt2;\n"
" int m_valInt3;\n"
" float m_val0;\n"
" float m_val1;\n"
" float m_val2;\n"
" float m_val3;\n"
"} SolverDebugInfo;\n"
"__kernel\n"
"__attribute__((reqd_work_group_size(WG_SIZE,1,1)))\n"
"void BatchSolveKernelFriction(__global Body* gBodies,\n"
" __global Shape* gShapes,\n"
" __global Constraint4* gConstraints,\n"
" __global int* gN,\n"
" __global int* gOffsets,\n"
" __global int* batchSizes,\n"
" int maxBatch1,\n"
" int cellBatch,\n"
" int4 nSplit\n"
" )\n"
"{\n"
" //__local int ldsBatchIdx[WG_SIZE+1];\n"
" __local int ldsCurBatch;\n"
" __local int ldsNextBatch;\n"
" __local int ldsStart;\n"
" int lIdx = GET_LOCAL_IDX;\n"
" int wgIdx = GET_GROUP_IDX;\n"
"// int gIdx = GET_GLOBAL_IDX;\n"
"// debugInfo[gIdx].m_valInt0 = gIdx;\n"
" //debugInfo[gIdx].m_valInt1 = GET_GROUP_SIZE;\n"
" int zIdx = (wgIdx/((nSplit.x*nSplit.y)/4))*2+((cellBatch&4)>>2);\n"
" int remain= (wgIdx%((nSplit.x*nSplit.y)/4));\n"
" int yIdx = (remain/(nSplit.x/2))*2 + ((cellBatch&2)>>1);\n"
" int xIdx = (remain%(nSplit.x/2))*2 + (cellBatch&1);\n"
" int cellIdx = xIdx+yIdx*nSplit.x+zIdx*(nSplit.x*nSplit.y);\n"
" \n"
" if( gN[cellIdx] == 0 ) \n"
" return;\n"
" int maxBatch = batchSizes[cellIdx];\n"
" const int start = gOffsets[cellIdx];\n"
" const int end = start + gN[cellIdx];\n"
" \n"
" if( lIdx == 0 )\n"
" {\n"
" ldsCurBatch = 0;\n"
" ldsNextBatch = 0;\n"
" ldsStart = start;\n"
" }\n"
" GROUP_LDS_BARRIER;\n"
" int idx=ldsStart+lIdx;\n"
" while (ldsCurBatch < maxBatch)\n"
" {\n"
" for(; idx<end; )\n"
" {\n"
" if (gConstraints[idx].m_batchIdx == ldsCurBatch)\n"
" {\n"
" solveFrictionConstraint( gBodies, gShapes, &gConstraints[idx] );\n"
" idx+=64;\n"
" } else\n"
" {\n"
" break;\n"
" }\n"
" }\n"
" GROUP_LDS_BARRIER;\n"
" if( lIdx == 0 )\n"
" {\n"
" ldsCurBatch++;\n"
" }\n"
" GROUP_LDS_BARRIER;\n"
" }\n"
" \n"
" \n"
"}\n"
"__kernel void solveSingleFrictionKernel(__global Body* gBodies,\n"
" __global Shape* gShapes,\n"
" __global Constraint4* gConstraints,\n"
" int cellIdx,\n"
" int batchOffset,\n"
" int numConstraintsInBatch\n"
" )\n"
"{\n"
" int index = get_global_id(0);\n"
" if (index < numConstraintsInBatch)\n"
" {\n"
" \n"
" int idx=batchOffset+index;\n"
" \n"
" solveFrictionConstraint( gBodies, gShapes, &gConstraints[idx] );\n"
" } \n"
"}\n"
;
| 412 | 0.652176 | 1 | 0.652176 | game-dev | MEDIA | 0.250978 | game-dev | 0.662812 | 1 | 0.662812 |
acidanthera/Lilu | 3,659 | capstone/bindings/java/capstone/Arm.java | // Capstone Java binding
// By Nguyen Anh Quynh & Dang Hoang Vu, 2013
package capstone;
import com.sun.jna.Structure;
import com.sun.jna.Union;
import java.util.List;
import java.util.Arrays;
import static capstone.Arm_const.*;
public class Arm {
public static class MemType extends Structure {
public int base;
public int index;
public int scale;
public int disp;
@Override
public List getFieldOrder() {
return Arrays.asList("base", "index", "scale", "disp");
}
}
public static class OpValue extends Union {
public int reg;
public int imm;
public double fp;
public MemType mem;
public int setend;
@Override
public List getFieldOrder() {
return Arrays.asList("reg", "imm", "fp", "mem", "setend");
}
}
public static class OpShift extends Structure {
public int type;
public int value;
@Override
public List getFieldOrder() {
return Arrays.asList("type","value");
}
}
public static class Operand extends Structure {
public int vector_index;
public OpShift shift;
public int type;
public OpValue value;
public boolean subtracted;
public void read() {
readField("vector_index");
readField("type");
if (type == ARM_OP_MEM)
value.setType(MemType.class);
if (type == ARM_OP_FP)
value.setType(Double.TYPE);
if (type == ARM_OP_PIMM || type == ARM_OP_IMM || type == ARM_OP_CIMM)
value.setType(Integer.TYPE);
if (type == ARM_OP_REG)
value.setType(Integer.TYPE);
if (type == ARM_OP_INVALID)
return;
readField("value");
readField("shift");
readField("subtracted");
}
@Override
public List getFieldOrder() {
return Arrays.asList("vector_index", "shift", "type", "value", "subtracted");
}
}
public static class UnionOpInfo extends Capstone.UnionOpInfo {
public boolean usermode;
public int vector_size;
public int vector_data;
public int cps_mode;
public int cps_flag;
public int cc;
public byte update_flags;
public byte writeback;
public byte mem_barrier;
public byte op_count;
public Operand [] op;
public UnionOpInfo() {
op = new Operand[36];
}
public void read() {
readField("usermode");
readField("vector_size");
readField("vector_data");
readField("cps_mode");
readField("cps_flag");
readField("cc");
readField("update_flags");
readField("writeback");
readField("mem_barrier");
readField("op_count");
op = new Operand[op_count];
if (op_count != 0)
readField("op");
}
@Override
public List getFieldOrder() {
return Arrays.asList("usermode", "vector_size", "vector_data",
"cps_mode", "cps_flag", "cc", "update_flags", "writeback", "mem_barrier", "op_count", "op");
}
}
public static class OpInfo extends Capstone.OpInfo {
public boolean usermode;
public int vectorSize;
public int vectorData;
public int cpsMode;
public int cpsFlag;
public int cc;
public boolean updateFlags;
public boolean writeback;
public int memBarrier;
public Operand [] op = null;
public OpInfo(UnionOpInfo op_info) {
usermode = op_info.usermode;
vectorSize = op_info.vector_size;
vectorData = op_info.vector_data;
cpsMode = op_info.cps_mode;
cpsFlag = op_info.cps_flag;
cc = op_info.cc;
updateFlags = (op_info.update_flags > 0);
writeback = (op_info.writeback > 0);
memBarrier = op_info.mem_barrier;
op = op_info.op;
}
}
}
| 412 | 0.526602 | 1 | 0.526602 | game-dev | MEDIA | 0.16101 | game-dev | 0.759561 | 1 | 0.759561 |
hundeva/Lean-Launcher | 5,386 | src/com/android/launcher3/logging/DumpTargetWrapper.java | /*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.
*/
package com.android.launcher3.logging;
import android.os.Process;
import android.text.TextUtils;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.model.nano.LauncherDumpProto;
import com.android.launcher3.model.nano.LauncherDumpProto.ContainerType;
import com.android.launcher3.model.nano.LauncherDumpProto.DumpTarget;
import com.android.launcher3.model.nano.LauncherDumpProto.ItemType;
import com.android.launcher3.model.nano.LauncherDumpProto.UserType;
import java.util.ArrayList;
import java.util.List;
/**
* This class can be used when proto definition doesn't support nesting.
*/
public class DumpTargetWrapper {
DumpTarget node;
ArrayList<DumpTargetWrapper> children;
public DumpTargetWrapper() {
children = new ArrayList<>();
}
public DumpTargetWrapper(int containerType, int id) {
this();
node = newContainerTarget(containerType, id);
}
public DumpTargetWrapper(ItemInfo info) {
this();
node = newItemTarget(info);
}
public DumpTarget getDumpTarget() {
return node;
}
public void add(DumpTargetWrapper child) {
children.add(child);
}
public List<DumpTarget> getFlattenedList() {
ArrayList<DumpTarget> list = new ArrayList<>();
list.add(node);
if (!children.isEmpty()) {
for(DumpTargetWrapper t: children) {
list.addAll(t.getFlattenedList());
}
list.add(node); // add a delimiter empty object
}
return list;
}
public DumpTarget newItemTarget(ItemInfo info) {
DumpTarget dt = new DumpTarget();
dt.type = DumpTarget.Type.ITEM;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
dt.itemType = ItemType.APP_ICON;
break;
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
dt.itemType = ItemType.UNKNOWN_ITEMTYPE;
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
dt.itemType = ItemType.WIDGET;
break;
case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
dt.itemType = ItemType.SHORTCUT;
break;
}
return dt;
}
public DumpTarget newContainerTarget(int type, int id) {
DumpTarget dt = new DumpTarget();
dt.type = DumpTarget.Type.CONTAINER;
dt.containerType = type;
dt.pageId = id;
return dt;
}
public static String getDumpTargetStr(DumpTarget t) {
if (t == null){
return "";
}
switch (t.type) {
case LauncherDumpProto.DumpTarget.Type.ITEM:
return getItemStr(t);
case LauncherDumpProto.DumpTarget.Type.CONTAINER:
String str = LoggerUtils.getFieldName(t.containerType, ContainerType.class);
if (t.containerType == ContainerType.WORKSPACE) {
str += " id=" + t.pageId;
} else if (t.containerType == ContainerType.FOLDER) {
str += " grid(" + t.gridX + "," + t.gridY+ ")";
}
return str;
default:
return "UNKNOWN TARGET TYPE";
}
}
private static String getItemStr(DumpTarget t) {
String typeStr = LoggerUtils.getFieldName(t.itemType, ItemType.class);
if (!TextUtils.isEmpty(t.packageName)) {
typeStr += ", package=" + t.packageName;
}
if (!TextUtils.isEmpty(t.component)) {
typeStr += ", component=" + t.component;
}
return typeStr + ", grid(" + t.gridX + "," + t.gridY + "), span(" + t.spanX + "," + t.spanY
+ "), pageIdx=" + t.pageId + " user=" + t.userType;
}
public DumpTarget writeToDumpTarget(ItemInfo info) {
node.component = info.getTargetComponent() == null? "":
info.getTargetComponent().flattenToString();
node.packageName = info.getTargetComponent() == null? "":
info.getTargetComponent().getPackageName();
if (info instanceof LauncherAppWidgetInfo) {
node.component = ((LauncherAppWidgetInfo) info).providerName.flattenToString();
node.packageName = ((LauncherAppWidgetInfo) info).providerName.getPackageName();
}
node.gridX = info.cellX;
node.gridY = info.cellY;
node.spanX = info.spanX;
node.spanY = info.spanY;
node.userType = (info.user.equals(Process.myUserHandle()))? UserType.DEFAULT : UserType.WORK;
return node;
}
}
| 412 | 0.857222 | 1 | 0.857222 | game-dev | MEDIA | 0.892962 | game-dev | 0.971931 | 1 | 0.971931 |
00-Evan/shattered-pixel-dungeon-gdx | 2,620 | core/src/com/shatteredpixel/shatteredpixeldungeon/items/weapon/missiles/darts/DisplacingDart.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 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.items.weapon.missiles.darts;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.ScrollOfTeleportation;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.watabou.utils.Random;
import java.util.ArrayList;
import java.util.HashMap;
public class DisplacingDart extends TippedDart {
{
image = ItemSpriteSheet.DISPLACING_DART;
}
int distance = 8;
@Override
public int proc(Char attacker, Char defender, int damage) {
if (!defender.properties().contains(Char.Property.IMMOVABLE)){
int startDist = Dungeon.level.distance(attacker.pos, defender.pos);
HashMap<Integer, ArrayList<Integer>> positions = new HashMap<>();
for (int pos = 0; pos < Dungeon.level.length(); pos++){
if (Dungeon.level.heroFOV[pos]
&& Dungeon.level.passable[pos]
&& Actor.findChar(pos) == null){
int dist = Dungeon.level.distance(attacker.pos, pos);
if (dist > startDist){
if (positions.get(dist) == null){
positions.put(dist, new ArrayList<Integer>());
}
positions.get(dist).add(pos);
}
}
}
float[] probs = new float[distance+1];
for (int i = 0; i <= distance; i++){
if (positions.get(i) != null){
probs[i] = i - startDist;
}
}
int chosenDist = Random.chances(probs);
if (chosenDist != -1){
int pos = positions.get(chosenDist).get(Random.index(positions.get(chosenDist)));
ScrollOfTeleportation.appear( defender, pos );
Dungeon.level.occupyCell(defender );
}
}
return super.proc(attacker, defender, damage);
}
}
| 412 | 0.88631 | 1 | 0.88631 | game-dev | MEDIA | 0.996786 | game-dev | 0.925032 | 1 | 0.925032 |
CleanroomMC/Multiblocked | 5,159 | src/main/java/com/cleanroommc/multiblocked/common/capability/PneumaticPressureCapability.java | package com.cleanroommc.multiblocked.common.capability;
import com.cleanroommc.multiblocked.api.capability.IO;
import com.cleanroommc.multiblocked.api.capability.MultiblockCapability;
import com.cleanroommc.multiblocked.api.capability.proxy.CapabilityProxy;
import com.cleanroommc.multiblocked.api.capability.trait.CapabilityTrait;
import com.cleanroommc.multiblocked.api.gui.texture.TextTexture;
import com.cleanroommc.multiblocked.api.gui.widget.imp.recipe.ContentWidget;
import com.cleanroommc.multiblocked.api.pattern.util.BlockInfo;
import com.cleanroommc.multiblocked.api.recipe.ContentModifier;
import com.cleanroommc.multiblocked.api.recipe.Recipe;
import com.cleanroommc.multiblocked.common.capability.trait.PneumaticMachineTrait;
import com.cleanroommc.multiblocked.common.capability.widget.NumberContentWidget;
import com.google.gson.*;
import me.desht.pneumaticcraft.api.tileentity.IAirHandler;
import me.desht.pneumaticcraft.api.tileentity.IPneumaticMachine;
import me.desht.pneumaticcraft.common.block.Blockss;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.lang.reflect.Type;
import java.util.List;
/**
* @author youyihj
*/
public class PneumaticPressureCapability extends MultiblockCapability<Float> {
public static final PneumaticPressureCapability CAP = new PneumaticPressureCapability();
protected PneumaticPressureCapability() {
super("pneumatic_pressure", new Color(0xFF3C00).getRGB());
}
@Override
public Float defaultContent() {
return 2.0f;
}
@Override
public Float copyInner(Float content) {
return content;
}
@Override
public Float copyInnerByModifier(Float content, ContentModifier modifier) {
return (float) modifier.apply(content);
}
@Override
public CapabilityProxy<? extends Float> createProxy(@Nonnull IO io, @Nonnull TileEntity tileEntity) {
return new Proxy(tileEntity);
}
@Override
public Float deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return json.getAsFloat();
}
@Override
public JsonElement serialize(Float src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src);
}
@Override
public boolean isBlockHasCapability(@Nonnull IO io, @Nonnull TileEntity tileEntity) {
return tileEntity instanceof IPneumaticMachine;
}
@Override
public BlockInfo[] getCandidates() {
return new BlockInfo[] {
new BlockInfo(Blockss.AIR_COMPRESSOR),
new BlockInfo(Blockss.LIQUID_COMPRESSOR),
new BlockInfo(Blockss.ADVANCED_AIR_COMPRESSOR),
new BlockInfo(Blockss.ADVANCED_LIQUID_COMPRESSOR),
new BlockInfo(Blockss.CREATIVE_COMPRESSOR)
};
}
@Override
public boolean hasTrait() {
return true;
}
@Override
public ContentWidget<? super Float> createContentWidget() {
return new NumberContentWidget().setContentTexture(new TextTexture("P", color)).setUnit("bar");
}
@Override
public CapabilityTrait createTrait() {
return new PneumaticMachineTrait();
}
private static class Proxy extends CapabilityProxy<Float> {
public Proxy(TileEntity tileEntity) {
super(CAP, tileEntity);
}
public IAirHandler getAirHandler() {
IPneumaticMachine machine = (IPneumaticMachine) getTileEntity();
if (machine != null) {
for (EnumFacing value : EnumFacing.values()) {
IAirHandler airHandler = machine.getAirHandler(value);
if (airHandler != null) return airHandler;
}
}
return null;
}
int air;
int volume;
@Override
protected boolean hasInnerChanged() {
IAirHandler airHandler = getAirHandler();
if (airHandler == null) return false;
if (airHandler.getAir() == air && airHandler.getVolume() == volume) {
return false;
}
air = airHandler.getAir();
volume = airHandler.getVolume();
return true;
}
@Override
protected List<Float> handleRecipeInner(IO io, Recipe recipe, List<Float> left, @Nullable String slotName, boolean simulate) {
IAirHandler handler = getAirHandler();
float sum = left.stream().reduce(0.0f, Float::sum);
int consumeAir = (int) (sum * 50);
if (handler != null && io == IO.IN) {
int air = handler.getAir();
if (Math.signum(air) == Math.signum(consumeAir) && Math.abs(air) >= Math.abs(consumeAir) && Math.abs(handler.getPressure()) >= Math.abs(sum)) {
if (!simulate) {
handler.addAir(-consumeAir);
}
return null;
}
}
return left;
}
}
}
| 412 | 0.831554 | 1 | 0.831554 | game-dev | MEDIA | 0.915134 | game-dev | 0.880616 | 1 | 0.880616 |
tgstation/tgstation | 8,137 | code/modules/spells/spell_types/shapeshift/_shapeshift.dm | /// Helper for checking of someone's shapeshifted currently.
#define is_shifted(mob) mob.has_status_effect(/datum/status_effect/shapechange_mob/from_spell)
/**
* Shapeshift spells.
*
* Allows the caster to transform to and from a different mob type.
*/
/datum/action/cooldown/spell/shapeshift
button_icon_state = "shapeshift"
school = SCHOOL_TRANSMUTATION
cooldown_time = 10 SECONDS
/// Our spell's requrements before we shapeshifted. Stored on shapeshift so we can restore them after unshifting.
var/pre_shift_requirements
/// Whether we revert to our human form on death.
var/revert_on_death = TRUE
/// Whether we die when our shapeshifted form is killed
var/die_with_shapeshifted_form = TRUE
/// Whether we convert our health from one form to another
var/convert_damage = TRUE
/// If convert damage is true, the damage type we deal when converting damage back and forth
var/convert_damage_type = BRUTE
/// Our chosen type.
var/mob/living/shapeshift_type
/// All possible types we can become.
/// This should be implemented even if there is only one choice.
var/list/atom/possible_shapes
/datum/action/cooldown/spell/shapeshift/Remove(mob/remove_from)
unshift_owner()
return ..()
/datum/action/cooldown/spell/shapeshift/is_valid_target(atom/cast_on)
return isliving(cast_on)
/datum/action/cooldown/spell/shapeshift/before_cast(mob/living/cast_on)
. = ..()
if(. & SPELL_CANCEL_CAST)
return
if(shapeshift_type)
// If another shapeshift spell was casted while we're already shifted, they could technically go to do_unshapeshift().
// However, we don't really want people casting shapeshift A to un-shapeshift from shapeshift B,
// as it could cause bugs or unintended behavior. So we'll just stop them here.
if(is_shifted(cast_on) && !is_type_in_list(cast_on, possible_shapes))
to_chat(cast_on, span_warning("This spell won't un-shapeshift you from this form!"))
return . | SPELL_CANCEL_CAST
return
if(length(possible_shapes) == 1)
shapeshift_type = possible_shapes[1]
return
// Not bothering with caching these as they're only ever shown once
var/list/shape_names_to_types = list()
var/list/shape_names_to_image = list()
if(!length(shape_names_to_types) || !length(shape_names_to_image))
for(var/atom/path as anything in possible_shapes)
var/shape_name = initial(path.name)
shape_names_to_types[shape_name] = path
shape_names_to_image[shape_name] = image(icon = initial(path.icon), icon_state = initial(path.icon_state))
var/picked_type = show_radial_menu(
cast_on,
cast_on,
shape_names_to_image,
custom_check = CALLBACK(src, PROC_REF(check_menu), cast_on),
radius = 38,
)
if(!picked_type)
return . | SPELL_CANCEL_CAST
var/atom/shift_type = shape_names_to_types[picked_type]
if(!ispath(shift_type))
return . | SPELL_CANCEL_CAST
shapeshift_type = shift_type || pick(possible_shapes)
if(QDELETED(src) || QDELETED(owner) || !can_cast_spell(feedback = FALSE))
return . | SPELL_CANCEL_CAST
/datum/action/cooldown/spell/shapeshift/cast(mob/living/cast_on)
. = ..()
cast_on.buckled?.unbuckle_mob(cast_on, force = TRUE)
var/currently_ventcrawling = (cast_on.movement_type & VENTCRAWLING)
var/mob/living/resulting_mob
// Do the shift back or forth
if(is_shifted(cast_on))
resulting_mob = do_unshapeshift(cast_on)
else
resulting_mob = do_shapeshift(cast_on)
// The shift is done, let's make sure they're in a valid state now
// If we're not ventcrawling, we don't need to mind
if(!currently_ventcrawling || !resulting_mob)
return
// We are ventcrawling - can our new form support ventcrawling?
if(HAS_TRAIT(resulting_mob, TRAIT_VENTCRAWLER_ALWAYS) || HAS_TRAIT(resulting_mob, TRAIT_VENTCRAWLER_NUDE))
return
// Uh oh. You've shapeshifted into something that can't fit into a vent, while ventcrawling.
eject_from_vents(resulting_mob)
/// Whenever someone shapeshifts within a vent,
/// and enters a state in which they are no longer a ventcrawler,
/// they are brutally ejected from the vents. In the form of gibs.
/datum/action/cooldown/spell/shapeshift/proc/eject_from_vents(mob/living/cast_on)
var/obj/machinery/atmospherics/pipe_you_die_in = cast_on.loc
var/datum/pipeline/our_pipeline
var/pipenets = pipe_you_die_in.return_pipenets()
if(islist(pipenets))
our_pipeline = pipenets[1]
else
our_pipeline = pipenets
to_chat(cast_on, span_userdanger("Casting [src] inside of [pipe_you_die_in] quickly turns you into a bloody mush!"))
var/obj/effect/gib_type = cast_on.get_gibs_type()
for(var/obj/machinery/atmospherics/components/unary/possible_vent in range(10, get_turf(cast_on)))
if(length(possible_vent.parents) && possible_vent.parents[1] == our_pipeline)
new gib_type(get_turf(possible_vent))
playsound(possible_vent, 'sound/mobs/non-humanoids/frog/reee.ogg', 75, TRUE)
priority_announce("We detected a pipe blockage around [get_area(get_turf(cast_on))], please dispatch someone to investigate.", "[command_name()]")
// Gib our caster, and make sure to leave nothing behind
// (If we leave something behind, it'll drop on the turf of the pipe, which is kinda wrong.)
cast_on.investigate_log("has been gibbed by shapeshifting while ventcrawling.", INVESTIGATE_DEATHS)
cast_on.gib()
/// Callback for the radial that allows the user to choose their species.
/datum/action/cooldown/spell/shapeshift/proc/check_menu(mob/living/caster)
if(QDELETED(src))
return FALSE
if(QDELETED(caster))
return FALSE
return !caster.incapacitated
/// Actually does the shapeshift, for the caster.
/datum/action/cooldown/spell/shapeshift/proc/do_shapeshift(mob/living/caster)
var/mob/living/new_shape = create_shapeshift_mob(caster.loc)
var/datum/status_effect/shapechange_mob/shapechange = new_shape.apply_status_effect(/datum/status_effect/shapechange_mob/from_spell, caster, src)
if(!shapechange)
// We failed to shift, maybe because we were already shapeshifted?
// Whatver the case, this shouldn't happen, so throw a stack trace.
to_chat(caster, span_warning("You can't shapeshift in this form!"))
stack_trace("[type] do_shapeshift was called when the mob was already shapeshifted (from a spell).")
return
// Make sure it's castable even in their new form.
pre_shift_requirements = spell_requirements
spell_requirements &= ~(SPELL_REQUIRES_HUMAN|SPELL_REQUIRES_WIZARD_GARB)
ADD_TRAIT(new_shape, TRAIT_DONT_WRITE_MEMORY, SHAPESHIFT_TRAIT) // If you shapeshift into a pet subtype we don't want to update Poly's deathcount or something when you die
// Make sure that if you shapechanged into a bot, the AI can't just turn you off.
var/mob/living/simple_animal/bot/polymorph_bot = new_shape
if (istype(polymorph_bot))
polymorph_bot.bot_cover_flags |= BOT_COVER_EMAGGED
polymorph_bot.bot_mode_flags &= ~BOT_MODE_REMOTE_ENABLED
return new_shape
/// Actually does the un-shapeshift, from the caster. (Caster is a shapeshifted mob.)
/datum/action/cooldown/spell/shapeshift/proc/do_unshapeshift(mob/living/caster)
var/datum/status_effect/shapechange_mob/shapechange = caster.has_status_effect(/datum/status_effect/shapechange_mob/from_spell)
if(!shapechange)
// We made it to do_unshapeshift without having a shapeshift status effect, this shouldn't happen.
to_chat(caster, span_warning("You can't un-shapeshift from this form!"))
stack_trace("[type] do_unshapeshift was called when the mob wasn't even shapeshifted (from a spell).")
return
// Restore the requirements.
spell_requirements = pre_shift_requirements
pre_shift_requirements = null
var/mob/living/unshapeshifted_mob = shapechange.caster_mob
caster.remove_status_effect(/datum/status_effect/shapechange_mob/from_spell)
return unshapeshifted_mob
/// Helper proc that instantiates the mob we shapeshift into.
/// Returns an instance of a living mob. Can be overridden.
/datum/action/cooldown/spell/shapeshift/proc/create_shapeshift_mob(atom/loc)
return new shapeshift_type(loc)
/// Removes an active shapeshift effect from the owner
/datum/action/cooldown/spell/shapeshift/proc/unshift_owner()
if (isnull(owner))
return
if (is_shifted(owner))
do_unshapeshift(owner)
#undef is_shifted
| 412 | 0.918535 | 1 | 0.918535 | game-dev | MEDIA | 0.886367 | game-dev | 0.982417 | 1 | 0.982417 |
EclipseMenu/EclipseMenu | 39,196 | src/modules/utils/GameCheckpoint.hpp | #pragma once
#include "modules/utils/SingletonCache.hpp"
#include <Geode/binding/PlayerObject.hpp>
using namespace geode::prelude;
namespace eclipse::utils {
class FixPlayLayerCheckpoint {
public:
FixPlayLayerCheckpoint() = default;
FixPlayLayerCheckpoint(PlayLayer* playLayer) {
//GJBaseGameLayer
m_player1CollisionBlock = playLayer->m_player1CollisionBlock;
m_player2CollisionBlock = playLayer->m_player2CollisionBlock;
m_extraDelta = playLayer->m_extraDelta;
m_unk32d0 = playLayer->m_unk32d0;
m_queueInterval = playLayer->m_queueInterval;
m_unk32ec = playLayer->m_unk32ec;
m_currentStep = playLayer->m_currentStep;
m_unk3380 = playLayer->m_unk3380;
#ifndef GEODE_IS_ANDROID
m_gameObjectPhysics = playLayer->m_gameState.m_gameObjectPhysics;
#endif
}
void apply(PlayLayer* playLayer) {
//GJBaseGameLayer
playLayer->m_player1CollisionBlock = m_player1CollisionBlock;
playLayer->m_player2CollisionBlock = m_player2CollisionBlock;
playLayer->m_extraDelta = m_extraDelta;
playLayer->m_unk32d0 = m_unk32d0;
playLayer->m_queueInterval = m_queueInterval;
playLayer->m_unk32ec = m_unk32ec;
playLayer->m_currentStep = m_currentStep;
playLayer->m_unk3380 = m_unk3380;
#ifndef GEODE_IS_ANDROID
playLayer->m_gameState.m_gameObjectPhysics = m_gameObjectPhysics;
#endif
}
private:
//GJBaseGameLayer
GameObject* m_player1CollisionBlock;
GameObject* m_player2CollisionBlock;
double m_extraDelta;
int m_unk32d0;
double m_queueInterval;
int m_unk32ec;
int m_currentStep;
float m_unk3380;
#ifndef GEODE_IS_ANDROID
//GameState
gd::unordered_map<int, GameObjectPhysics> m_gameObjectPhysics;
#endif
};
class FixPlayerCheckpoint {
public:
FixPlayerCheckpoint() = default;
FixPlayerCheckpoint(PlayerObject* player) {
m_wasTeleported = player->m_wasTeleported;
m_fixGravityBug = player->m_fixGravityBug;
m_reverseSync = player->m_reverseSync;
m_yVelocityBeforeSlope = player->m_yVelocityBeforeSlope;
m_dashX = player->m_dashX;
m_dashY = player->m_dashY;
m_dashAngle = player->m_dashAngle;
m_dashStartTime = player->m_dashStartTime;
m_slopeStartTime = player->m_slopeStartTime;
m_justPlacedStreak = player->m_justPlacedStreak;
m_maybeLastGroundObject = player->m_maybeLastGroundObject;
m_lastCollisionBottom = player->m_lastCollisionBottom;
m_lastCollisionTop = player->m_lastCollisionTop;
m_lastCollisionLeft = player->m_lastCollisionLeft;
m_lastCollisionRight = player->m_lastCollisionRight;
m_unk50C = player->m_unk50C;
m_unk510 = player->m_unk510;
m_currentSlope2 = player->m_currentSlope2;
m_preLastGroundObject = player->m_preLastGroundObject;
m_slopeAngle = player->m_slopeAngle;
m_slopeSlidingMaybeRotated = player->m_slopeSlidingMaybeRotated;
m_quickCheckpointMode = player->m_quickCheckpointMode;
m_collidedObject = player->m_collidedObject;
m_lastGroundObject = player->m_lastGroundObject;
m_collidingWithLeft = player->m_collidingWithLeft;
m_collidingWithRight = player->m_collidingWithRight;
m_maybeSavedPlayerFrame = player->m_maybeSavedPlayerFrame;
m_scaleXRelated2 = player->m_scaleXRelated2;
m_groundYVelocity = player->m_groundYVelocity;
m_yVelocityRelated = player->m_yVelocityRelated;
m_scaleXRelated3 = player->m_scaleXRelated3;
m_scaleXRelated4 = player->m_scaleXRelated4;
m_scaleXRelated5 = player->m_scaleXRelated5;
m_isCollidingWithSlope = player->m_isCollidingWithSlope;
m_isBallRotating = player->m_isBallRotating;
m_unk669 = player->m_unk669;
m_currentSlope3 = player->m_currentSlope3;
m_currentSlope = player->m_currentSlope;
unk_584 = player->unk_584;
m_collidingWithSlopeId = player->m_collidingWithSlopeId;
m_slopeFlipGravityRelated = player->m_slopeFlipGravityRelated;
m_slopeAngleRadians = player->m_slopeAngleRadians;
m_rotationSpeed = player->m_rotationSpeed;
m_rotateSpeed = player->m_rotateSpeed;
m_isRotating = player->m_isRotating;
m_isBallRotating2 = player->m_isBallRotating2;
m_hasGlow = player->m_hasGlow;
m_isHidden = player->m_isHidden;
m_ghostType = player->m_ghostType;
m_speedMultiplier = player->m_speedMultiplier;
m_yStart = player->m_yStart;
m_gravity = player->m_gravity;
m_trailingParticleLife = player->m_trailingParticleLife;
m_unk648 = player->m_unk648;
m_gameModeChangedTime = player->m_gameModeChangedTime;
m_padRingRelated = player->m_padRingRelated;
m_maybeReducedEffects = player->m_maybeReducedEffects;
m_maybeIsFalling = player->m_maybeIsFalling;
m_shouldTryPlacingCheckpoint = player->m_shouldTryPlacingCheckpoint;
m_playEffects = player->m_playEffects;
m_maybeCanRunIntoBlocks = player->m_maybeCanRunIntoBlocks;
m_hasGroundParticles = player->m_hasGroundParticles;
m_hasShipParticles = player->m_hasShipParticles;
m_isOnGround3 = player->m_isOnGround3;
m_checkpointTimeout = player->m_checkpointTimeout;
m_lastCheckpointTime = player->m_lastCheckpointTime;
m_lastJumpTime = player->m_lastJumpTime;
m_lastFlipTime = player->m_lastFlipTime;
m_flashTime = player->m_flashTime;
m_flashRelated = player->m_flashRelated;
m_flashRelated1 = player->m_flashRelated1;
m_colorRelated2 = player->m_colorRelated2;
m_flashRelated3 = player->m_flashRelated3;
m_lastSpiderFlipTime = player->m_lastSpiderFlipTime;
m_unkBool5 = player->m_unkBool5;
m_maybeIsVehicleGlowing = player->m_maybeIsVehicleGlowing;
m_switchWaveTrailColor = player->m_switchWaveTrailColor;
m_practiceDeathEffect = player->m_practiceDeathEffect;
m_accelerationOrSpeed = player->m_accelerationOrSpeed;
m_snapDistance = player->m_snapDistance;
m_ringJumpRelated = player->m_ringJumpRelated;
m_objectSnappedTo = player->m_objectSnappedTo;
m_pendingCheckpoint = player->m_pendingCheckpoint;
m_onFlyCheckpointTries = player->m_onFlyCheckpointTries;
m_maybeSpriteRelated = player->m_maybeSpriteRelated;
m_useLandParticles0 = player->m_useLandParticles0;
m_landParticlesAngle = player->m_landParticlesAngle;
m_landParticleRelatedY = player->m_landParticleRelatedY;
m_playerStreak = player->m_playerStreak;
m_streakStrokeWidth = player->m_streakStrokeWidth;
m_disableStreakTint = player->m_disableStreakTint;
m_alwaysShowStreak = player->m_alwaysShowStreak;
m_shipStreakType = player->m_shipStreakType;
m_slopeRotation = player->m_slopeRotation;
m_currentSlopeYVelocity = player->m_currentSlopeYVelocity;
m_unk3d0 = player->m_unk3d0;
m_blackOrbRelated = player->m_blackOrbRelated;
m_unk3e0 = player->m_unk3e0;
m_unk3e1 = player->m_unk3e1;
m_isAccelerating = player->m_isAccelerating;
m_isCurrentSlopeTop = player->m_isCurrentSlopeTop;
m_collidedTopMinY = player->m_collidedTopMinY;
m_collidedBottomMaxY = player->m_collidedBottomMaxY;
m_collidedLeftMaxX = player->m_collidedLeftMaxX;
m_collidedRightMinX = player->m_collidedRightMinX;
m_fadeOutStreak = player->m_fadeOutStreak;
// m_canPlaceCheckpoint = m_canPlaceCheckpointckpoint; (breaking)
m_colorRelated = player->m_colorRelated;
m_secondColorRelated = player->m_secondColorRelated;
m_hasCustomGlowColor = player->m_hasCustomGlowColor>m_hasCustomGlowColor;
m_glowColor = player->m_glowColor;
m_maybeIsColliding = player->m_maybeIsColliding;
// m_jumpBuffered = player->m_jumpBuffered; (breaking)
m_stateRingJump = player->m_stateRingJump;
m_wasJumpBuffered = player->m_wasJumpBuffered;
m_wasRobotJump = player->m_wasRobotJump;
m_stateJumpBuffered = player->m_stateJumpBuffered;
m_stateRingJump2 = player->m_stateRingJump2;
m_touchedRing = player->m_touchedRing;
m_touchedCustomRing = player->m_touchedCustomRing;
m_touchedGravityPortal = player->m_touchedGravityPortal;
m_maybeTouchedBreakableBlock = player->m_maybeTouchedBreakableBlock;
m_jumpRelatedAC2 = player->m_jumpRelatedAC2;
m_touchedPad = player->m_touchedPad;
m_yVelocity = player->m_yVelocity;
m_fallSpeed = player->m_fallSpeed;
m_isOnSlope = player->m_isOnSlope;
m_wasOnSlope = player->m_wasOnSlope;
m_slopeVelocity = player->m_slopeVelocity;
m_maybeUpsideDownSlope = player->m_maybeUpsideDownSlope;
m_isShip = player->m_isShip;
m_isBird = player->m_isBird;
m_isBall = player->m_isBall;
m_isDart = player->m_isDart;
m_isRobot = player->m_isRobot;
m_isSpider = player->m_isSpider;
m_isUpsideDown = player->m_isUpsideDown;
m_isDead = player->m_isDead;
m_isOnGround = player->m_isOnGround;
m_isGoingLeft = player->m_isGoingLeft;
m_isSideways = player->m_isSideways;
m_isSwing = player->m_isSwing;
m_reverseRelated = player->m_reverseRelated;
m_maybeReverseSpeed = player->m_maybeReverseSpeed;
m_maybeReverseAcceleration = player->m_maybeReverseAcceleration;
m_xVelocityRelated2 = player->m_xVelocityRelated2;
m_isDashing = player->m_isDashing;
m_unk9e8 = player->m_unk9e8;
m_groundObjectMaterial = player->m_groundObjectMaterial;
m_vehicleSize = player->m_vehicleSize;
m_playerSpeed = player->m_playerSpeed;
m_shipRotation = player->m_shipRotation;
m_lastPortalPos = player->m_lastPortalPos;
m_unkUnused3 = player->m_unkUnused3;
m_isOnGround2 = player->m_isOnGround2;
m_lastLandTime = player->m_lastLandTime;
m_platformerVelocityRelated = player->m_platformerVelocityRelated;
m_maybeIsBoosted = player->m_maybeIsBoosted;
m_scaleXRelatedTime = player->m_scaleXRelatedTime;
m_decreaseBoostSlide = player->m_decreaseBoostSlide;
m_unkA29 = player->m_unkA29;
m_isLocked = player->m_isLocked;
m_controlsDisabled = player->m_controlsDisabled;
m_lastGroundedPos = player->m_lastGroundedPos;
m_lastActivatedPortal = player->m_lastActivatedPortal;
m_hasEverJumped = player->m_hasEverJumped;
m_hasEverHitRing = player->m_hasEverHitRing;
m_playerColor1 = player->m_playerColor1;
m_playerColor2 = player->m_playerColor2;
m_isSecondPlayer = player->m_isSecondPlayer;
m_unkA99 = player->m_unkA99;
m_isBeingSpawnedByDualPortal = player->m_isBeingSpawnedByDualPortal;
m_audioScale = player->m_audioScale;
m_unkAngle1 = player->m_unkAngle1;
m_yVelocityRelated3 = player->m_yVelocityRelated3;
m_defaultMiniIcon = player->m_defaultMiniIcon;
m_swapColors = player->m_swapColors;
m_switchDashFireColor = player->m_switchDashFireColor;
m_followRelated = player->m_followRelated;
m_unk838 = player->m_unk838;
m_stateOnGround = player->m_stateOnGround;
m_stateUnk = player->m_stateUnk;
m_stateNoStickX = player->m_stateNoStickX;
m_stateNoStickY = player->m_stateNoStickY;
m_stateUnk2 = player->m_stateUnk2;
m_stateBoostX = player->m_stateBoostX;
m_stateBoostY = player->m_stateBoostY;
m_maybeStateForce2 = player->m_maybeStateForce2;
m_stateScale = player->m_stateScale;
m_platformerXVelocity = player->m_platformerXVelocity;
m_holdingRight = player->m_holdingRight;
m_holdingLeft = player->m_holdingLeft;
m_leftPressedFirst = player->m_leftPressedFirst;
m_scaleXRelated = player->m_scaleXRelated;
m_maybeHasStopped = player->m_maybeHasStopped;
m_xVelocityRelated = player->m_xVelocityRelated;
m_maybeGoingCorrectSlopeDirection = player->m_maybeGoingCorrectSlopeDirection;
m_isSliding = player->m_isSliding;
m_maybeSlopeForce = player->m_maybeSlopeForce;
m_isOnIce = player->m_isOnIce;
m_physDeltaRelated = player->m_physDeltaRelated;
m_isOnGround4 = player->m_isOnGround4;
m_maybeSlidingTime = player->m_maybeSlidingTime;
m_maybeSlidingStartTime = player->m_maybeSlidingStartTime;
m_changedDirectionsTime = player->m_changedDirectionsTime;
m_slopeEndTime = player->m_slopeEndTime;
m_isMoving = player->m_isMoving;
m_platformerMovingLeft = player->m_platformerMovingLeft;
m_platformerMovingRight = player->m_platformerMovingRight;
m_isSlidingRight = player->m_isSlidingRight;
m_maybeChangedDirectionAngle = player->m_maybeChangedDirectionAngle;
m_unkUnused2 = player->m_unkUnused2;
m_stateNoAutoJump = player->m_stateNoAutoJump;
m_stateDartSlide = player->m_stateDartSlide;
m_stateHitHead = player->m_stateHitHead;
m_stateFlipGravity = player->m_stateFlipGravity;
m_gravityMod = player->m_gravityMod;
m_stateForce = player->m_stateForce;
m_stateForceVector = player->m_stateForceVector;
m_affectedByForces = player->m_affectedByForces;
m_somethingPlayerSpeedTime = player->m_somethingPlayerSpeedTime;
m_playerSpeedAC = player->m_playerSpeedAC;
m_fixRobotJump = player->m_fixRobotJump;
// m_holdingButtons = player->m_holdingButtons; // map<int, bool>
m_inputsLocked = player->m_inputsLocked;
m_gv0123 = player->m_gv0123;
m_iconRequestID = player->m_iconRequestID;
m_unkUnused = player->m_unkUnused;
m_isOutOfBounds = player->m_isOutOfBounds;
m_fallStartY = player->m_fallStartY;
m_disablePlayerSqueeze = player->m_disablePlayerSqueeze;
m_robotAnimation1Enabled = player->m_robotAnimation1Enabled;
m_robotAnimation2Enabled = player->m_robotAnimation2Enabled;
m_spiderAnimationEnabled = player->m_spiderAnimationEnabled;
m_position = player->m_position;
m_rotation = player->getRotation();
#ifndef GEODE_IS_ANDROID
m_rotateObjectsRelated = player->m_rotateObjectsRelated; // unordered_map<int, GJPointDouble>
m_maybeRotatedObjectsMap = player->m_maybeRotatedObjectsMap; // unordered_map<int, GameObject*>
m_ringRelatedSet = player->m_ringRelatedSet; // unordered_set<int>
m_touchedRings = player->m_touchedRings; // unordered_set<int>
m_jumpPadRelated = player->m_jumpPadRelated; // map<int, bool>
m_playerFollowFloats = player->m_playerFollowFloats; // vector<float>
m_currentRobotAnimation = player->m_currentRobotAnimation;
for (int i = 0; i < player->m_touchingRings->count(); i++)
m_touchingRings.push_back(player->m_touchingRings->objectAtIndex(i));
#endif
}
void apply(PlayerObject* player) {
if (!utils::get<PlayLayer>()->m_isPracticeMode) return;
player->m_wasTeleported = m_wasTeleported;
player->m_fixGravityBug = m_fixGravityBug;
player->m_reverseSync = m_reverseSync;
player->m_yVelocityBeforeSlope = m_yVelocityBeforeSlope;
player->m_dashX = m_dashX;
player->m_dashY = m_dashY;
player->m_dashAngle = m_dashAngle;
player->m_dashStartTime = m_dashStartTime;
player->m_slopeStartTime = m_slopeStartTime;
player->m_justPlacedStreak = m_justPlacedStreak;
player->m_maybeLastGroundObject = m_maybeLastGroundObject;
player->m_lastCollisionBottom = m_lastCollisionBottom;
player->m_lastCollisionTop = m_lastCollisionTop;
player->m_lastCollisionLeft = m_lastCollisionLeft;
player->m_lastCollisionRight = m_lastCollisionRight;
player->m_unk50C = m_unk50C;
player->m_unk510 = m_unk510;
player->m_currentSlope2 = m_currentSlope2;
player->m_preLastGroundObject = m_preLastGroundObject;
player->m_slopeAngle = m_slopeAngle;
player->m_slopeSlidingMaybeRotated = m_slopeSlidingMaybeRotated;
player->m_quickCheckpointMode = m_quickCheckpointMode;
player->m_collidedObject = m_collidedObject;
player->m_lastGroundObject = m_lastGroundObject;
player->m_collidingWithLeft = m_collidingWithLeft;
player->m_collidingWithRight = m_collidingWithRight;
player->m_maybeSavedPlayerFrame = m_maybeSavedPlayerFrame;
player->m_scaleXRelated2 = m_scaleXRelated2;
player->m_groundYVelocity = m_groundYVelocity;
player->m_yVelocityRelated = m_yVelocityRelated;
player->m_scaleXRelated3 = m_scaleXRelated3;
player->m_scaleXRelated4 = m_scaleXRelated4;
player->m_scaleXRelated5 = m_scaleXRelated5;
player->m_isCollidingWithSlope = m_isCollidingWithSlope;
player->m_isBallRotating = m_isBallRotating;
player->m_unk669 = m_unk669;
player->m_currentSlope3 = m_currentSlope3;
player->m_currentSlope = m_currentSlope;
player->unk_584 = unk_584;
player->m_collidingWithSlopeId = m_collidingWithSlopeId;
player->m_slopeFlipGravityRelated = m_slopeFlipGravityRelated;
player->m_slopeAngleRadians = m_slopeAngleRadians;
player->m_rotationSpeed = m_rotationSpeed;
player->m_rotateSpeed = m_rotateSpeed;
player->m_isRotating = m_isRotating;
player->m_isBallRotating2 = m_isBallRotating2;
player->m_hasGlow = m_hasGlow;
player->m_isHidden = m_isHidden;
player->m_ghostType = m_ghostType;
player->m_speedMultiplier = m_speedMultiplier;
player->m_yStart = m_yStart;
player->m_gravity = m_gravity;
player->m_trailingParticleLife = m_trailingParticleLife;
player->m_unk648 = m_unk648;
player->m_gameModeChangedTime = m_gameModeChangedTime;
player->m_padRingRelated = m_padRingRelated;
player->m_maybeReducedEffects = m_maybeReducedEffects;
player->m_maybeIsFalling = m_maybeIsFalling;
player->m_shouldTryPlacingCheckpoint = m_shouldTryPlacingCheckpoint;
player->m_playEffects = m_playEffects;
player->m_maybeCanRunIntoBlocks = m_maybeCanRunIntoBlocks;
player->m_hasGroundParticles = m_hasGroundParticles;
player->m_hasShipParticles = m_hasShipParticles;
player->m_isOnGround3 = m_isOnGround3;
player->m_checkpointTimeout = m_checkpointTimeout;
player->m_lastCheckpointTime = m_lastCheckpointTime;
player->m_lastJumpTime = m_lastJumpTime;
player->m_lastFlipTime = m_lastFlipTime;
player->m_flashTime = m_flashTime;
player->m_flashRelated = m_flashRelated;
player->m_flashRelated1 = m_flashRelated1;
player->m_colorRelated2 = m_colorRelated2;
player->m_flashRelated3 = m_flashRelated3;
player->m_lastSpiderFlipTime = m_lastSpiderFlipTime;
player->m_unkBool5 = m_unkBool5;
player->m_maybeIsVehicleGlowing = m_maybeIsVehicleGlowing;
player->m_switchWaveTrailColor = m_switchWaveTrailColor;
player->m_practiceDeathEffect = m_practiceDeathEffect;
player->m_accelerationOrSpeed = m_accelerationOrSpeed;
player->m_snapDistance = m_snapDistance;
player->m_ringJumpRelated = m_ringJumpRelated;
player->m_objectSnappedTo = m_objectSnappedTo;
player->m_pendingCheckpoint = m_pendingCheckpoint;
player->m_onFlyCheckpointTries = m_onFlyCheckpointTries;
player->m_maybeSpriteRelated = m_maybeSpriteRelated;
player->m_useLandParticles0 = m_useLandParticles0;
player->m_landParticlesAngle = m_landParticlesAngle;
player->m_landParticleRelatedY = m_landParticleRelatedY;
player->m_playerStreak = m_playerStreak;
player->m_streakStrokeWidth = m_streakStrokeWidth;
player->m_disableStreakTint = m_disableStreakTint;
player->m_alwaysShowStreak = m_alwaysShowStreak;
player->m_shipStreakType = m_shipStreakType;
player->m_slopeRotation = m_slopeRotation;
player->m_currentSlopeYVelocity = m_currentSlopeYVelocity;
player->m_unk3d0 = m_unk3d0;
player->m_blackOrbRelated = m_blackOrbRelated;
player->m_unk3e0 = m_unk3e0;
player->m_unk3e1 = m_unk3e1;
player->m_isAccelerating = m_isAccelerating;
player->m_isCurrentSlopeTop = m_isCurrentSlopeTop;
player->m_collidedTopMinY = m_collidedTopMinY;
player->m_collidedBottomMaxY = m_collidedBottomMaxY;
player->m_collidedLeftMaxX = m_collidedLeftMaxX;
player->m_collidedRightMinX = m_collidedRightMinX;
player->m_fadeOutStreak = m_fadeOutStreak;
// player->m_canPlaceCheckpoint = m_canPlaceCheckpoint; (breaking)
player->m_colorRelated = m_colorRelated;
player->m_secondColorRelated = m_secondColorRelated;
player->m_hasCustomGlowColor = m_hasCustomGlowColor;
player->m_glowColor = m_glowColor;
player->m_maybeIsColliding = m_maybeIsColliding;
// player->m_jumpBuffered = m_jumpBuffered; (breaking)
player->m_stateRingJump = m_stateRingJump;
player->m_wasJumpBuffered = m_wasJumpBuffered;
player->m_wasRobotJump = m_wasRobotJump;
player->m_stateJumpBuffered = m_stateJumpBuffered;
player->m_stateRingJump2 = m_stateRingJump2;
player->m_touchedRing = m_touchedRing;
player->m_touchedCustomRing = m_touchedCustomRing;
player->m_touchedGravityPortal = m_touchedGravityPortal;
player->m_maybeTouchedBreakableBlock = m_maybeTouchedBreakableBlock;
player->m_jumpRelatedAC2 = m_jumpRelatedAC2;
player->m_touchedPad = m_touchedPad;
player->m_yVelocity = m_yVelocity;
player->m_fallSpeed = m_fallSpeed;
player->m_isOnSlope = m_isOnSlope;
player->m_wasOnSlope = m_wasOnSlope;
player->m_slopeVelocity = m_slopeVelocity;
player->m_maybeUpsideDownSlope = m_maybeUpsideDownSlope;
player->m_isShip = m_isShip;
player->m_isBird = m_isBird;
player->m_isBall = m_isBall;
player->m_isDart = m_isDart;
player->m_isRobot = m_isRobot;
player->m_isSpider = m_isSpider;
player->m_isUpsideDown = m_isUpsideDown;
player->m_isDead = m_isDead;
player->m_isOnGround = m_isOnGround;
player->m_isGoingLeft = m_isGoingLeft;
player->m_isSideways = m_isSideways;
player->m_isSwing = m_isSwing;
player->m_reverseRelated = m_reverseRelated;
player->m_maybeReverseSpeed = m_maybeReverseSpeed;
player->m_maybeReverseAcceleration = m_maybeReverseAcceleration;
player->m_xVelocityRelated2 = m_xVelocityRelated2;
player->m_isDashing = m_isDashing;
player->m_unk9e8 = m_unk9e8;
player->m_groundObjectMaterial = m_groundObjectMaterial;
player->m_vehicleSize = m_vehicleSize;
player->m_playerSpeed = m_playerSpeed;
player->m_shipRotation = m_shipRotation;
player->m_lastPortalPos = m_lastPortalPos;
player->m_unkUnused3 = m_unkUnused3;
player->m_isOnGround2 = m_isOnGround2;
player->m_lastLandTime = m_lastLandTime;
player->m_platformerVelocityRelated = m_platformerVelocityRelated;
player->m_maybeIsBoosted = m_maybeIsBoosted;
player->m_scaleXRelatedTime = m_scaleXRelatedTime;
player->m_decreaseBoostSlide = m_decreaseBoostSlide;
player->m_unkA29 = m_unkA29;
player->m_isLocked = m_isLocked;
player->m_controlsDisabled = m_controlsDisabled;
player->m_lastGroundedPos = m_lastGroundedPos;
player->m_lastActivatedPortal = m_lastActivatedPortal;
player->m_hasEverJumped = m_hasEverJumped;
player->m_hasEverHitRing = m_hasEverHitRing;
player->m_playerColor1 = m_playerColor1;
player->m_playerColor2 = m_playerColor2;
player->m_isSecondPlayer = m_isSecondPlayer;
player->m_unkA99 = m_unkA99;
player->m_isBeingSpawnedByDualPortal = m_isBeingSpawnedByDualPortal;
player->m_audioScale = m_audioScale;
player->m_unkAngle1 = m_unkAngle1;
player->m_yVelocityRelated3 = m_yVelocityRelated3;
player->m_defaultMiniIcon = m_defaultMiniIcon;
player->m_swapColors = m_swapColors;
player->m_switchDashFireColor = m_switchDashFireColor;
player->m_followRelated = m_followRelated;
player->m_unk838 = m_unk838;
player->m_stateOnGround = m_stateOnGround;
player->m_stateUnk = m_stateUnk;
player->m_stateNoStickX = m_stateNoStickX;
player->m_stateNoStickY = m_stateNoStickY;
player->m_stateUnk2 = m_stateUnk2;
player->m_stateBoostX = m_stateBoostX;
player->m_stateBoostY = m_stateBoostY;
player->m_maybeStateForce2 = m_maybeStateForce2;
player->m_stateScale = m_stateScale;
player->m_platformerXVelocity = m_platformerXVelocity;
player->m_holdingRight = m_holdingRight;
player->m_holdingLeft = m_holdingLeft;
player->m_leftPressedFirst = m_leftPressedFirst;
player->m_scaleXRelated = m_scaleXRelated;
player->m_maybeHasStopped = m_maybeHasStopped;
player->m_xVelocityRelated = m_xVelocityRelated;
player->m_maybeGoingCorrectSlopeDirection = m_maybeGoingCorrectSlopeDirection;
player->m_isSliding = m_isSliding;
player->m_maybeSlopeForce = m_maybeSlopeForce;
player->m_isOnIce = m_isOnIce;
player->m_physDeltaRelated = m_physDeltaRelated;
player->m_isOnGround4 = m_isOnGround4;
player->m_maybeSlidingTime = m_maybeSlidingTime;
player->m_maybeSlidingStartTime = m_maybeSlidingStartTime;
player->m_changedDirectionsTime = m_changedDirectionsTime;
player->m_slopeEndTime = m_slopeEndTime;
player->m_isMoving = m_isMoving;
player->m_platformerMovingLeft = m_platformerMovingLeft;
player->m_platformerMovingRight = m_platformerMovingRight;
player->m_isSlidingRight = m_isSlidingRight;
player->m_maybeChangedDirectionAngle = m_maybeChangedDirectionAngle;
player->m_unkUnused2 = m_unkUnused2;
player->m_stateNoAutoJump = m_stateNoAutoJump;
player->m_stateDartSlide = m_stateDartSlide;
player->m_stateHitHead = m_stateHitHead;
player->m_stateFlipGravity = m_stateFlipGravity;
player->m_gravityMod = m_gravityMod;
player->m_stateForce = m_stateForce;
player->m_stateForceVector = m_stateForceVector;
player->m_affectedByForces = m_affectedByForces;
player->m_somethingPlayerSpeedTime = m_somethingPlayerSpeedTime;
player->m_playerSpeedAC = m_playerSpeedAC;
player->m_fixRobotJump = m_fixRobotJump;
player->m_inputsLocked = m_inputsLocked;
player->m_gv0123 = m_gv0123;
player->m_iconRequestID = m_iconRequestID;
player->m_unkUnused = m_unkUnused;
player->m_isOutOfBounds = m_isOutOfBounds;
player->m_fallStartY = m_fallStartY;
player->m_disablePlayerSqueeze = m_disablePlayerSqueeze;
player->m_robotAnimation1Enabled = m_robotAnimation1Enabled;
player->m_robotAnimation2Enabled = m_robotAnimation2Enabled;
player->m_spiderAnimationEnabled = m_spiderAnimationEnabled;
player->m_position = m_position;
player->setPosition(m_position);
player->setRotation(m_rotation);
#ifndef GEODE_IS_ANDROID
player->m_rotateObjectsRelated = m_rotateObjectsRelated;
player->m_maybeRotatedObjectsMap = m_maybeRotatedObjectsMap;
player->m_ringRelatedSet = m_ringRelatedSet;
player->m_touchedRings = m_touchedRings;
player->m_jumpPadRelated = m_jumpPadRelated;
player->m_playerFollowFloats = m_playerFollowFloats;
player->m_currentRobotAnimation = m_currentRobotAnimation;
player->m_touchingRings->removeAllObjects();
for (CCObject* obj : m_touchingRings)
player->m_touchingRings->addObject(obj);
#endif
}
private:
cocos2d::CCPoint m_position;
float m_rotation;
bool m_wasTeleported;
bool m_fixGravityBug;
bool m_reverseSync;
double m_yVelocityBeforeSlope;
double m_dashX;
double m_dashY;
double m_dashAngle;
double m_dashStartTime;
double m_slopeStartTime;
bool m_justPlacedStreak;
cocos2d::CCNode* m_maybeLastGroundObject;
int m_lastCollisionBottom;
int m_lastCollisionTop;
int m_lastCollisionLeft;
int m_lastCollisionRight;
int m_unk50C;
int m_unk510;
GameObject* m_currentSlope2;
GameObject* m_preLastGroundObject;
float m_slopeAngle;
bool m_slopeSlidingMaybeRotated;
bool m_quickCheckpointMode;
GameObject* m_collidedObject;
GameObject* m_lastGroundObject;
GameObject* m_collidingWithLeft;
GameObject* m_collidingWithRight;
int m_maybeSavedPlayerFrame;
double m_scaleXRelated2;
double m_groundYVelocity;
double m_yVelocityRelated;
double m_scaleXRelated3;
double m_scaleXRelated4;
double m_scaleXRelated5;
bool m_isCollidingWithSlope;
bool m_isBallRotating;
bool m_unk669;
GameObject* m_currentSlope3;
GameObject* m_currentSlope;
double unk_584;
int m_collidingWithSlopeId;
bool m_slopeFlipGravityRelated;
float m_slopeAngleRadians;
float m_rotationSpeed;
float m_rotateSpeed;
bool m_isRotating;
bool m_isBallRotating2;
bool m_hasGlow;
bool m_isHidden;
GhostType m_ghostType;
double m_speedMultiplier;
double m_yStart;
double m_gravity;
float m_trailingParticleLife;
float m_unk648;
double m_gameModeChangedTime;
bool m_padRingRelated;
bool m_maybeReducedEffects;
bool m_maybeIsFalling;
bool m_shouldTryPlacingCheckpoint;
bool m_playEffects;
bool m_maybeCanRunIntoBlocks;
bool m_hasGroundParticles;
bool m_hasShipParticles;
bool m_isOnGround3;
bool m_checkpointTimeout;
double m_lastCheckpointTime;
double m_lastJumpTime;
double m_lastFlipTime;
double m_flashTime;
float m_flashRelated;
float m_flashRelated1;
cocos2d::ccColor3B m_colorRelated2;
cocos2d::ccColor3B m_flashRelated3;
double m_lastSpiderFlipTime;
bool m_unkBool5;
bool m_maybeIsVehicleGlowing;
bool m_switchWaveTrailColor;
bool m_practiceDeathEffect;
double m_accelerationOrSpeed;
double m_snapDistance;
bool m_ringJumpRelated;
GameObject* m_objectSnappedTo;
CheckpointObject* m_pendingCheckpoint;
int m_onFlyCheckpointTries;
bool m_maybeSpriteRelated;
bool m_useLandParticles0;
float m_landParticlesAngle;
float m_landParticleRelatedY;
int m_playerStreak;
float m_streakStrokeWidth;
bool m_disableStreakTint;
bool m_alwaysShowStreak;
ShipStreak m_shipStreakType;
double m_slopeRotation;
double m_currentSlopeYVelocity;
double m_unk3d0;
double m_blackOrbRelated;
bool m_unk3e0;
bool m_unk3e1;
bool m_isAccelerating;
bool m_isCurrentSlopeTop;
double m_collidedTopMinY;
double m_collidedBottomMaxY;
double m_collidedLeftMaxX;
double m_collidedRightMinX;
bool m_fadeOutStreak;
// bool m_canPlaceCheckpoint; (breaking)
cocos2d::ccColor3B m_colorRelated;
cocos2d::ccColor3B m_secondColorRelated;
bool m_hasCustomGlowColor;
cocos2d::ccColor3B m_glowColor;
bool m_maybeIsColliding;
// bool m_jumpBuffered; (breaking)
bool m_stateRingJump;
bool m_wasJumpBuffered;
bool m_wasRobotJump;
unsigned char m_stateJumpBuffered;
bool m_stateRingJump2;
bool m_touchedRing;
bool m_touchedCustomRing;
bool m_touchedGravityPortal;
bool m_maybeTouchedBreakableBlock;
geode::SeedValueRSV m_jumpRelatedAC2;
bool m_touchedPad;
double m_yVelocity;
double m_fallSpeed;
bool m_isOnSlope;
bool m_wasOnSlope;
float m_slopeVelocity;
bool m_maybeUpsideDownSlope;
bool m_isShip;
bool m_isBird;
bool m_isBall;
bool m_isDart;
bool m_isRobot;
bool m_isSpider;
bool m_isUpsideDown;
bool m_isDead;
bool m_isOnGround;
bool m_isGoingLeft;
bool m_isSideways;
bool m_isSwing;
int m_reverseRelated;
double m_maybeReverseSpeed;
double m_maybeReverseAcceleration;
float m_xVelocityRelated2;
bool m_isDashing;
int m_unk9e8;
int m_groundObjectMaterial;
float m_vehicleSize;
float m_playerSpeed;
cocos2d::CCPoint m_shipRotation;
cocos2d::CCPoint m_lastPortalPos;
float m_unkUnused3;
bool m_isOnGround2;
double m_lastLandTime;
float m_platformerVelocityRelated;
bool m_maybeIsBoosted;
double m_scaleXRelatedTime;
bool m_decreaseBoostSlide;
bool m_unkA29;
bool m_isLocked;
bool m_controlsDisabled;
cocos2d::CCPoint m_lastGroundedPos;
GameObject* m_lastActivatedPortal;
bool m_hasEverJumped;
bool m_hasEverHitRing;
cocos2d::ccColor3B m_playerColor1;
cocos2d::ccColor3B m_playerColor2;
bool m_isSecondPlayer;
bool m_unkA99;
bool m_isBeingSpawnedByDualPortal;
float m_audioScale;
float m_unkAngle1;
float m_yVelocityRelated3;
bool m_defaultMiniIcon;
bool m_swapColors;
bool m_switchDashFireColor;
int m_followRelated;
float m_unk838;
int m_stateOnGround;
unsigned char m_stateUnk;
unsigned char m_stateNoStickX;
unsigned char m_stateNoStickY;
unsigned char m_stateUnk2;
int m_stateBoostX;
int m_stateBoostY;
int m_maybeStateForce2;
int m_stateScale;
double m_platformerXVelocity;
bool m_holdingRight;
bool m_holdingLeft;
bool m_leftPressedFirst;
double m_scaleXRelated;
bool m_maybeHasStopped;
float m_xVelocityRelated;
bool m_maybeGoingCorrectSlopeDirection;
bool m_isSliding;
double m_maybeSlopeForce;
bool m_isOnIce;
double m_physDeltaRelated;
bool m_isOnGround4;
int m_maybeSlidingTime;
double m_maybeSlidingStartTime;
double m_changedDirectionsTime;
double m_slopeEndTime;
bool m_isMoving;
bool m_platformerMovingLeft;
bool m_platformerMovingRight;
bool m_isSlidingRight;
double m_maybeChangedDirectionAngle;
double m_unkUnused2;
int m_stateNoAutoJump;
int m_stateDartSlide;
int m_stateHitHead;
int m_stateFlipGravity;
float m_gravityMod;
int m_stateForce;
cocos2d::CCPoint m_stateForceVector;
bool m_affectedByForces;
float m_somethingPlayerSpeedTime;
float m_playerSpeedAC;
bool m_fixRobotJump;
// gd::map<int, bool> m_holdingButtons; (breaking)
bool m_inputsLocked;
bool m_gv0123;
int m_iconRequestID;
int m_unkUnused;
bool m_isOutOfBounds;
float m_fallStartY;
bool m_disablePlayerSqueeze;
bool m_robotAnimation1Enabled;
bool m_robotAnimation2Enabled;
bool m_spiderAnimationEnabled;
// these dont work well on android
// (P.S. robtop pls update NDK)
#ifndef GEODE_IS_ANDROID
std::unordered_map<int, GJPointDouble> m_rotateObjectsRelated;
std::unordered_map<int, GameObject*> m_maybeRotatedObjectsMap;
std::unordered_set<int> m_ringRelatedSet;
std::unordered_set<int> m_touchedRings;
std::map<int, bool> m_jumpPadRelated;
std::vector<float> m_playerFollowFloats;
std::vector<CCObject*> m_touchingRings;
std::string m_currentRobotAnimation;
#endif
};
}
| 412 | 0.570428 | 1 | 0.570428 | game-dev | MEDIA | 0.911312 | game-dev | 0.903283 | 1 | 0.903283 |
andrei1058/BedWars1058 | 11,843 | bedwars-plugin/src/main/java/com/andrei1058/bedwars/arena/tasks/GamePlayingTask.java | /*
* BedWars1058 - A bed wars mini-game.
* Copyright (C) 2021 Andrei Dascălu
*
* 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/>.
*
* Contact e-mail: andrew.dascalu@gmail.com
*/
package com.andrei1058.bedwars.arena.tasks;
import com.andrei1058.bedwars.BedWars;
import com.andrei1058.bedwars.api.arena.GameState;
import com.andrei1058.bedwars.api.arena.IArena;
import com.andrei1058.bedwars.api.arena.generator.IGenerator;
import com.andrei1058.bedwars.api.arena.team.ITeam;
import com.andrei1058.bedwars.api.configuration.ConfigPath;
import com.andrei1058.bedwars.api.events.player.PlayerInvisibilityPotionEvent;
import com.andrei1058.bedwars.api.language.Language;
import com.andrei1058.bedwars.api.language.Messages;
import com.andrei1058.bedwars.api.tasks.PlayingTask;
import com.andrei1058.bedwars.arena.Arena;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
import java.util.Map;
import static com.andrei1058.bedwars.BedWars.nms;
import static com.andrei1058.bedwars.api.language.Language.getMsg;
public class GamePlayingTask implements Runnable, PlayingTask {
private Arena arena;
private BukkitTask task;
private int beds_destroy_countdown, dragon_spawn_countdown, game_end_countdown;
public GamePlayingTask(Arena arena) {
this.arena = arena;
this.beds_destroy_countdown = BedWars.config.getInt(ConfigPath.GENERAL_CONFIGURATION_BEDS_DESTROY_COUNTDOWN);
this.dragon_spawn_countdown = BedWars.config.getInt(ConfigPath.GENERAL_CONFIGURATION_DRAGON_SPAWN_COUNTDOWN);
this.game_end_countdown = BedWars.config.getInt(ConfigPath.GENERAL_CONFIGURATION_GAME_END_COUNTDOWN);
this.task = Bukkit.getScheduler().runTaskTimer(BedWars.plugin, this, 0, 20L);
}
public Arena getArena() {
return arena;
}
@Override
public BukkitTask getBukkitTask() {
return task;
}
/**
* Get task ID
*/
public int getTask() {
return task.getTaskId();
}
public int getBedsDestroyCountdown() {
return beds_destroy_countdown;
}
public int getDragonSpawnCountdown() {
return dragon_spawn_countdown;
}
public int getGameEndCountdown() {
return game_end_countdown;
}
@Override
public void run() {
switch (getArena().getNextEvent()) {
case EMERALD_GENERATOR_TIER_II:
case EMERALD_GENERATOR_TIER_III:
case DIAMOND_GENERATOR_TIER_II:
case DIAMOND_GENERATOR_TIER_III:
if (getArena().upgradeDiamondsCount > 0) {
getArena().upgradeDiamondsCount--;
if (getArena().upgradeDiamondsCount == 0) {
getArena().updateNextEvent();
}
}
if (getArena().upgradeEmeraldsCount > 0) {
getArena().upgradeEmeraldsCount--;
if (getArena().upgradeEmeraldsCount == 0) {
getArena().updateNextEvent();
}
}
break;
case BEDS_DESTROY:
beds_destroy_countdown--;
if (getBedsDestroyCountdown() == 0) {
for (Player p : getArena().getPlayers()) {
nms.sendTitle(p, getMsg(p, Messages.NEXT_EVENT_TITLE_ANNOUNCE_BEDS_DESTROYED), getMsg(p, Messages.NEXT_EVENT_SUBTITLE_ANNOUNCE_BEDS_DESTROYED), 0, 40, 10);
p.sendMessage(getMsg(p, Messages.NEXT_EVENT_CHAT_ANNOUNCE_BEDS_DESTROYED));
}
for (Player p : getArena().getSpectators()) {
nms.sendTitle(p, getMsg(p, Messages.NEXT_EVENT_TITLE_ANNOUNCE_BEDS_DESTROYED), getMsg(p, Messages.NEXT_EVENT_SUBTITLE_ANNOUNCE_BEDS_DESTROYED), 0, 40, 10);
p.sendMessage(getMsg(p, Messages.NEXT_EVENT_CHAT_ANNOUNCE_BEDS_DESTROYED));
}
for (ITeam t : getArena().getTeams()) {
t.setBedDestroyed(true);
}
getArena().updateNextEvent();
}
break;
case ENDER_DRAGON:
dragon_spawn_countdown--;
if (getDragonSpawnCountdown() == 0) {
for (Player p : getArena().getPlayers()) {
nms.sendTitle(p, getMsg(p, Messages.NEXT_EVENT_TITLE_ANNOUNCE_SUDDEN_DEATH), getMsg(p, Messages.NEXT_EVENT_SUBTITLE_ANNOUNCE_SUDDEN_DEATH), 0, 40, 10);
for (ITeam t : getArena().getTeams()) {
if (t.getMembers().isEmpty()) continue;
p.sendMessage(getMsg(p, Messages.NEXT_EVENT_CHAT_ANNOUNCE_SUDDEN_DEATH).replace("{TeamDragons}", String.valueOf(t.getDragons()))
.replace("{TeamColor}", t.getColor().chat().toString()).replace("{TeamName}", t.getDisplayName(Language.getPlayerLanguage(p))));
}
}
for (Player p : getArena().getSpectators()) {
nms.sendTitle(p, getMsg(p, Messages.NEXT_EVENT_TITLE_ANNOUNCE_SUDDEN_DEATH), getMsg(p, Messages.NEXT_EVENT_SUBTITLE_ANNOUNCE_SUDDEN_DEATH), 0, 40, 10);
for (ITeam t : getArena().getTeams()) {
if (t.getMembers().isEmpty()) continue;
p.sendMessage(getMsg(p, Messages.NEXT_EVENT_CHAT_ANNOUNCE_SUDDEN_DEATH).replace("{TeamDragons}", String.valueOf(t.getDragons()))
.replace("{TeamColor}", t.getColor().chat().toString()).replace("{TeamName}", t.getDisplayName(Language.getPlayerLanguage(p))));
}
}
getArena().updateNextEvent();
for (ITeam team : arena.getTeams()){
for (IGenerator o : team.getGenerators()) {
Location l = o.getLocation();
for (int y = 0; y < 20; y++) {
l.clone().subtract(0, y, 0).getBlock().setType(Material.AIR);
}
}
}
for (ITeam t : getArena().getTeams()) {
if (t.getMembers().isEmpty()) continue;
for (int x = 0; x < t.getDragons(); x++) {
nms.spawnDragon(getArena().getConfig().getArenaLoc("waiting.Loc").add(0, 10, 0), t);
}
}
}
break;
case GAME_END:
game_end_countdown--;
if (getGameEndCountdown() == 0) {
getArena().checkWinner();
getArena().changeStatus(GameState.restarting);
}
break;
}
int distance = 0;
for (ITeam t : getArena().getTeams()) {
if (t.getSize() > 1) {
for (Player p : t.getMembers()) {
for (Player p2 : t.getMembers()) {
if (p2 == p) continue;
if (distance == 0) {
distance = (int) p.getLocation().distance(p2.getLocation());
} else if ((int) p.getLocation().distance(p2.getLocation()) < distance) {
distance = (int) p.getLocation().distance(p2.getLocation());
}
}
nms.playAction(p, getMsg(p, Messages.FORMATTING_ACTION_BAR_TRACKING).replace("{team}", t.getColor().chat() + t.getDisplayName(Language.getPlayerLanguage(p)))
.replace("{distance}", t.getColor().chat().toString() + distance).replace("&", "§"));
}
}
// spawn items
for (IGenerator o : t.getGenerators()) {
o.spawn();
}
}
/* AFK SYSTEM FOR PLAYERS */
int current = 0;
for (Player p : getArena().getPlayers()) {
if (Arena.afkCheck.get(p.getUniqueId()) == null) {
Arena.afkCheck.put(p.getUniqueId(), current);
} else {
current = Arena.afkCheck.get(p.getUniqueId());
current++;
Arena.afkCheck.replace(p.getUniqueId(), current);
if (current == 45) {
BedWars.getAPI().getAFKUtil().setPlayerAFK(p, true);
}
}
}
/* RESPAWN SESSION */
if (!getArena().getRespawnSessions().isEmpty()) {
for (Map.Entry<Player, Integer> e : getArena().getRespawnSessions().entrySet()) {
if (e.getValue() <= 0) {
IArena a = Arena.getArenaByPlayer(e.getKey());
if (a == null) {
getArena().getRespawnSessions().remove(e.getKey());
continue;
}
ITeam t = a.getTeam(e.getKey());
if (t == null){
a.addSpectator(e.getKey(), true, null);
} else {
t.respawnMember(e.getKey());
e.getKey().setAllowFlight(false);
e.getKey().setFlying(false);
}
} else {
nms.sendTitle(e.getKey(), getMsg(e.getKey(), Messages.PLAYER_DIE_RESPAWN_TITLE).replace("{time}",
String.valueOf(e.getValue())), getMsg(e.getKey(), Messages.PLAYER_DIE_RESPAWN_SUBTITLE).replace("{time}",
String.valueOf(e.getValue())), 0, 30, 10);
e.getKey().sendMessage(getMsg(e.getKey(), Messages.PLAYER_DIE_RESPAWN_CHAT).replace("{time}", String.valueOf(e.getValue())));
getArena().getRespawnSessions().replace(e.getKey(), e.getValue() - 1);
}
}
}
/* INVISIBILITY FOR ARMOR */
if (!getArena().getShowTime().isEmpty()) {
for (Map.Entry<Player, Integer> e : getArena().getShowTime().entrySet()) {
if (e.getValue() <= 0) {
for (Player p : e.getKey().getWorld().getPlayers()) {
nms.showArmor(e.getKey(), p);
//nms.showPlayer(e.getKey(), p);
}
e.getKey().removePotionEffect(PotionEffectType.INVISIBILITY);
getArena().getShowTime().remove(e.getKey());
Bukkit.getPluginManager().callEvent(new PlayerInvisibilityPotionEvent(PlayerInvisibilityPotionEvent.Type.REMOVED, getArena().getTeam(e.getKey()), e.getKey(), getArena()));
} else {
getArena().getShowTime().replace(e.getKey(), e.getValue() - 1);
}
}
}
/* SPAWN ITEMS */
for (IGenerator o : getArena().getOreGenerators()) {
o.spawn();
}
}
public void cancel() {
task.cancel();
}
}
| 412 | 0.905432 | 1 | 0.905432 | game-dev | MEDIA | 0.92197 | game-dev | 0.948322 | 1 | 0.948322 |
jjbali/Extended-Experienced-PD | 2,558 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/secret/SecretWellRoom.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.levels.rooms.secret;
import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.WaterOfAwareness;
import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.WaterOfHealth;
import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.WellWater;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
public class SecretWellRoom extends SecretRoom {
private static final Class<?>[] WATERS =
{WaterOfAwareness.class, WaterOfHealth.class};
@Override
public boolean canConnect(Point p) {
//refuses connections next to corners
return super.canConnect(p) && ((p.x > left+1 && p.x < right-1) || (p.y > top+1 && p.y < bottom-1));
}
public void paint( Level level ) {
Painter.fill( level, this, Terrain.WALL );
Point door = entrance();
Point well;
if (door.x == left){
well = new Point(right-2, door.y);
} else if (door.x == right){
well = new Point(left+2, door.y);
} else if (door.y == top){
well = new Point(door.x, bottom-2);
} else {
well = new Point(door.x, top+2);
}
Painter.fill(level, well.x-1, well.y-1, 3, 3, Terrain.CHASM);
Painter.drawLine(level, door, well, Terrain.EMPTY);
Painter.set( level, well, Terrain.WELL );
@SuppressWarnings("unchecked")
Class<? extends WellWater> waterClass = (Class<? extends WellWater>) Random.element( WATERS );
WellWater.seed(well.x + level.width() * well.y, 1, waterClass, level);
entrance().set( Door.Type.HIDDEN );
}
}
| 412 | 0.778128 | 1 | 0.778128 | game-dev | MEDIA | 0.987839 | game-dev | 0.97674 | 1 | 0.97674 |
brandonmousseau/vhvr-mod | 9,166 | Unity/ValheimVR/Assets/SteamVR/InteractionSystem/Samples/Scripts/FloppyHand.cs | //======= Copyright (c) Valve Corporation, All rights reserved. ===============
using UnityEngine;
using System.Collections;
namespace Valve.VR.InteractionSystem.Sample
{
public class FloppyHand : MonoBehaviour
{
protected float fingerFlexAngle = 140;
public SteamVR_Action_Single squeezyAction = SteamVR_Input.GetAction<SteamVR_Action_Single>("Squeeze");
public SteamVR_Input_Sources inputSource;
[System.Serializable]
public class Finger
{
public float mass;
[Range(0, 1)]
public float pos;
public Vector3 forwardAxis;
public SkinnedMeshRenderer renderer;
[HideInInspector]
public SteamVR_Action_Single squeezyAction;
public SteamVR_Input_Sources inputSource;
public Transform[] bones;
public Transform referenceBone;
public Vector2 referenceAngles;
public enum eulerAxis
{
X, Y, Z
}
public eulerAxis referenceAxis;
[HideInInspector]
public float flexAngle;
private Vector3[] rotation;
private Vector3[] velocity;
private Transform[] boneTips;
private Vector3[] oldTipPosition;
private Vector3[] oldTipDelta;
private Vector3[,] inertiaSmoothing;
float squeezySmooth;
private int inertiaSteps = 10;
private float k = 400;
private float damping = 8;
private Quaternion[] startRot;
public void ApplyForce(Vector3 worldForce)
{
for (int i = 0; i < startRot.Length; i++)
{
velocity[i] += worldForce / 50;
}
}
public void Init()
{
startRot = new Quaternion[bones.Length];
rotation = new Vector3[bones.Length];
velocity = new Vector3[bones.Length];
oldTipPosition = new Vector3[bones.Length];
oldTipDelta = new Vector3[bones.Length];
boneTips = new Transform[bones.Length];
inertiaSmoothing = new Vector3[bones.Length, inertiaSteps];
for (int i = 0; i < bones.Length; i++)
{
startRot[i] = bones[i].localRotation;
if (i < bones.Length - 1)
{
boneTips[i] = bones[i + 1];
}
}
}
public void UpdateFinger(float deltaTime)
{
if (deltaTime == 0)
return;
float squeezeValue = 0;
if (squeezyAction != null && squeezyAction.GetActive(inputSource))
squeezeValue = squeezyAction.GetAxis(inputSource);
squeezySmooth = Mathf.Lerp(squeezySmooth, Mathf.Sqrt(squeezeValue), deltaTime * 10);
if (renderer.sharedMesh.blendShapeCount > 0)
{
renderer.SetBlendShapeWeight(0, squeezySmooth * 100);
}
float boneRot = 0;
if (referenceAxis == eulerAxis.X)
boneRot = referenceBone.localEulerAngles.x;
if (referenceAxis == eulerAxis.Y)
boneRot = referenceBone.localEulerAngles.y;
if (referenceAxis == eulerAxis.Z)
boneRot = referenceBone.localEulerAngles.z;
boneRot = FixAngle(boneRot);
pos = Mathf.InverseLerp(referenceAngles.x, referenceAngles.y, boneRot);
if (mass > 0)
{
for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
{
bool useOffset = boneTips[boneIndex] != null;
if (useOffset) // inertia sim
{
Vector3 offset = (boneTips[boneIndex].localPosition - bones[boneIndex].InverseTransformPoint(oldTipPosition[boneIndex])) / deltaTime;
Vector3 inertia = (offset - oldTipDelta[boneIndex]) / deltaTime;
oldTipDelta[boneIndex] = offset;
Vector3 drag = offset * -2;
inertia *= -2f;
for (int offsetIndex = inertiaSteps - 1; offsetIndex > 0; offsetIndex--) // offset inertia steps
{
inertiaSmoothing[boneIndex, offsetIndex] = inertiaSmoothing[boneIndex, offsetIndex - 1];
}
inertiaSmoothing[boneIndex, 0] = inertia;
Vector3 smoothedInertia = Vector3.zero;
for (int offsetIndex = 0; offsetIndex < inertiaSteps; offsetIndex++) // offset inertia steps
{
smoothedInertia += inertiaSmoothing[boneIndex, offsetIndex];
}
smoothedInertia = smoothedInertia / inertiaSteps;
//if (boneIndex == 0 && Input.GetKey(KeyCode.Space))
// Debug.Log(smoothedInertia);
smoothedInertia = PowVector(smoothedInertia / 20, 3) * 20;
Vector3 forward = forwardAxis;
Vector3 forwardDrag = forwardAxis + drag;
Vector3 forwardInertia = forwardAxis + smoothedInertia;
Quaternion dragQuaternion = Quaternion.FromToRotation(forward, forwardDrag);
Quaternion inertiaQuaternion = Quaternion.FromToRotation(forward, forwardInertia);
velocity[boneIndex] += FixVector(dragQuaternion.eulerAngles) * 2 * deltaTime;
velocity[boneIndex] += FixVector(inertiaQuaternion.eulerAngles) * 50 * deltaTime;
velocity[boneIndex] = Vector3.ClampMagnitude(velocity[boneIndex], 1000);
}
Vector3 targetPos = pos * Vector3.right * (flexAngle / bones.Length);
Vector3 springForce = -k * (rotation[boneIndex] - targetPos);
var dampingForce = damping * velocity[boneIndex];
var force = springForce - dampingForce;
var acceleration = force / mass;
velocity[boneIndex] += acceleration * deltaTime;
rotation[boneIndex] += velocity[boneIndex] * Time.deltaTime;
rotation[boneIndex] = Vector3.ClampMagnitude(rotation[boneIndex], 180);
if (useOffset)
{
oldTipPosition[boneIndex] = boneTips[boneIndex].position;
}
}
}
else
{
Debug.LogError("<b>[SteamVR Interaction]</b> finger mass is zero");
}
}
public void ApplyTransforms()
{
for (int i = 0; i < bones.Length; i++)
{
bones[i].localRotation = startRot[i];
bones[i].Rotate(rotation[i], Space.Self);
}
}
private Vector3 FixVector(Vector3 ang)
{
return new Vector3(FixAngle(ang.x), FixAngle(ang.y), FixAngle(ang.z));
}
private float FixAngle(float ang)
{
if (ang > 180)
ang = -360 + ang;
return ang;
}
private Vector3 PowVector(Vector3 vector, float power)
{
Vector3 sign = new Vector3(Mathf.Sign(vector.x), Mathf.Sign(vector.y), Mathf.Sign(vector.z));
vector.x = Mathf.Pow(Mathf.Abs(vector.x), power) * sign.x;
vector.y = Mathf.Pow(Mathf.Abs(vector.y), power) * sign.y;
vector.z = Mathf.Pow(Mathf.Abs(vector.z), power) * sign.z;
return vector;
}
}
public Finger[] fingers;
public Vector3 constforce;
private void Start()
{
for (int fingerIndex = 0; fingerIndex < fingers.Length; fingerIndex++)
{
fingers[fingerIndex].Init();
fingers[fingerIndex].flexAngle = fingerFlexAngle;
fingers[fingerIndex].squeezyAction = squeezyAction;
fingers[fingerIndex].inputSource = inputSource;
}
}
private void Update()
{
for (int fingerIndex = 0; fingerIndex < fingers.Length; fingerIndex++)
{
fingers[fingerIndex].ApplyForce(constforce);
fingers[fingerIndex].UpdateFinger(Time.deltaTime);
fingers[fingerIndex].ApplyTransforms();
}
}
}
} | 412 | 0.924258 | 1 | 0.924258 | game-dev | MEDIA | 0.984467 | game-dev | 0.981361 | 1 | 0.981361 |
LoneGazebo/Community-Patch-DLL | 8,728 | (2) Vox Populi/Mapscripts/EMP/Donut.lua | -------------------------------------------------------------------------------
-- FILE: Donut.lua
-- AUTHOR: Bob Thomas (Sirian)
-- PURPOSE: Global map script - Circular continent with center region.
-------------------------------------------------------------------------------
-- Copyright (c) 2011 Firaxis Games, Inc. All rights reserved.
-------------------------------------------------------------------------------
include("MapGenerator");
include("MultilayeredFractal");
include("TerrainGenerator");
include("FeatureGenerator");
------------------------------------------------------------------------------
function GetMapScriptInfo()
local world_age, temperature, rainfall, sea_level, resources = GetCoreMapOptions()
return {
Name = "TXT_KEY_MAP_DONUT",
Description = "TXT_KEY_MAP_DONUT_HELP",
IconIndex = 18,
IconAtlas = "WORLDTYPE_ATLAS_3",
SupportsMultiplayer = true,
Folder = "MAP_FOLDER_SP_DLC_1",
CustomOptions = {
{
Name = "TXT_KEY_MAP_OPTION_CENTER_REGION",
Values = {
"TXT_KEY_MAP_OPTION_HILLS",
"TXT_KEY_MAP_OPTION_MOUNTAINS",
"TXT_KEY_MAP_OPTION_OCEAN",
"TXT_KEY_MAP_OPTION_DESERT",
"TXT_KEY_MAP_OPTION_STANDARD",
"TXT_KEY_MAP_OPTION_RANDOM",
},
DefaultValue = 3,
SortPriority = 1,
},
}
};
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
function GetMapInitData(worldSize)
-- Donut uses a square map grid.
local worldsizes = {
[GameInfo.Worlds.WORLDSIZE_DUEL.ID] = {24, 24},
[GameInfo.Worlds.WORLDSIZE_TINY.ID] = {36, 36},
[GameInfo.Worlds.WORLDSIZE_SMALL.ID] = {44, 44},
[GameInfo.Worlds.WORLDSIZE_STANDARD.ID] = {52, 52},
[GameInfo.Worlds.WORLDSIZE_LARGE.ID] = {64, 64},
[GameInfo.Worlds.WORLDSIZE_HUGE.ID] = {80, 80}
}
local grid_size = worldsizes[worldSize];
--
local world = GameInfo.Worlds[worldSize];
if(world ~= nil) then
return {
Width = grid_size[1],
Height = grid_size[2],
WrapX = false,
};
end
end
------------------------------------------------------------------------------
-------------------------------------------------------------------------------
function MultilayeredFractal:GeneratePlotsByRegion()
-- Sirian's MultilayeredFractal controlling function.
-- You -MUST- customize this function for each script using MultilayeredFractal.
--
-- This implementation is specific to Donut.
local iW, iH = Map.GetGridSize();
local fracFlags = {FRAC_WRAP_X = false, FRAC_POLAR = true};
-- Get user input.
hole_type = Map.GetCustomOption(1) -- Global
if hole_type == 6 then
hole_type = 1 + Map.Rand(5, "Random terrain type for center region - Donut Lua");
end
local worldsizes = {
[GameInfo.Worlds.WORLDSIZE_DUEL.ID] = 3,
[GameInfo.Worlds.WORLDSIZE_TINY.ID] = 4,
[GameInfo.Worlds.WORLDSIZE_SMALL.ID] = 4,
[GameInfo.Worlds.WORLDSIZE_STANDARD.ID] = 5,
[GameInfo.Worlds.WORLDSIZE_LARGE.ID] = 5,
[GameInfo.Worlds.WORLDSIZE_HUGE.ID] = 6,
};
local grain = worldsizes[Map.GetWorldSize()];
local terrainFrac = Fractal.Create(iW, iH, grain, fracFlags, -1, -1);
local iHillsThreshold = terrainFrac:GetHeight(91);
local iPeaksThreshold = terrainFrac:GetHeight(96);
local iHillsClumps = terrainFrac:GetHeight(4);
local hillsFrac = Fractal.Create(iW, iH, grain, fracFlags, -1, -1);
local iHillsBottom1 = hillsFrac:GetHeight(20);
local iHillsTop1 = hillsFrac:GetHeight(30);
local iHillsBottom2 = hillsFrac:GetHeight(70);
local iHillsTop2 = hillsFrac:GetHeight(80);
local iCenterX = math.floor(iW / 2);
local iCenterY = math.floor(iH / 2);
local iRadius = iCenterX - 4;
local iHoleRadius = math.floor(iRadius / 2);
for y = 0, iH - 1 do
for x = 0, iW - 1 do
local i = y * iW + x + 1;
local fDistance = 0;
if x ~= iCenterX or y ~= iCenterY then
fDistance = math.sqrt(((x - iCenterX) ^ 2) + ((y - iCenterY) ^ 2));
end
if fDistance > iRadius then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_OCEAN;
elseif fDistance < iHoleRadius and hole_type < 4 then -- Plot is in hole of donut.
if hole_type == 1 then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_HILLS;
elseif hole_type == 2 then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_MOUNTAIN;
else
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_OCEAN;
end
else
local val = terrainFrac:GetHeight(x, y);
local hillsVal = hillsFrac:GetHeight(x, y);
if val >= iPeaksThreshold then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_MOUNTAIN;
elseif val >= iHillsThreshold or val <= iHillsClumps then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_HILLS;
elseif hillsVal >= iHillsBottom1 and hillsVal <= iHillsTop1 then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_HILLS;
elseif hillsVal >= iHillsBottom2 and hillsVal <= iHillsTop2 then
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_HILLS;
else
self.wholeworldPlotTypes[i] = PlotTypes.PLOT_LAND;
end
end
end
end
-- Plot Type generation completed. Return global plot array.
return self.wholeworldPlotTypes
end
------------------------------------------------------------------------------
function GeneratePlotTypes()
print("Setting Plot Types (Lua Donut) ...");
local layered_world = MultilayeredFractal.Create();
local plotsDonut = layered_world:GeneratePlotsByRegion();
SetPlotTypes(plotsDonut);
GenerateCoasts();
end
------------------------------------------------------------------------------
----------------------------------------------------------------------------------
function TerrainGenerator:GenerateTerrainAtPlot(iX, iY)
local plot = Map.GetPlot(iX, iY);
if (plot:IsWater()) then
local val = plot:GetTerrainType();
if val == TerrainTypes.NO_TERRAIN then -- Error handling.
val = self.terrainGrass;
plot:SetPlotType(PlotTypes.PLOT_LAND, false, false);
end
return val;
end
local iW, iH = Map.GetGridSize();
local iCenterX = math.floor(iW / 2);
local iCenterY = math.floor(iH / 2);
local iRadius = iCenterX - 4;
local iHoleRadius = math.floor(iRadius / 2);
local terrainVal = self.terrainGrass;
local fDistance = 0;
if iX ~= iCenterX or iY ~= iCenterY then
fDistance = math.sqrt(((iX - iCenterX) ^ 2) + ((iY - iCenterY) ^ 2));
end
if fDistance < iHoleRadius and hole_type == 4 then -- Desert plot in center.
terrainVal = self.terrainDesert;
else
local desertVal = self.deserts:GetHeight(iX, iY);
local plainsVal = self.plains:GetHeight(iX, iY);
if ((desertVal >= self.iDesertBottom) and (desertVal <= self.iDesertTop)) then
terrainVal = self.terrainDesert;
elseif ((plainsVal >= self.iPlainsBottom) and (plainsVal <= self.iPlainsTop)) then
terrainVal = self.terrainPlains;
end
end
return terrainVal;
end
----------------------------------------------------------------------------------
function GenerateTerrain()
print("Generating Terrain (Lua Donut) ...");
local terraingen = TerrainGenerator.Create();
terrainTypes = terraingen:GenerateTerrain();
SetTerrainTypes(terrainTypes);
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
function FeatureGenerator:AddIceAtPlot(plot, iX, iY, lat)
-- No ice.
end
------------------------------------------------------------------------------
function FeatureGenerator:AddJunglesAtPlot(plot, iX, iY, lat)
-- No jungle.
end
------------------------------------------------------------------------------
function AddFeatures()
print("Adding Features (Lua Donut) ...");
local featuregen = FeatureGenerator.Create();
-- False parameter removes mountains from coastlines.
featuregen:AddFeatures(false);
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
function StartPlotSystem()
print("Creating start plot database.");
local start_plot_database = AssignStartingPlots.Create()
print("Dividing the map in to Regions.");
-- Regional Division Method 1: Biggest Landmass
local args = {
method = 1,
};
start_plot_database:GenerateRegions(args)
print("Choosing start locations for civilizations.");
local args = {
mustBeCoast = true,
};
start_plot_database:ChooseLocations(args)
print("Normalizing start locations and assigning them to Players.");
start_plot_database:BalanceAndAssign()
print("Placing Natural Wonders.");
start_plot_database:PlaceNaturalWonders()
print("Placing Resources and City States.");
start_plot_database:PlaceResourcesAndCityStates()
end
------------------------------------------------------------------------------
| 412 | 0.729192 | 1 | 0.729192 | game-dev | MEDIA | 0.773133 | game-dev | 0.837559 | 1 | 0.837559 |
Secrets-of-Sosaria/World | 2,110 | Data/Scripts/Mobiles/Civilized/Citizens/TrainingBow.cs | using System;
using Server;
using Server.ContextMenus;
using System.Collections;
using System.Collections.Generic;
using Server.Network;
using System.Text;
using Server.Items;
using Server.Mobiles;
namespace Server.Mobiles
{
public class TrainingBow : Citizens
{
[Constructable]
public TrainingBow()
{
Blessed = true;
CantWalk = true;
AI = AIType.AI_Melee;
}
public override void OnMovement( Mobile m, Point3D oldLocation )
{
}
public override void OnThink()
{
if ( DateTime.Now >= m_NextTalk )
{
foreach ( Item hay in this.GetItemsInRange( 6 ) )
{
if ( hay is ArcheryButte && ( hay.X == X || hay.Y == Y ) )
{
if ( this.FindItemOnLayer( Layer.FirstValid ) != null && !(this.FindItemOnLayer( Layer.FirstValid ) is BaseRanged) ) { this.Delete(); }
else if ( this.FindItemOnLayer( Layer.TwoHanded ) != null && !(this.FindItemOnLayer( Layer.TwoHanded ) is BaseRanged) ) { this.Delete(); }
hay.OnDoubleClick( this );
if ( hay.X == X ){ hay.ItemID = 0x100B; } else { hay.ItemID = 0x100A; }
m_NextTalk = (DateTime.Now + TimeSpan.FromSeconds( Utility.RandomMinMax( 2, 5 ) ));
}
}
}
}
public override void OnAfterSpawn()
{
base.OnAfterSpawn();
Server.Misc.TavernPatrons.RemoveSomeGear( this, false );
Server.Misc.MorphingTime.CheckNecromancer( this );
Item bow = new Bow();
bow.Delete();
switch ( Utility.RandomMinMax( 1, 6 ) )
{
case 1: bow = new Bow(); break;
case 2: bow = new Crossbow(); break;
case 3: bow = new HeavyCrossbow(); break;
case 4: bow = new CompositeBow(); break;
case 5: bow = new Yumi(); break;
case 6: bow = new RepeatingCrossbow(); break;
}
bow.Movable = false;
AddItem( bow );
}
public TrainingBow( Serial serial ) : base( serial )
{
}
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();
}
}
} | 412 | 0.937889 | 1 | 0.937889 | game-dev | MEDIA | 0.929699 | game-dev | 0.986199 | 1 | 0.986199 |
TartaricAcid/TouhouLittleMaid | 3,859 | src/main/java/com/github/tartaricacid/touhoulittlemaid/command/subcommand/ChatTokensCommand.java | package com.github.tartaricacid.touhoulittlemaid.command.subcommand;
import com.github.tartaricacid.touhoulittlemaid.capability.ChatTokensCapabilityProvider;
import com.github.tartaricacid.touhoulittlemaid.command.arguments.HandleTypeArgument;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import java.util.Collection;
public final class ChatTokensCommand {
private static final String TOKENS = "tokens";
private static final String GET_NAME = "get";
private static final String HANDLE_NAME = "handle";
private static final String TARGETS_NAME = "targets";
private static final String COUNT_NAME = "count";
public static LiteralArgumentBuilder<CommandSourceStack> get() {
LiteralArgumentBuilder<CommandSourceStack> pack = Commands.literal(TOKENS);
RequiredArgumentBuilder<CommandSourceStack, EntitySelector> targets = Commands.argument(TARGETS_NAME, EntityArgument.players());
RequiredArgumentBuilder<CommandSourceStack, Integer> count = Commands.argument(COUNT_NAME, IntegerArgumentType.integer(0));
RequiredArgumentBuilder<CommandSourceStack, String> handleType = Commands.argument(HANDLE_NAME, HandleTypeArgument.type());
pack.then(Commands.literal(GET_NAME).then(targets.executes(ChatTokensCommand::getTokens)));
pack.then(handleType.then(targets.then(count.executes(ChatTokensCommand::handleTokens))));
return pack;
}
private static int handleTokens(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
Collection<ServerPlayer> players = EntityArgument.getPlayers(context, TARGETS_NAME);
int count = IntegerArgumentType.getInteger(context, COUNT_NAME);
String type = HandleTypeArgument.getType(context, HANDLE_NAME);
for (Player player : players) {
switch (type) {
case "set":
player.getCapability(ChatTokensCapabilityProvider.CHAT_TOKENS_CAP, null).ifPresent(power -> power.setCount(count));
break;
case "add":
player.getCapability(ChatTokensCapabilityProvider.CHAT_TOKENS_CAP, null).ifPresent(power -> power.addCount(count));
break;
case "min":
player.getCapability(ChatTokensCapabilityProvider.CHAT_TOKENS_CAP, null).ifPresent(power -> power.removeCount(count));
break;
default:
}
}
context.getSource().sendSuccess(() -> Component.translatable("commands.touhou_little_maid.chat_tokens.handle.info", players.size()), true);
return Command.SINGLE_SUCCESS;
}
private static int getTokens(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
for (Player player : EntityArgument.getPlayers(context, TARGETS_NAME)) {
player.getCapability(ChatTokensCapabilityProvider.CHAT_TOKENS_CAP, null).ifPresent(tokens ->
context.getSource().sendSuccess(() -> Component.translatable("commands.touhou_little_maid.chat_tokens.get.info",
player.getScoreboardName(), tokens.getCount()), false));
}
return Command.SINGLE_SUCCESS;
}
}
| 412 | 0.889451 | 1 | 0.889451 | game-dev | MEDIA | 0.975088 | game-dev | 0.962777 | 1 | 0.962777 |
lordofduct/spacepuppy-unity-framework | 4,903 | SpacepuppyBase/Collections/CooldownPool.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace com.spacepuppy.Collections
{
/// <summary>
/// Used to store temporary references for a duration of time. Call Update to update the pool
/// releasing objects that are old enough. Always call Update on the unity main thread!
/// </summary>
/// <typeparam name="T"></typeparam>
public class CooldownPool<T> : IEnumerable<CooldownPool<T>.CooldownInfo> where T : class
{
#region Fields
private Dictionary<T, CooldownInfo> _table = new Dictionary<T, CooldownInfo>();
private ITimeSupplier _time;
#endregion
#region CONSTRUCTOR
public CooldownPool()
{
}
#endregion
#region Properties
public int Count { get { return _table.Count; } }
public ITimeSupplier UpdateTimeSupplier
{
get
{
if (_time == null) _time = SPTime.Normal;
return _time;
}
set
{
if (value == null) throw new System.ArgumentNullException("value");
_time = value;
}
}
#endregion
#region Methods
public void Add(T obj, float duration)
{
CooldownInfo info;
if(_table.TryGetValue(obj, out info))
{
info.Duration += duration;
}
else
{
_table[obj] = new CooldownInfo(obj, this.UpdateTimeSupplier.Total, duration);
}
}
public bool Contains(T obj)
{
return _table.ContainsKey(obj);
}
public void Update()
{
var t = this.UpdateTimeSupplier.Total;
CooldownInfo info;
using (var toRemove = TempCollection.GetList<T>())
{
var e1 = _table.GetEnumerator();
while (e1.MoveNext())
{
info = e1.Current.Value;
if (info.Object == null || t - info.StartTime > info.Duration)
{
toRemove.Add(info.Object);
}
}
if (toRemove.Count > 0)
{
var e2 = toRemove.GetEnumerator();
while (e2.MoveNext())
{
_table.Remove(e2.Current);
}
}
}
}
public void Clear()
{
_table.Clear();
}
#endregion
#region IEnumerable Interface
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<CooldownPool<T>.CooldownInfo> IEnumerable<CooldownInfo>.GetEnumerator()
{
return this.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Special Types
public struct CooldownInfo
{
private T _obj;
private float _startTime;
private float _dur;
public CooldownInfo(T obj, float startTime, float dur)
{
_obj = obj;
_startTime = startTime;
_dur = dur;
}
public T Object { get { return _obj; } }
public float StartTime
{
get { return _startTime; }
internal set { _startTime = value; }
}
public float Duration
{
get { return _dur; }
internal set { _dur = value; }
}
}
public struct Enumerator : IEnumerator<CooldownInfo>
{
private Dictionary<T, CooldownInfo>.Enumerator _e;
public Enumerator(CooldownPool<T> pool)
{
if (pool == null) throw new System.ArgumentNullException();
_e = pool._table.GetEnumerator();
}
public CooldownInfo Current
{
get
{
return _e.Current.Value;
}
}
object IEnumerator.Current
{
get
{
return _e.Current.Value;
}
}
public void Dispose()
{
_e.Dispose();
}
public bool MoveNext()
{
return _e.MoveNext();
}
void System.Collections.IEnumerator.Reset()
{
throw new System.NotSupportedException();
}
}
#endregion
}
}
| 412 | 0.836545 | 1 | 0.836545 | game-dev | MEDIA | 0.695591 | game-dev | 0.952677 | 1 | 0.952677 |
Secrets-of-Sosaria/World | 9,757 | Data/Scripts/Items/Explorers/CamperTent.cs | using System;
using Server;
using System.Collections.Generic;
using System.Collections;
using Server.Mobiles;
using Server.Items;
using Server.Regions;
using Server.Network;
using Server.Multis;
using Server.Misc;
using Server.ContextMenus;
using Server.Gumps;
using Server.Commands;
namespace Server.Items
{
public enum CamperTentEffect
{
Charges
}
public class CampersTent : Item
{
public override string DefaultDescription{ get{ return "This is a camping tent that you can use to get away from the dangers of the land and rest. You can only use these tents if you have at least a 40 in the camping skill and they eventually wear out from use. If you double click the tent while it is in your pack, you will setup the tent for yourself. No one will be able to follow you in the tent unless they have a tent and the appropriate skill. If you set the tent down and double click it, then others will be able to use the tent to rest as they can double click the tent to follow you in. The original rolled tent will be put back into your pack, while the standing tent is left behind and will only remain for about 30 seconds so your comrades should make haste and follow you in. If anyone wants to leave the tent, then simply double click the tent flap you came in by. Anyone can stay in the tent as long as they want, but they will return to the spot where they used the tent when they leave."; } }
private CamperTentEffect m_CamperTentEffect;
private int m_Charges;
[CommandProperty( AccessLevel.GameMaster )]
public CamperTentEffect Effect
{
get{ return m_CamperTentEffect; }
set{ m_CamperTentEffect = value; InvalidateProperties(); }
}
[CommandProperty( AccessLevel.GameMaster )]
public int Charges
{
get{ return m_Charges; }
set{ m_Charges = value; InvalidateProperties(); }
}
[Constructable]
public CampersTent() : base( 0x0A59 )
{
Name = "camping tent";
Weight = 5.0;
Charges = 10;
Hue = Utility.RandomList( 0x96D, 0x96E, 0x96F, 0x970, 0x971, 0x972, 0x973, 0x974, 0x975, 0x976, 0x977, 0x978, 0x979, 0x97A, 0x97B, 0x97C, 0x97D, 0x97E );
}
public override void AddNameProperties(ObjectPropertyList list)
{
base.AddNameProperties(list);
list.Add( 1070722, "Setup A Safe Tent In Which To Rest");
list.Add( 1049644, "Usable By Those Skilled In Camping");
}
public override void OnDoubleClick( Mobile from )
{
bool inCombat = ( from.Combatant != null && from.InRange( from.Combatant.Location, 20 ) && from.Combatant.InLOS( from ) );
int CanUseTent = 0;
if ( from.Skills[SkillName.Camping].Value < 40 )
{
from.SendMessage( "You must be a novice explorer to use this tent." );
return;
}
else if ( from.Region.IsPartOf( typeof( PublicRegion ) ) )
{
from.SendMessage( "This is a really nice camping tent." );
return;
}
else if ( Server.Misc.Worlds.IsOnBoat( from ) )
{
from.SendMessage( "You cannot setup this tent near a boat." );
return;
}
else if ( Server.Misc.Worlds.IsOnSpaceship( from.Location, from.Map ) )
{
from.SendMessage( "You don't have anywhere to setup camp in this strange place." );
return;
}
else if ( inCombat )
{
from.SendMessage( "You cannot setup a tent while in combat." );
return;
}
else if ( ( from.Region.IsPartOf( typeof( BardDungeonRegion ) ) || from.Region.IsPartOf( typeof( DungeonRegion ) ) ) && from.Skills[SkillName.Camping].Value >= 90 )
{
CanUseTent = 1;
}
else if ( from.Skills[SkillName.Camping].Value < 90 &&
!Server.Misc.Worlds.IsMainRegion( Server.Misc.Worlds.GetRegionName( from.Map, from.Location ) ) &&
!from.Region.IsPartOf( typeof( OutDoorRegion ) ) &&
!from.Region.IsPartOf( typeof( OutDoorBadRegion ) ) &&
!from.Region.IsPartOf( typeof( VillageRegion ) ) )
{
from.SendMessage( "You are only skilled enough to use this tent outdoors." );
return;
}
else if ( from.Skills[SkillName.Camping].Value >= 90 &&
!from.Region.IsPartOf( typeof( DungeonRegion ) ) &&
!from.Region.IsPartOf( typeof( BardDungeonRegion ) ) &&
!Server.Misc.Worlds.IsMainRegion( Server.Misc.Worlds.GetRegionName( from.Map, from.Location ) ) &&
!from.Region.IsPartOf( typeof( OutDoorRegion ) ) &&
!from.Region.IsPartOf( typeof( OutDoorBadRegion ) ) &&
!from.Region.IsPartOf( typeof( VillageRegion ) ) )
{
from.SendMessage( "You can only use this tent outdoors or in dungeons." );
return;
}
else
{
CanUseTent = 1;
}
if ( CanUseTent > 0 && from.CheckSkill( SkillName.Camping, 0.0, 125.0 ) )
{
if ( IsChildOf( from.Backpack ) && Charges > 0 )
{
Server.Items.Kindling.RaiseCamping( from );
ConsumeCharge( from );
PlayerMobile pc = (PlayerMobile)from;
string sX = from.X.ToString();
string sY = from.Y.ToString();
string sZ = from.Z.ToString();
string sMap = Worlds.GetMyMapString( from.Map );
string sZone = "the Camping Tent";
if ( from.Region.IsPartOf( typeof( DungeonRegion ) ) || from.Region.IsPartOf( typeof( BardDungeonRegion ) ) ){ sZone = "the Dungeon Room"; }
string doors = sX + "#" + sY + "#" + sZ + "#" + sMap + "#" + sZone;
((PlayerMobile)from).CharacterPublicDoor = doors;
Point3D loc = new Point3D( 3710, 3971, 0 );
if ( from.Region.IsPartOf( typeof( DungeonRegion ) ) ){ loc = new Point3D( 3687, 3333, 0 ); }
else if ( from.Region.IsPartOf( typeof( BardDungeonRegion ) ) ){ loc = new Point3D( 3687, 3333, 0 ); }
else if ( from.Skills[SkillName.Camping].Value > 66 ){ loc = new Point3D( 3792, 3967, 0 ); }
TentTeleport( from, loc, Map.Sosaria, 0x057, sZone, "enter" );
return;
}
else if ( from.InRange( this.GetWorldLocation(), 3 ) && Charges > 0 )
{
Server.Items.Kindling.RaiseCamping( from );
ConsumeCharge( from );
PlayerMobile pc = (PlayerMobile)from;
string sX = from.X.ToString();
string sY = from.Y.ToString();
string sZ = from.Z.ToString();
string sMap = Worlds.GetMyMapString( from.Map );
string sZone = "the Camping Tent";
if ( from.Region.IsPartOf( typeof( DungeonRegion ) ) || from.Region.IsPartOf( typeof( BardDungeonRegion ) ) ){ sZone = "the Dungeon Room"; }
string doors = sX + "#" + sY + "#" + sZ + "#" + sMap + "#" + sZone;
((PlayerMobile)from).CharacterPublicDoor = doors;
Point3D loc = new Point3D( 3710, 3971, 0 );
if ( from.Region.IsPartOf( typeof( DungeonRegion ) ) ){ loc = new Point3D( 3687, 3333, 0 ); }
else if ( from.Region.IsPartOf( typeof( BardDungeonRegion ) ) ){ loc = new Point3D( 3687, 3333, 0 ); }
else if ( from.Skills[SkillName.Camping].Value > 66 ){ loc = new Point3D( 3792, 3967, 0 ); }
InternalItem builtTent = new InternalItem();
builtTent.Name = "camping tent";
ThruDoor publicTent = (ThruDoor)builtTent;
publicTent.m_PointDest = loc;
publicTent.m_MapDest = Map.Sosaria;
builtTent.MoveToWorld( this.Location, this.Map );
from.AddToBackpack( this );
TentTeleport( from, loc, Map.Sosaria, 0x057, sZone, "enter" );
return;
}
else if ( !from.InRange( this.GetWorldLocation(), 3 ) && Charges > 0 )
{
from.SendLocalizedMessage( 502138 ); // That is too far away for you to use
return;
}
else
{
from.SendMessage( "This tent is too worn from over use, and is no longer of any good." );
this.Delete();
return;
}
}
else if ( CanUseTent > 0 )
{
from.SendMessage( "Your tent is a bit more worn out as you fail to set it up properly." );
Server.Items.Kindling.RaiseCamping( from );
ConsumeCharge( from );
if ( Charges < 1 )
{
from.SendMessage( "This tent is too worn from over use, and is no longer of any good." );
this.Delete();
return;
}
return;
}
}
public static void TentTeleport( Mobile m, Point3D loc, Map map, int sound, string zone, string direction )
{
BaseCreature.TeleportPets( m, loc, map, false );
m.MoveToWorld ( loc, map );
m.PlaySound( sound );
LoggingFunctions.LogRegions( m, zone, direction );
}
public void ConsumeCharge( Mobile from )
{
--Charges;
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
list.Add( 1060584, "{0}\t{1}", m_Charges.ToString(), "Uses" );
}
private class InternalItem : ThruDoor
{
public InternalItem()
{
ItemID = 0x2795;
InternalTimer t = new InternalTimer( this );
t.Start();
}
public InternalItem( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
Delete();
}
private class InternalTimer : Timer
{
private Item m_Item;
public InternalTimer( Item item ) : base( TimeSpan.FromSeconds( 30.0 ) )
{
Priority = TimerPriority.OneSecond;
m_Item = item;
}
protected override void OnTick()
{
m_Item.Delete();
}
}
}
public CampersTent( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
writer.Write( (int) m_CamperTentEffect );
writer.Write( (int) m_Charges );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_CamperTentEffect = (CamperTentEffect)reader.ReadInt();
m_Charges = (int)reader.ReadInt();
break;
}
}
}
}
} | 412 | 0.981866 | 1 | 0.981866 | game-dev | MEDIA | 0.902373 | game-dev | 0.849872 | 1 | 0.849872 |
storax/kubedoom | 13,646 | dockerdoom/trunk/src/p_switch.c | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// Copyright(C) 1993-1996 Id Software, Inc.
// Copyright(C) 2005 Simon Howard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
//
// DESCRIPTION:
// Switches, buttons. Two-state animation. Exits.
//
//-----------------------------------------------------------------------------
#include "i_system.h"
#include "deh_main.h"
#include "doomdef.h"
#include "p_local.h"
#include "g_game.h"
#include "s_sound.h"
// Data.
#include "sounds.h"
// State.
#include "doomstat.h"
#include "r_state.h"
//
// CHANGE THE TEXTURE OF A WALL SWITCH TO ITS OPPOSITE
//
switchlist_t alphSwitchList[] =
{
// Doom shareware episode 1 switches
{"SW1BRCOM", "SW2BRCOM", 1},
{"SW1BRN1", "SW2BRN1", 1},
{"SW1BRN2", "SW2BRN2", 1},
{"SW1BRNGN", "SW2BRNGN", 1},
{"SW1BROWN", "SW2BROWN", 1},
{"SW1COMM", "SW2COMM", 1},
{"SW1COMP", "SW2COMP", 1},
{"SW1DIRT", "SW2DIRT", 1},
{"SW1EXIT", "SW2EXIT", 1},
{"SW1GRAY", "SW2GRAY", 1},
{"SW1GRAY1", "SW2GRAY1", 1},
{"SW1METAL", "SW2METAL", 1},
{"SW1PIPE", "SW2PIPE", 1},
{"SW1SLAD", "SW2SLAD", 1},
{"SW1STARG", "SW2STARG", 1},
{"SW1STON1", "SW2STON1", 1},
{"SW1STON2", "SW2STON2", 1},
{"SW1STONE", "SW2STONE", 1},
{"SW1STRTN", "SW2STRTN", 1},
// Doom registered episodes 2&3 switches
{"SW1BLUE", "SW2BLUE", 2},
{"SW1CMT", "SW2CMT", 2},
{"SW1GARG", "SW2GARG", 2},
{"SW1GSTON", "SW2GSTON", 2},
{"SW1HOT", "SW2HOT", 2},
{"SW1LION", "SW2LION", 2},
{"SW1SATYR", "SW2SATYR", 2},
{"SW1SKIN", "SW2SKIN", 2},
{"SW1VINE", "SW2VINE", 2},
{"SW1WOOD", "SW2WOOD", 2},
// Doom II switches
{"SW1PANEL", "SW2PANEL", 3},
{"SW1ROCK", "SW2ROCK", 3},
{"SW1MET2", "SW2MET2", 3},
{"SW1WDMET", "SW2WDMET", 3},
{"SW1BRIK", "SW2BRIK", 3},
{"SW1MOD1", "SW2MOD1", 3},
{"SW1ZIM", "SW2ZIM", 3},
{"SW1STON6", "SW2STON6", 3},
{"SW1TEK", "SW2TEK", 3},
{"SW1MARB", "SW2MARB", 3},
{"SW1SKULL", "SW2SKULL", 3},
{"\0", "\0", 0}
};
int switchlist[MAXSWITCHES * 2];
int numswitches;
button_t buttonlist[MAXBUTTONS];
//
// P_InitSwitchList
// Only called at game initialization.
//
void P_InitSwitchList(void)
{
int i;
int index;
int episode;
episode = 1;
if (gamemode == registered || gamemode == retail)
episode = 2;
else
if ( gamemode == commercial )
episode = 3;
for (index = 0,i = 0;i < MAXSWITCHES;i++)
{
if (!alphSwitchList[i].episode)
{
numswitches = index/2;
switchlist[index] = -1;
break;
}
if (alphSwitchList[i].episode <= episode)
{
#if 0 // UNUSED - debug?
int value;
if (R_CheckTextureNumForName(alphSwitchList[i].name1) < 0)
{
I_Error("Can't find switch texture '%s'!",
alphSwitchList[i].name1);
continue;
}
value = R_TextureNumForName(alphSwitchList[i].name1);
#endif
switchlist[index++] = R_TextureNumForName(DEH_String(alphSwitchList[i].name1));
switchlist[index++] = R_TextureNumForName(DEH_String(alphSwitchList[i].name2));
}
}
}
//
// Start a button counting down till it turns off.
//
void
P_StartButton
( line_t* line,
bwhere_e w,
int texture,
int time )
{
int i;
// See if button is already pressed
for (i = 0;i < MAXBUTTONS;i++)
{
if (buttonlist[i].btimer
&& buttonlist[i].line == line)
{
return;
}
}
for (i = 0;i < MAXBUTTONS;i++)
{
if (!buttonlist[i].btimer)
{
buttonlist[i].line = line;
buttonlist[i].where = w;
buttonlist[i].btexture = texture;
buttonlist[i].btimer = time;
buttonlist[i].soundorg = &line->frontsector->soundorg;
return;
}
}
I_Error("P_StartButton: no button slots left!");
}
//
// Function that changes wall texture.
// Tell it if switch is ok to use again (1=yes, it's a button).
//
void
P_ChangeSwitchTexture
( line_t* line,
int useAgain )
{
int texTop;
int texMid;
int texBot;
int i;
int sound;
if (!useAgain)
line->special = 0;
texTop = sides[line->sidenum[0]].toptexture;
texMid = sides[line->sidenum[0]].midtexture;
texBot = sides[line->sidenum[0]].bottomtexture;
sound = sfx_swtchn;
// EXIT SWITCH?
if (line->special == 11)
sound = sfx_swtchx;
for (i = 0;i < numswitches*2;i++)
{
if (switchlist[i] == texTop)
{
S_StartSound(buttonlist->soundorg,sound);
sides[line->sidenum[0]].toptexture = switchlist[i^1];
if (useAgain)
P_StartButton(line,top,switchlist[i],BUTTONTIME);
return;
}
else
{
if (switchlist[i] == texMid)
{
S_StartSound(buttonlist->soundorg,sound);
sides[line->sidenum[0]].midtexture = switchlist[i^1];
if (useAgain)
P_StartButton(line, middle,switchlist[i],BUTTONTIME);
return;
}
else
{
if (switchlist[i] == texBot)
{
S_StartSound(buttonlist->soundorg,sound);
sides[line->sidenum[0]].bottomtexture = switchlist[i^1];
if (useAgain)
P_StartButton(line, bottom,switchlist[i],BUTTONTIME);
return;
}
}
}
}
}
//
// P_UseSpecialLine
// Called when a thing uses a special line.
// Only the front sides of lines are usable.
//
boolean
P_UseSpecialLine
( mobj_t* thing,
line_t* line,
int side )
{
// Err...
// Use the back sides of VERY SPECIAL lines...
if (side)
{
switch(line->special)
{
case 124:
// Sliding door open&close
// UNUSED?
break;
default:
return false;
break;
}
}
// Switches that other things can activate.
if (!thing->player)
{
// never open secret doors
if (line->flags & ML_SECRET)
return false;
switch(line->special)
{
case 1: // MANUAL DOOR RAISE
case 32: // MANUAL BLUE
case 33: // MANUAL RED
case 34: // MANUAL YELLOW
break;
default:
return false;
break;
}
}
// do something
switch (line->special)
{
// MANUALS
case 1: // Vertical Door
case 26: // Blue Door/Locked
case 27: // Yellow Door /Locked
case 28: // Red Door /Locked
case 31: // Manual door open
case 32: // Blue locked door open
case 33: // Red locked door open
case 34: // Yellow locked door open
case 117: // Blazing door raise
case 118: // Blazing door open
EV_VerticalDoor (line, thing);
break;
//UNUSED - Door Slide Open&Close
// case 124:
// EV_SlidingDoor (line, thing);
// break;
// SWITCHES
case 7:
// Build Stairs
if (EV_BuildStairs(line,build8))
P_ChangeSwitchTexture(line,0);
break;
case 9:
// Change Donut
if (EV_DoDonut(line))
P_ChangeSwitchTexture(line,0);
break;
case 11:
// Exit level
P_ChangeSwitchTexture(line,0);
G_ExitLevel ();
break;
case 14:
// Raise Floor 32 and change texture
if (EV_DoPlat(line,raiseAndChange,32))
P_ChangeSwitchTexture(line,0);
break;
case 15:
// Raise Floor 24 and change texture
if (EV_DoPlat(line,raiseAndChange,24))
P_ChangeSwitchTexture(line,0);
break;
case 18:
// Raise Floor to next highest floor
if (EV_DoFloor(line, raiseFloorToNearest))
P_ChangeSwitchTexture(line,0);
break;
case 20:
// Raise Plat next highest floor and change texture
if (EV_DoPlat(line,raiseToNearestAndChange,0))
P_ChangeSwitchTexture(line,0);
break;
case 21:
// PlatDownWaitUpStay
if (EV_DoPlat(line,downWaitUpStay,0))
P_ChangeSwitchTexture(line,0);
break;
case 23:
// Lower Floor to Lowest
if (EV_DoFloor(line,lowerFloorToLowest))
P_ChangeSwitchTexture(line,0);
break;
case 29:
// Raise Door
if (EV_DoDoor(line,normal))
P_ChangeSwitchTexture(line,0);
break;
case 41:
// Lower Ceiling to Floor
if (EV_DoCeiling(line,lowerToFloor))
P_ChangeSwitchTexture(line,0);
break;
case 71:
// Turbo Lower Floor
if (EV_DoFloor(line,turboLower))
P_ChangeSwitchTexture(line,0);
break;
case 49:
// Ceiling Crush And Raise
if (EV_DoCeiling(line,crushAndRaise))
P_ChangeSwitchTexture(line,0);
break;
case 50:
// Close Door
if (EV_DoDoor(line,close))
P_ChangeSwitchTexture(line,0);
break;
case 51:
// Secret EXIT
P_ChangeSwitchTexture(line,0);
G_SecretExitLevel ();
break;
case 55:
// Raise Floor Crush
if (EV_DoFloor(line,raiseFloorCrush))
P_ChangeSwitchTexture(line,0);
break;
case 101:
// Raise Floor
if (EV_DoFloor(line,raiseFloor))
P_ChangeSwitchTexture(line,0);
break;
case 102:
// Lower Floor to Surrounding floor height
if (EV_DoFloor(line,lowerFloor))
P_ChangeSwitchTexture(line,0);
break;
case 103:
// Open Door
if (EV_DoDoor(line,open))
P_ChangeSwitchTexture(line,0);
break;
case 111:
// Blazing Door Raise (faster than TURBO!)
if (EV_DoDoor (line,blazeRaise))
P_ChangeSwitchTexture(line,0);
break;
case 112:
// Blazing Door Open (faster than TURBO!)
if (EV_DoDoor (line,blazeOpen))
P_ChangeSwitchTexture(line,0);
break;
case 113:
// Blazing Door Close (faster than TURBO!)
if (EV_DoDoor (line,blazeClose))
P_ChangeSwitchTexture(line,0);
break;
case 122:
// Blazing PlatDownWaitUpStay
if (EV_DoPlat(line,blazeDWUS,0))
P_ChangeSwitchTexture(line,0);
break;
case 127:
// Build Stairs Turbo 16
if (EV_BuildStairs(line,turbo16))
P_ChangeSwitchTexture(line,0);
break;
case 131:
// Raise Floor Turbo
if (EV_DoFloor(line,raiseFloorTurbo))
P_ChangeSwitchTexture(line,0);
break;
case 133:
// BlzOpenDoor BLUE
case 135:
// BlzOpenDoor RED
case 137:
// BlzOpenDoor YELLOW
if (EV_DoLockedDoor (line,blazeOpen,thing))
P_ChangeSwitchTexture(line,0);
break;
case 140:
// Raise Floor 512
if (EV_DoFloor(line,raiseFloor512))
P_ChangeSwitchTexture(line,0);
break;
// BUTTONS
case 42:
// Close Door
if (EV_DoDoor(line,close))
P_ChangeSwitchTexture(line,1);
break;
case 43:
// Lower Ceiling to Floor
if (EV_DoCeiling(line,lowerToFloor))
P_ChangeSwitchTexture(line,1);
break;
case 45:
// Lower Floor to Surrounding floor height
if (EV_DoFloor(line,lowerFloor))
P_ChangeSwitchTexture(line,1);
break;
case 60:
// Lower Floor to Lowest
if (EV_DoFloor(line,lowerFloorToLowest))
P_ChangeSwitchTexture(line,1);
break;
case 61:
// Open Door
if (EV_DoDoor(line,open))
P_ChangeSwitchTexture(line,1);
break;
case 62:
// PlatDownWaitUpStay
if (EV_DoPlat(line,downWaitUpStay,1))
P_ChangeSwitchTexture(line,1);
break;
case 63:
// Raise Door
if (EV_DoDoor(line,normal))
P_ChangeSwitchTexture(line,1);
break;
case 64:
// Raise Floor to ceiling
if (EV_DoFloor(line,raiseFloor))
P_ChangeSwitchTexture(line,1);
break;
case 66:
// Raise Floor 24 and change texture
if (EV_DoPlat(line,raiseAndChange,24))
P_ChangeSwitchTexture(line,1);
break;
case 67:
// Raise Floor 32 and change texture
if (EV_DoPlat(line,raiseAndChange,32))
P_ChangeSwitchTexture(line,1);
break;
case 65:
// Raise Floor Crush
if (EV_DoFloor(line,raiseFloorCrush))
P_ChangeSwitchTexture(line,1);
break;
case 68:
// Raise Plat to next highest floor and change texture
if (EV_DoPlat(line,raiseToNearestAndChange,0))
P_ChangeSwitchTexture(line,1);
break;
case 69:
// Raise Floor to next highest floor
if (EV_DoFloor(line, raiseFloorToNearest))
P_ChangeSwitchTexture(line,1);
break;
case 70:
// Turbo Lower Floor
if (EV_DoFloor(line,turboLower))
P_ChangeSwitchTexture(line,1);
break;
case 114:
// Blazing Door Raise (faster than TURBO!)
if (EV_DoDoor (line,blazeRaise))
P_ChangeSwitchTexture(line,1);
break;
case 115:
// Blazing Door Open (faster than TURBO!)
if (EV_DoDoor (line,blazeOpen))
P_ChangeSwitchTexture(line,1);
break;
case 116:
// Blazing Door Close (faster than TURBO!)
if (EV_DoDoor (line,blazeClose))
P_ChangeSwitchTexture(line,1);
break;
case 123:
// Blazing PlatDownWaitUpStay
if (EV_DoPlat(line,blazeDWUS,0))
P_ChangeSwitchTexture(line,1);
break;
case 132:
// Raise Floor Turbo
if (EV_DoFloor(line,raiseFloorTurbo))
P_ChangeSwitchTexture(line,1);
break;
case 99:
// BlzOpenDoor BLUE
case 134:
// BlzOpenDoor RED
case 136:
// BlzOpenDoor YELLOW
if (EV_DoLockedDoor (line,blazeOpen,thing))
P_ChangeSwitchTexture(line,1);
break;
case 138:
// Light Turn On
EV_LightTurnOn(line,255);
P_ChangeSwitchTexture(line,1);
break;
case 139:
// Light Turn Off
EV_LightTurnOn(line,35);
P_ChangeSwitchTexture(line,1);
break;
}
return true;
}
| 412 | 0.893752 | 1 | 0.893752 | game-dev | MEDIA | 0.928215 | game-dev | 0.975036 | 1 | 0.975036 |
ss14Starlight/space-station-14 | 5,098 | Content.IntegrationTests/Tests/HumanInventoryUniformSlotsTest.cs | using Content.Shared.Inventory;
using Robust.Shared.GameObjects;
namespace Content.IntegrationTests.Tests
{
// Tests the behavior of InventoryComponent.
// i.e. the interaction between uniforms and the pocket/ID slots.
// and also how big items don't fit in pockets.
[TestFixture]
public sealed class HumanInventoryUniformSlotsTest
{
[TestPrototypes]
private const string Prototypes = @"
- type: entity
name: HumanUniformDummy
id: HumanUniformDummy
components:
- type: Inventory
- type: ContainerContainer
- type: entity
name: UniformDummy
id: UniformDummy
components:
- type: Clothing
slots: [innerclothing]
- type: Item
size: Tiny
- type: entity
name: IDCardDummy
id: IDCardDummy
components:
- type: Clothing
slots:
- idcard
- type: Item
size: Tiny
- type: IdCard
- type: entity
name: FlashlightDummy
id: FlashlightDummy
components:
- type: Item
size: Tiny
- type: entity
name: ToolboxDummy
id: ToolboxDummy
components:
- type: Item
size: Huge
";
[Test]
public async Task Test()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
var testMap = await pair.CreateTestMap();
var coordinates = testMap.GridCoords;
EntityUid human = default;
EntityUid uniform = default;
EntityUid idCard = default;
EntityUid pocketItem = default;
InventorySystem invSystem = default!;
var mapSystem = server.System<SharedMapSystem>();
var entityMan = server.ResolveDependency<IEntityManager>();
await server.WaitAssertion(() =>
{
invSystem = entityMan.System<InventorySystem>();
human = entityMan.SpawnEntity("HumanUniformDummy", coordinates);
uniform = entityMan.SpawnEntity("UniformDummy", coordinates);
idCard = entityMan.SpawnEntity("IDCardDummy", coordinates);
pocketItem = entityMan.SpawnEntity("FlashlightDummy", coordinates);
var tooBigItem = entityMan.SpawnEntity("ToolboxDummy", coordinates);
Assert.Multiple(() =>
{
Assert.That(invSystem.CanEquip(human, uniform, "jumpsuit", out _));
// Can't equip any of these since no uniform!
Assert.That(invSystem.CanEquip(human, idCard, "id", out _), Is.False);
Assert.That(invSystem.CanEquip(human, pocketItem, "pocket1", out _), Is.False);
Assert.That(invSystem.CanEquip(human, tooBigItem, "pocket2", out _), Is.False); // This one fails either way.
});
Assert.Multiple(() =>
{
Assert.That(invSystem.TryEquip(human, uniform, "jumpsuit"));
Assert.That(invSystem.TryEquip(human, idCard, "id"));
});
#pragma warning disable NUnit2045
Assert.That(invSystem.CanEquip(human, tooBigItem, "pocket1", out _), Is.False); // Still failing!
Assert.That(invSystem.TryEquip(human, pocketItem, "pocket1"));
#pragma warning restore NUnit2045
Assert.Multiple(() =>
{
Assert.That(IsDescendant(idCard, human, entityMan));
Assert.That(IsDescendant(pocketItem, human, entityMan));
});
// Now drop the jumpsuit.
Assert.That(invSystem.TryUnequip(human, "jumpsuit"));
});
await server.WaitRunTicks(2);
await server.WaitAssertion(() =>
{
Assert.Multiple(() =>
{
// Items have been dropped!
Assert.That(IsDescendant(uniform, human, entityMan), Is.False);
Assert.That(IsDescendant(idCard, human, entityMan), Is.False);
Assert.That(IsDescendant(pocketItem, human, entityMan), Is.False);
// Ensure everything null here.
Assert.That(!invSystem.TryGetSlotEntity(human, "jumpsuit", out _));
Assert.That(!invSystem.TryGetSlotEntity(human, "id", out _));
Assert.That(!invSystem.TryGetSlotEntity(human, "pocket1", out _));
});
mapSystem.DeleteMap(testMap.MapId);
});
await pair.CleanReturnAsync();
}
private static bool IsDescendant(EntityUid descendant, EntityUid parent, IEntityManager entManager)
{
var xforms = entManager.GetEntityQuery<TransformComponent>();
var tmpParent = xforms.GetComponent(descendant).ParentUid;
while (tmpParent.IsValid())
{
if (tmpParent == parent)
{
return true;
}
tmpParent = xforms.GetComponent(tmpParent).ParentUid;
}
return false;
}
}
}
| 412 | 0.868143 | 1 | 0.868143 | game-dev | MEDIA | 0.936289 | game-dev | 0.600151 | 1 | 0.600151 |
ProjectIgnis/CardScripts | 5,785 | official/c70417076.lua | --Emウィンド・サッカー
--Performage Wind Drainer
--scripted by Naim
local s,id=GetID()
function s.initial_effect(c)
--Pendulum Summon procedure
Pendulum.AddProcedure(c)
--Activate 1 of these effects
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_PZONE)
e1:SetCountLimit(1)
e1:SetTarget(s.efftg)
e1:SetOperation(s.effop)
c:RegisterEffect(e1)
--Special Summon this card from your hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_HAND)
e2:SetCountLimit(1,id)
e2:SetCondition(s.spcon)
e2:SetTarget(s.sptg)
e2:SetOperation(s.spop)
c:RegisterEffect(e2)
--Reduce this card's Level by 1
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,2))
e3:SetCategory(CATEGORY_LVCHANGE)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetTarget(s.selflvtg)
e3:SetOperation(s.selflvop)
c:RegisterEffect(e3)
--Change the Levels of all Level 4 "Performage" monsters you control to 5
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(id,3))
e4:SetCategory(CATEGORY_LVCHANGE)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1)
e4:SetTarget(s.lvtg)
e4:SetOperation(s.lvop)
c:RegisterEffect(e4)
end
s.listed_series={SET_PERFORMAGE}
function s.tgfilter(c)
return c:IsSetCard(SET_PERFORMAGE) and c:IsType(TYPE_PENDULUM) and c:IsFaceup() and (c:IsLevelAbove(2) or c:GetScale()>0)
end
function s.efftg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then
if not (chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and s.tgfilter(chkc)) then return false end
local op=e:GetLabel()
return (op==1 and chkc:IsLevelAbove(2)) or (op==2 and chkc:GetScale()>0)
end
if chk==0 then return Duel.IsExistingTarget(s.tgfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local tc=Duel.SelectTarget(tp,s.tgfilter,tp,LOCATION_MZONE,0,1,1,nil):GetFirst()
local b1,b2=tc:IsLevelAbove(2),tc:GetScale()>0
local op=Duel.SelectEffect(tp,
{b1,aux.Stringid(id,4)},
{b2,aux.Stringid(id,5)})
e:SetLabel(op)
if op==1 then
e:SetCategory(CATEGORY_LVCHANGE)
Duel.SetOperationInfo(0,CATEGORY_LVCHANGE,tc,1,tp,-1)
elseif op==2 then
e:SetCategory(0)
end
end
function s.effop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not (tc:IsRelateToEffect(e) and tc:IsFaceup()) then return end
local op=e:GetLabel()
local c=e:GetHandler()
if op==1 then
--Reduce its Level by 1
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(-1)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
tc:RegisterEffect(e1)
elseif op==2 then
local scale=tc:GetScale()
--Increase this card's Pendulum Scale by that monster's
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_UPDATE_LSCALE)
e2:SetValue(scale)
e2:SetReset(RESET_EVENT|RESETS_STANDARD_DISABLE)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_RSCALE)
c:RegisterEffect(e3)
end
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(nil,tp,0,LOCATION_MZONE,1,nil)
or Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsSetCard,SET_PERFORMAGE),tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,tp,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then
c:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(id,6))
--Cannot Special Summon, except "Performage" monsters while it is in the Monster Zone
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetRange(LOCATION_MZONE)
e1:SetAbsoluteRange(tp,1,0)
e1:SetTarget(function(e,c) return not c:IsSetCard(SET_PERFORMAGE) end)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
c:RegisterEffect(e1,true)
end
end
function s.selflvtg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsLevelAbove(2) end
Duel.SetOperationInfo(0,CATEGORY_LVCHANGE,c,1,tp,-1)
end
function s.selflvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
--Reduce its Level by 1
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(-1)
e1:SetReset(RESET_EVENT|RESETS_STANDARD_DISABLE)
c:RegisterEffect(e1)
end
end
function s.lvfilter(c)
return c:IsLevel(4) and c:IsSetCard(SET_PERFORMAGE) and c:IsFaceup()
end
function s.lvtg(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetMatchingGroup(s.lvfilter,tp,LOCATION_MZONE,0,nil)
if chk==0 then return #g>0 end
Duel.SetOperationInfo(0,CATEGORY_LVCHANGE,g,#g,tp,5)
end
function s.lvop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(s.lvfilter,tp,LOCATION_MZONE,0,nil)
if #g==0 then return end
local c=e:GetHandler()
for tc in g:Iter() do
--Change their Levels to 5
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(5)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end | 412 | 0.926354 | 1 | 0.926354 | game-dev | MEDIA | 0.986173 | game-dev | 0.951667 | 1 | 0.951667 |
KentBeck/BPlusTree3 | 17,874 | rust/tests/test_utils.rs | #![allow(dead_code)] // Allow unused utility functions for future tests
/// Comprehensive test utilities to eliminate massive test duplication
/// This module provides reusable patterns for adversarial testing and common operations
use bplustree::BPlusTreeMap;
// ============================================================================
// TREE CREATION UTILITIES - Replace 185 instances of BPlusTreeMap::new()
// ============================================================================
/// Standard tree with capacity 4 (most common pattern)
pub fn create_tree_4() -> BPlusTreeMap<i32, String> {
BPlusTreeMap::new(4).expect("Failed to create tree with capacity 4")
}
/// Standard tree with capacity 4 for integer keys and values
pub fn create_tree_4_int() -> BPlusTreeMap<i32, i32> {
BPlusTreeMap::new(4).expect("Failed to create integer tree with capacity 4")
}
/// Standard tree with capacity 5 (for odd capacity testing)
pub fn create_tree_5() -> BPlusTreeMap<i32, String> {
BPlusTreeMap::new(5).expect("Failed to create tree with capacity 5")
}
/// Standard tree with capacity 6 (for specific testing scenarios)
pub fn create_tree_6() -> BPlusTreeMap<i32, String> {
BPlusTreeMap::new(6).expect("Failed to create tree with capacity 6")
}
/// Generic tree creation with custom capacity
pub fn create_tree_capacity(capacity: usize) -> BPlusTreeMap<i32, String> {
BPlusTreeMap::new(capacity).expect(&format!("Failed to create tree with capacity {}", capacity))
}
/// Generic integer tree creation with custom capacity
pub fn create_tree_capacity_int(capacity: usize) -> BPlusTreeMap<i32, i32> {
BPlusTreeMap::new(capacity).expect(&format!(
"Failed to create integer tree with capacity {}",
capacity
))
}
// ============================================================================
// DATA POPULATION UTILITIES - Replace 176 for-loop patterns
// ============================================================================
/// Insert sequential data 0..count with string values
pub fn insert_sequential_range(tree: &mut BPlusTreeMap<i32, String>, count: usize) {
for i in 0..count {
tree.insert(i as i32, format!("value_{}", i));
}
}
/// Insert sequential data 0..count with integer values
pub fn insert_sequential_range_int(tree: &mut BPlusTreeMap<i32, i32>, count: usize) {
for i in 0..count {
tree.insert(i as i32, i as i32);
}
}
/// Insert data with custom key multiplier (common pattern: i * multiplier)
pub fn insert_with_multiplier(tree: &mut BPlusTreeMap<i32, String>, count: usize, multiplier: i32) {
for i in 0..count {
let key = (i as i32) * multiplier;
tree.insert(key, format!("value_{}", i));
}
}
/// Insert data with custom key multiplier for integer trees
pub fn insert_with_multiplier_int(
tree: &mut BPlusTreeMap<i32, i32>,
count: usize,
multiplier: i32,
) {
for i in 0..count {
let key = (i as i32) * multiplier;
tree.insert(key, i as i32);
}
}
/// Insert data with offset and multiplier (key = offset + i * multiplier)
pub fn insert_with_offset_multiplier(
tree: &mut BPlusTreeMap<i32, String>,
count: usize,
offset: i32,
multiplier: i32,
) {
for i in 0..count {
let key = offset + (i as i32) * multiplier;
tree.insert(key, format!("value_{}", i));
}
}
/// Insert data with custom key and value functions
pub fn insert_with_custom_fn<F, G>(
tree: &mut BPlusTreeMap<i32, String>,
count: usize,
key_fn: F,
value_fn: G,
) where
F: Fn(usize) -> i32,
G: Fn(usize) -> String,
{
for i in 0..count {
let key = key_fn(i);
let value = value_fn(i);
tree.insert(key, value);
}
}
/// Insert sequential data start..end with string values
pub fn insert_range(tree: &mut BPlusTreeMap<i32, String>, start: usize, end: usize) {
for i in start..end {
tree.insert(i as i32, format!("value_{}", i));
}
}
/// Insert sequential data start..end with integer values
pub fn insert_range_int(tree: &mut BPlusTreeMap<i32, i32>, start: usize, end: usize) {
for i in start..end {
tree.insert(i as i32, i as i32);
}
}
// ============================================================================
// COMBINED TREE CREATION AND POPULATION - Most common patterns
// ============================================================================
/// Create tree with capacity 4 and insert 0..count sequential data
pub fn create_tree_4_with_data(count: usize) -> BPlusTreeMap<i32, String> {
let mut tree = create_tree_4();
insert_sequential_range(&mut tree, count);
tree
}
/// Create integer tree with capacity 4 and insert 0..count sequential data
pub fn create_tree_4_int_with_data(count: usize) -> BPlusTreeMap<i32, i32> {
let mut tree = create_tree_4_int();
insert_sequential_range_int(&mut tree, count);
tree
}
/// Create tree with custom capacity and insert 0..count sequential data
pub fn create_tree_with_data(capacity: usize, count: usize) -> BPlusTreeMap<i32, String> {
let mut tree = create_tree_capacity(capacity);
insert_sequential_range(&mut tree, count);
tree
}
/// Create integer tree with custom capacity and insert 0..count sequential data
pub fn create_tree_int_with_data(capacity: usize, count: usize) -> BPlusTreeMap<i32, i32> {
let mut tree = create_tree_capacity_int(capacity);
insert_sequential_range_int(&mut tree, count);
tree
}
/// Create tree with data using multiplier pattern (common: i * 2, i * 3, i * 5, i * 10)
pub fn create_tree_4_with_multiplier(count: usize, multiplier: i32) -> BPlusTreeMap<i32, String> {
let mut tree = create_tree_4();
insert_with_multiplier(&mut tree, count, multiplier);
tree
}
// ============================================================================
// INVARIANT CHECKING UTILITIES - Replace 44 instances
// ============================================================================
/// Standard invariant check with panic on failure
pub fn assert_invariants(tree: &BPlusTreeMap<i32, String>, context: &str) {
if let Err(e) = tree.check_invariants_detailed() {
panic!("Invariant violation in {}: {}", context, e);
}
}
/// Standard invariant check for integer trees
pub fn assert_invariants_int(tree: &BPlusTreeMap<i32, i32>, context: &str) {
if let Err(e) = tree.check_invariants_detailed() {
panic!("Invariant violation in {}: {}", context, e);
}
}
/// Comprehensive tree validation including ordering
pub fn assert_full_validation(tree: &BPlusTreeMap<i32, String>, context: &str) {
assert_invariants(tree, context);
verify_ordering(tree);
}
/// Comprehensive tree validation for integer trees
pub fn assert_full_validation_int(tree: &BPlusTreeMap<i32, i32>, context: &str) {
assert_invariants_int(tree, context);
verify_ordering_int(tree);
}
// ============================================================================
// ADVERSARIAL ATTACK PATTERNS - Common deletion patterns
// ============================================================================
/// Execute deletion range attack (delete items from start to end)
pub fn deletion_range_attack(tree: &mut BPlusTreeMap<i32, String>, start: usize, end: usize) {
for i in start..end {
tree.remove(&(i as i32));
}
}
/// Execute deletion range attack for integer trees
pub fn deletion_range_attack_int(tree: &mut BPlusTreeMap<i32, i32>, start: usize, end: usize) {
for i in start..end {
tree.remove(&(i as i32));
}
}
/// Execute alternating deletion pattern (delete every other item)
pub fn alternating_deletion_attack(tree: &mut BPlusTreeMap<i32, String>, count: usize) {
for i in (0..count).step_by(2) {
tree.remove(&(i as i32));
}
}
/// Execute a stress test cycle with automatic invariant checking
pub fn stress_test_cycle<F>(tree: &mut BPlusTreeMap<i32, String>, cycles: usize, attack_fn: F)
where
F: Fn(&mut BPlusTreeMap<i32, String>, usize),
{
for cycle in 0..cycles {
attack_fn(tree, cycle);
// Unified invariant checking with context
if let Err(e) = tree.check_invariants_detailed() {
panic!("ATTACK SUCCESSFUL at cycle {}: {}", cycle, e);
}
}
}
/// Standard arena exhaustion attack pattern
pub fn arena_exhaustion_attack(tree: &mut BPlusTreeMap<i32, String>, cycle: usize) {
let cycle_i32 = cycle as i32;
// Fill tree to create many nodes
for i in 0..100 {
tree.insert(cycle_i32 * 1000 + i, format!("v{}-{}", cycle, i));
}
// Delete most items to free nodes
for i in 0..95 {
tree.remove(&(cycle_i32 * 1000 + i));
}
println!(
"Cycle {}: Free leaves={}, Free branches={}",
cycle,
tree.free_leaf_count(),
tree.branch_arena_stats().free_count
);
}
/// Standard fragmentation attack pattern
pub fn fragmentation_attack(tree: &mut BPlusTreeMap<i32, String>, base_key: i32) {
// Insert in a pattern that creates and frees nodes in specific order
for i in 0..500 {
tree.insert(base_key + i * 10, format!("fragmented-{}", i));
}
// Delete every other item
for i in (0..500).step_by(2) {
tree.remove(&(base_key + i * 10));
}
// Reinsert to reuse freed slots
for i in 0..250 {
tree.insert(base_key + i * 10 + 5, format!("reused-{}", i * 1000));
}
}
/// Deep tree creation attack pattern
pub fn deep_tree_attack(tree: &mut BPlusTreeMap<i32, i32>, capacity: usize) {
let mut key = 0;
for level in 0..5 {
let level_u32 = u32::try_from(level).expect("Level should fit in u32");
let count = capacity.pow(level_u32);
for _ in 0..count * 10 {
tree.insert(key, key);
key += 100; // Large gaps to force deep structure
}
}
}
/// Alternating operations attack pattern
pub fn alternating_operations_attack(tree: &mut BPlusTreeMap<i32, String>, round: usize) {
// Delete from left side
let left_key = (round * 6) as i32;
if tree.contains_key(&left_key) {
tree.remove(&left_key);
}
// Insert in middle
let mid_key = 30 + round as i32;
tree.insert(mid_key * 2 + 1, format!("mid{}", round));
// Delete from right side
let right_key = 118 - (round * 6) as i32;
if tree.contains_key(&right_key) {
tree.remove(&right_key);
}
}
// ============================================================================
// VERIFICATION UTILITIES
// ============================================================================
/// Verify tree ordering after operations
pub fn verify_ordering(tree: &BPlusTreeMap<i32, String>) {
let items: Vec<_> = tree.items().collect();
for i in 1..items.len() {
if items[i - 1].0 >= items[i].0 {
panic!("Items out of order after operations!");
}
}
}
/// Verify tree ordering for integer trees
pub fn verify_ordering_int(tree: &BPlusTreeMap<i32, i32>) {
let items: Vec<_> = tree.items().collect();
for i in 1..items.len() {
if items[i - 1].0 >= items[i].0 {
panic!("Items out of order after operations!");
}
}
}
/// Verify tree has expected number of items
pub fn verify_item_count(tree: &BPlusTreeMap<i32, String>, expected: usize, context: &str) {
let actual = tree.len();
if actual != expected {
panic!(
"Item count mismatch in {}: Expected {} items, got {}",
context, expected, actual
);
}
}
/// Verify tree has expected number of items (integer version)
pub fn verify_item_count_int(tree: &BPlusTreeMap<i32, i32>, expected: usize, context: &str) {
let actual = tree.len();
if actual != expected {
panic!(
"Item count mismatch in {}: Expected {} items, got {}",
context, expected, actual
);
}
}
// ============================================================================
// SPECIALIZED TEST SETUPS
// ============================================================================
/// Create a tree with specific structure for branch testing
pub fn create_branch_test_tree(capacity: usize) -> BPlusTreeMap<i32, String> {
let mut tree = create_tree_capacity(capacity);
// Build specific tree structure where branches are at minimum
let keys = vec![
10, 20, 30, 40, 15, 25, 35, 45, 12, 18, 22, 28, 32, 38, 42, 48,
];
for key in keys {
tree.insert(key, format!("v{}", key));
}
// Delete strategically to make siblings exactly at minimum
for key in vec![18, 28, 38, 48] {
tree.remove(&key);
}
tree
}
/// Standard setup for concurrent access simulation
pub fn setup_concurrent_simulation() -> (Vec<(bool, i32)>, Vec<(bool, i32)>) {
let thread1_ops = vec![
(true, 1),
(true, 3),
(true, 5),
(false, 3),
(true, 7),
(false, 1),
];
let thread2_ops = vec![
(true, 2),
(true, 4),
(false, 2),
(true, 6),
(true, 8),
(false, 4),
];
(thread1_ops, thread2_ops)
}
/// Execute interleaved operations for concurrent simulation
pub fn execute_interleaved_ops(
tree: &mut BPlusTreeMap<i32, String>,
thread1_ops: &[(bool, i32)],
thread2_ops: &[(bool, i32)],
) {
for i in 0..thread1_ops.len() {
// Thread 1 operation
let (is_insert, key) = thread1_ops[i];
if is_insert {
tree.insert(key * 10, format!("t1-{}", key));
} else {
tree.remove(&(key * 10));
}
// Check invariants after each operation
assert_invariants(tree, &format!("after thread1 op {}", i));
// Thread 2 operation
let (is_insert, key) = thread2_ops[i];
if is_insert {
tree.insert(key * 10 + 1, format!("t2-{}", key));
} else {
tree.remove(&(key * 10 + 1));
}
// Check invariants after each operation
assert_invariants(tree, &format!("after thread2 op {}", i));
}
}
// ============================================================================
// DEBUGGING AND STATISTICS
// ============================================================================
/// Print tree statistics for debugging
pub fn print_tree_stats(tree: &BPlusTreeMap<i32, String>, label: &str) {
let leaf_stats = tree.leaf_arena_stats();
let branch_stats = tree.branch_arena_stats();
println!(
"{}: {} items, Free leaves={}, Free branches={}",
label,
tree.len(),
leaf_stats.free_count,
branch_stats.free_count
);
println!("Leaf sizes: {:?}", tree.leaf_sizes());
}
/// Print tree statistics for integer trees
pub fn print_tree_stats_int(tree: &BPlusTreeMap<i32, i32>, label: &str) {
let leaf_stats = tree.leaf_arena_stats();
let branch_stats = tree.branch_arena_stats();
println!(
"{}: {} items, Free leaves={}, Free branches={}",
label,
tree.len(),
leaf_stats.free_count,
branch_stats.free_count
);
println!("Leaf sizes: {:?}", tree.leaf_sizes());
}
// ============================================================================
// LEGACY COMPATIBILITY - Keep existing test function names working
// ============================================================================
/// Legacy compatibility - create attack tree
pub fn create_attack_tree(capacity: usize) -> BPlusTreeMap<i32, String> {
create_tree_capacity(capacity)
}
/// Legacy compatibility - create simple tree
pub fn create_simple_tree(capacity: usize) -> BPlusTreeMap<i32, i32> {
create_tree_capacity_int(capacity)
}
/// Legacy compatibility - populate tree with sequential data
pub fn populate_sequential(tree: &mut BPlusTreeMap<i32, String>, count: usize) {
insert_sequential_range(tree, count);
}
/// Legacy compatibility - populate tree with sequential integer data
pub fn populate_sequential_int(tree: &mut BPlusTreeMap<i32, i32>, count: usize) {
insert_sequential_range_int(tree, count);
}
/// Legacy compatibility - populate tree with sequential integer data where value = key * 10
pub fn populate_sequential_int_x10(tree: &mut BPlusTreeMap<i32, i32>, count: usize) {
for i in 0..count {
tree.insert(i as i32, (i as i32) * 10);
}
}
/// Legacy compatibility - verify attack failed
pub fn assert_attack_failed(tree: &BPlusTreeMap<i32, String>, context: &str) {
assert_invariants(tree, context);
}
/// Legacy compatibility - verify attack failed for integer trees
pub fn assert_attack_failed_int(tree: &BPlusTreeMap<i32, i32>, context: &str) {
assert_invariants_int(tree, context);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_utilities_basic_functionality() {
let mut tree = create_tree_4();
insert_sequential_range(&mut tree, 10);
assert_eq!(tree.len(), 10);
verify_ordering(&tree);
assert_invariants(&tree, "basic functionality test");
}
#[test]
fn test_stress_cycle_utility() {
let mut tree = create_tree_4();
// Test that stress_test_cycle works correctly
stress_test_cycle(&mut tree, 5, |tree, cycle| {
tree.insert(cycle as i32, format!("cycle_{}", cycle));
});
assert_eq!(tree.len(), 5);
}
#[test]
fn test_combined_creation_utilities() {
let tree = create_tree_4_with_data(20);
assert_eq!(tree.len(), 20);
assert_full_validation(&tree, "combined creation test");
}
#[test]
fn test_attack_patterns() {
let mut tree = create_tree_4_with_data(50);
// Test deletion range attack
deletion_range_attack(&mut tree, 10, 40);
assert_eq!(tree.len(), 20);
assert_full_validation(&tree, "deletion range attack");
}
}
| 412 | 0.934762 | 1 | 0.934762 | game-dev | MEDIA | 0.199477 | game-dev | 0.901428 | 1 | 0.901428 |
openitu/STL | 2,254 | src/mnru/mnru.h | #ifndef MNRU_DEFINED
#define MNRU_DEFINED 200
/* Smart function prototypes: for [ag]cc, VaxC, and [tb]cc */
#if !defined(ARGS)
#if (defined(__STDC__) || defined(VMS) || defined(__DECC) || defined(MSDOS) || defined(__MSDOS__))
#define ARGS(s) s
#else
#define ARGS(s) ()
#endif
#endif
#ifdef STL92_RNG
#define RANDOM_state ori_RANDOM_state
#else
#define RANDOM_state new_RANDOM_state
#endif
/* Definition of type for random_MNRU state variables */
typedef struct {
int idum;
int inext, inextp;
long ma[56]; /* this is a special value; shall not be changed [1],[2] */
} ori_RANDOM_state;
/* Definition of type for random_MNRU state variables */
typedef struct {
float *gauss;
} new_RANDOM_state;
/* Definitions for the MNRU state variable */
#define MNRU_STAGE_OUT_FLT 2 /* number of 2nd-order stages in filter */
/* Definition of type for MNRU state variables */
typedef struct {
/* State variables related to the rnadom number generation */
long seed, clip;
double signal_gain, noise_gain;
double *vet, last_xk, last_yk, last_y20k_lp;
RANDOM_state rnd_state; /* for random_MNRU() */
char rnd_mode;
/* State variables related to the output band-pass filtering */
double A[MNRU_STAGE_OUT_FLT][3]; /* numerator coefficients */
double B[MNRU_STAGE_OUT_FLT][2]; /* denominator coefficients */
double DLY[MNRU_STAGE_OUT_FLT][2]; /* delay storage elements (z-shifts) */
} MNRU_state;
/* Prototype for MNRU and random function(s) */
double *MNRU_process ARGS ((char operation, MNRU_state * s, float *input, float *output, long n, long seed, char mode, double Q, float *fseed));
double *P50_MNRU_process ARGS ((char operation, MNRU_state * s, double *input, double *output, long n, char mode, double Q, char dcRemoval, float *fseed));
float random_MNRU ARGS ((char *mode, RANDOM_state * r, long seed));
/* Definitions for the MNRU algorithm */
#define MOD_NOISE 1
#define NOISE_ONLY 0
#define SIGNAL_ONLY -1
#define MNRU_START 1
#define MNRU_CONTINUE 0
#define MNRU_STOP -1
/* Definitions for Knuth's subtractive Random Number Generator */
#define RANDOM_RUN 0
#define RANDOM_RESET 1
#endif
/* ------------------------- End of MNRU.H ----------------------------- */
| 412 | 0.831388 | 1 | 0.831388 | game-dev | MEDIA | 0.418099 | game-dev | 0.538387 | 1 | 0.538387 |
LegacyModdingMC/UniMixins | 4,820 | module-compat/src/main/java/io/github/legacymoddingmc/unimixins/compat/CompatCore.java | package io.github.legacymoddingmc.unimixins.compat;
import java.util.*;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import io.github.legacymoddingmc.unimixins.common.config.ConfigUtil;
import io.github.legacymoddingmc.unimixins.compat.asm.IgnoreDuplicateJarsTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Mixins;
@MCVersion("1.7.10")
public class CompatCore implements IFMLLoadingPlugin {
public static final Logger LOGGER = LogManager.getLogger("unimixins");
public CompatCore() {
LOGGER.info("Instantiating CompatCore");
ConfigUtil.load(CompatConfig.class);
if(CompatConfig.enableRemapper) {
// We register the transformer this way to register it as early as possible.
Launch.classLoader.registerTransformer(relativeClassName("asm.ASMRemapperTransformer"));
}
}
@Override
public String[] getASMTransformerClass() {
List<String> classes = new ArrayList<>();
if(CompatConfig.enhanceCrashReports) {
classes.add("io.github.legacymoddingmc.unimixins.compat.asm.EnhanceCrashReportsTransformer");
}
if(IgnoreDuplicateJarsTransformer.wantsToRun()) {
classes.add("io.github.legacymoddingmc.unimixins.compat.asm.IgnoreDuplicateJarsTransformer");
}
if(Boolean.parseBoolean(System.getProperty("unimixins.compat.hackClasspathModDiscovery", "false"))) {
classes.add("io.github.legacymoddingmc.unimixins.compat.asm.HackClasspathModDiscoveryTransformer");
}
return classes.toArray(new String[0]);
}
private static String relativeClassName(String relName) {
String name = CompatCore.class.getName();
name = name.substring(0, name.lastIndexOf('.') + 1);
name += relName;
return name;
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
/**
* <p>This is the earliest point after the Mixin environment's initialization where we can inject code.
* <p>We register our error handler here.
*/
@Override
public void injectData(Map<String, Object> data) {
if(CompatConfig.enhanceCrashReports) {
Mixins.registerErrorHandlerClass("io.github.legacymoddingmc.unimixins.compat.MixinErrorHandler");
}
}
@Override
public String getAccessTransformerClass() {
return "io.github.legacymoddingmc.unimixins.compat.CompatCore$DummyTransformer";
}
/** Coremod Access Transformers are initialized at the beginning of {@link cpw.mods.fml.common.launcher.FMLDeobfTweaker#injectIntoClassLoader}.
* We use this as an injection point, this transformer doesn't actually transform anything. */
@SuppressWarnings("unused")
public static class DummyTransformer implements IClassTransformer {
public DummyTransformer() {
if (CompatConfig.improveInitPhaseDetection) {
setFmlLoggerToVerbose();
}
}
/** Mixin detects the start of the INIT phase by listening for the "Validating minecraft" FML log message.
* (See <tt>MixinAppender</tt> in {@link org.spongepowered.asm.launch.platform.MixinPlatformAgentFMLLegacy}.)
*
* <p>It sets the verbosity to ALL in an attempt to ensure the message gets logged, but this is not always the
* case. We add an extra check here, in a method that gets called right before that log message.</p>
*/
private static void setFmlLoggerToVerbose() {
Logger fmlLog;
try {
fmlLog = FMLRelaunchLog.log.getLogger();
if (!(fmlLog instanceof org.apache.logging.log4j.core.Logger)) {
return;
}
} catch (NoClassDefFoundError e) {
return;
}
org.apache.logging.log4j.core.Logger fmlCoreLog = (org.apache.logging.log4j.core.Logger)fmlLog;
if(fmlCoreLog.getLevel() != Level.ALL) {
LOGGER.info("Correcting FML log level from " + fmlCoreLog.getLevel() + " to ALL");
} else {
LOGGER.debug("FML log level was already ALL, doing nothing");
}
fmlCoreLog.setLevel(Level.ALL);
}
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
return basicClass;
}
}
}
| 412 | 0.885398 | 1 | 0.885398 | game-dev | MEDIA | 0.862097 | game-dev | 0.966647 | 1 | 0.966647 |
TheKisDevs/LavaHack-Public | 1,293 | src/main/java/com/kisman/cc/module/exploit/KismansDupe.java | package com.kisman.cc.module.exploit;
import com.kisman.cc.module.Category;
import com.kisman.cc.module.Module;
import i.gishreloaded.gishcode.utils.visual.ChatUtils;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import static com.kisman.cc.util.Globals.random;
public class KismansDupe extends Module {
public KismansDupe() {
super("KismansDupe", "KismansDupe", Category.EXPLOIT);
}
public void onEnable() {
if(mc.player == null && mc.world == null) return;
ItemStack itemStack = mc.player.getHeldItemMainhand();
if (itemStack.isEmpty()) {
ChatUtils.error("You need to hold an item in hand to dupe!");
super.setToggled(false);
return;
}
int count = random.nextInt(31) + 1;
for (int i = 0; i <= count; i++) {
EntityItem entityItem = mc.player.dropItem(itemStack.copy(), false, true);
if (entityItem != null) mc.world.addEntityToWorld(entityItem.getEntityId(), entityItem);
}
int total = count * itemStack.getCount();
mc.player.sendChatMessage("I just used the Kisman's Dupe and got " + total + " " + itemStack.getDisplayName() + " thanks to kisman.cc!");
super.setToggled(false);
}
}
| 412 | 0.824444 | 1 | 0.824444 | game-dev | MEDIA | 0.96539 | game-dev | 0.90815 | 1 | 0.90815 |
b3dgs/lionheart-remake | 7,905 | com.b3dgs.lionheart.editor/src/com/b3dgs/lionheart/editor/stage/StagePart.java | /*
* Copyright (C) 2013-2024 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com)
*
* 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/>.
*/
package com.b3dgs.lionheart.editor.stage;
import javax.annotation.PostConstruct;
import org.eclipse.e4.ui.services.EMenuService;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import com.b3dgs.lionengine.Constant;
import com.b3dgs.lionengine.Xml;
import com.b3dgs.lionengine.editor.utility.control.UtilButton;
import com.b3dgs.lionengine.editor.utility.dialog.UtilDialog;
import com.b3dgs.lionengine.editor.validator.InputValidator;
import com.b3dgs.lionengine.editor.widget.BrowseWidget;
import com.b3dgs.lionengine.editor.widget.ComboWidget;
import com.b3dgs.lionengine.editor.widget.TextWidget;
import com.b3dgs.lionheart.StageConfig;
import com.b3dgs.lionheart.editor.Activator;
import com.b3dgs.lionheart.landscape.BackgroundType;
import com.b3dgs.lionheart.landscape.ForegroundConfig;
import com.b3dgs.lionheart.landscape.ForegroundType;
/**
* Element properties part.
*/
public class StagePart
{
/** Id. */
public static final String ID = Activator.PLUGIN_ID + ".part.stage";
private BrowseWidget pic;
private BrowseWidget text;
private BrowseWidget music;
private BrowseWidget map;
private BrowseWidget raster;
private ComboWidget<BackgroundType> background;
private ComboWidget<ForegroundType> foreground;
private TextWidget depth;
private TextWidget offset;
private TextWidget speed;
private TextWidget raise;
private Button effect;
/**
* Create part.
*/
public StagePart()
{
super();
}
/**
* Create the composite.
*
* @param parent The parent reference.
* @param menuService The menu service reference.
*/
@PostConstruct
public void createComposite(Composite parent, EMenuService menuService)
{
final Composite naration = new Composite(parent, SWT.NONE);
naration.setLayout(new GridLayout(2, true));
naration.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
pic = new BrowseWidget(naration, Messages.Picture, UtilDialog.getImageFilter(), true);
text = new BrowseWidget(naration, Messages.Text, new String[]
{
"txt"
}, true);
final Composite data = new Composite(parent, SWT.NONE);
data.setLayout(new GridLayout(2, true));
data.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
music = new BrowseWidget(data, Messages.Music, new String[]
{
"sc68"
}, true);
map = new BrowseWidget(data, Messages.Map, UtilDialog.getImageFilter(), true);
final Composite back = new Composite(parent, SWT.NONE);
back.setLayout(new GridLayout(2, false));
back.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
raster = new BrowseWidget(back, Messages.Raster);
background = new ComboWidget<>(back, Messages.Background, false, BackgroundType.values());
final Composite front = new Composite(parent, SWT.NONE);
front.setLayout(new GridLayout(6, false));
front.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
foreground = new ComboWidget<>(front, Messages.Foreground, false, ForegroundType.values());
depth = new TextWidget(front, Messages.Depth, InputValidator.INTEGER_MATCH);
offset = new TextWidget(front, Messages.Offset, InputValidator.INTEGER_MATCH);
speed = new TextWidget(front, Messages.Speed, InputValidator.DOUBLE_MATCH);
raise = new TextWidget(front, Messages.Raise, InputValidator.INTEGER_MATCH);
effect = UtilButton.createCheck(Messages.Effect, front);
}
/**
* Load stage data.
*
* @param stage The stage to load.
*/
public void load(StageConfig stage)
{
pic.setLocation(null);
text.setLocation(null);
raster.setLocation(null);
depth.set(Constant.EMPTY_STRING);
offset.set(Constant.EMPTY_STRING);
speed.set(Constant.EMPTY_STRING);
stage.getPic().ifPresent(p -> pic.setLocation(p.getPath()));
stage.getText().ifPresent(t -> text.setLocation(t));
music.setLocation(stage.getMusic().getPath());
map.setLocation(stage.getMapFile().getPath());
stage.getRasterFolder().ifPresent(r -> raster.setLocation(r));
background.setValue(stage.getBackground());
final ForegroundConfig foregroundConfig = stage.getForeground();
foreground.setValue(foregroundConfig.getType());
foregroundConfig.getWaterDepth().ifPresent(depth::set);
foregroundConfig.getWaterOffset().ifPresent(offset::set);
foregroundConfig.getWaterSpeed().ifPresent(speed::set);
raise.set(foregroundConfig.getWaterRaise());
effect.setSelection(foregroundConfig.getWaterEffect());
}
/**
* Save stage data.
*
* @param root The root reference.
*/
public void save(Xml root)
{
if (pic.getMedia() != null)
{
root.writeString(StageConfig.ATT_STAGE_PIC, pic.getMedia().getPath());
}
if (text.getMedia() != null)
{
root.writeString(StageConfig.ATT_STAGE_TEXT, text.getMedia().getPath());
}
if (music.getMedia() != null)
{
root.createChild(StageConfig.NODE_MUSIC).writeString(StageConfig.ATT_FILE, music.getMedia().getPath());
}
if (map.getMedia() != null)
{
root.createChild(StageConfig.NODE_MAP).writeString(StageConfig.ATT_FILE, map.getMedia().getPath());
}
if (raster.getMedia() != null)
{
root.createChild(StageConfig.NODE_RASTER)
.writeString(StageConfig.ATT_RASTER_FOLDER, raster.getMedia().getPath());
}
root.createChild(StageConfig.NODE_BACKGROUND).writeEnum(StageConfig.ATT_BACKGROUND_TYPE, background.getValue());
final Xml foregroundNode = root.createChild(ForegroundConfig.NODE_FOREGROUND);
foregroundNode.writeEnum(ForegroundConfig.ATT_FOREGROUND_TYPE, foreground.getValue());
depth.getValue().ifPresent(v ->
{
if (v != 0)
{
foregroundNode.writeInteger(ForegroundConfig.ATT_WATER_DEPTH, v);
}
});
offset.getValue().ifPresent(v ->
{
if (v != 0)
{
foregroundNode.writeInteger(ForegroundConfig.ATT_WATER_OFFSET, v);
}
});
speed.getValueDouble().ifPresent(v ->
{
if (Double.compare(v, 0.0) != 0)
{
foregroundNode.writeDouble(ForegroundConfig.ATT_WATER_SPEED, v);
}
});
raise.getValue().ifPresent(v ->
{
if (v != 0)
{
foregroundNode.writeInteger(ForegroundConfig.ATT_WATER_RAISE, v);
}
});
if (!effect.getSelection())
{
foregroundNode.writeBoolean(ForegroundConfig.ATT_WATER_EFFECT, effect.getSelection());
}
}
}
| 412 | 0.934286 | 1 | 0.934286 | game-dev | MEDIA | 0.593843 | game-dev | 0.992718 | 1 | 0.992718 |
CauldronDevelopmentLLC/cbang | 1,530 | src/re2/src/util/utf.h | /*
* The authors of this software are Rob Pike and Ken Thompson.
* Copyright (c) 2002 by Lucent Technologies.
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
* This file and rune.cc have been converted to compile as C++ code
* in name space re2.
*/
#ifndef RE2_UTIL_UTF_H__
#define RE2_UTIL_UTF_H__
#include <stdint.h>
namespace re2 {
typedef signed int Rune; /* Code-point values in Unicode 4.0 are 21 bits wide.*/
enum
{
UTFmax = 4, /* maximum bytes per rune */
Runesync = 0x80, /* cannot represent part of a UTF sequence (<) */
Runeself = 0x80, /* rune and UTF sequences are the same (<) */
Runeerror = 0xFFFD, /* decoding error in UTF */
Runemax = 0x10FFFF, /* maximum rune value */
};
int runetochar(char* s, const Rune* r);
int chartorune(Rune* r, const char* s);
int fullrune(const char* s, int n);
int utflen(const char* s);
char* utfrune(const char*, Rune);
} // namespace re2
#endif // RE2_UTIL_UTF_H__
| 412 | 0.549149 | 1 | 0.549149 | game-dev | MEDIA | 0.421157 | game-dev | 0.600731 | 1 | 0.600731 |
DeNA/Anjin | 2,218 | Tests/Runtime/Agents/DoNothingAgentTest.cs | // Copyright (c) 2023 DeNA Co., Ltd.
// This software is released under the MIT License.
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using DeNA.Anjin.Utilities;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
namespace DeNA.Anjin.Agents
{
public class DoNothingAgentTest
{
[Test]
public async Task Run_cancelTask_stopAgent()
{
var agent = ScriptableObject.CreateInstance<DoNothingAgent>();
agent.Logger = Debug.unityLogger;
agent.Random = new RandomFactory(0).CreateRandom();
agent.name = nameof(Run_cancelTask_stopAgent);
agent.lifespanSec = 0; // Expect indefinite execution
var gameObject = new GameObject();
var cancellationToken = gameObject.GetCancellationTokenOnDestroy();
var task = agent.Run(cancellationToken);
await UniTask.NextFrame();
Object.DestroyImmediate(gameObject);
await UniTask.NextFrame();
Assert.That(task.Status, Is.EqualTo(UniTaskStatus.Canceled));
LogAssert.Expect(LogType.Log, $"Enter {agent.name}.Run()");
LogAssert.Expect(LogType.Log, $"Exit {agent.name}.Run()");
}
[Test]
public async Task Run_lifespanPassed_stopAgent()
{
var agent = ScriptableObject.CreateInstance<DoNothingAgent>();
agent.Logger = Debug.unityLogger;
agent.Random = new RandomFactory(0).CreateRandom();
agent.name = nameof(Run_lifespanPassed_stopAgent);
agent.lifespanSec = 1;
using (var cancellationTokenSource = new CancellationTokenSource())
{
var cancellationToken = cancellationTokenSource.Token;
var task = agent.Run(cancellationToken);
await UniTask.Delay(2000); // Consider overhead
Assert.That(task.Status, Is.EqualTo(UniTaskStatus.Succeeded));
}
LogAssert.Expect(LogType.Log, $"Enter {agent.name}.Run()");
LogAssert.Expect(LogType.Log, $"Exit {agent.name}.Run()");
}
}
}
| 412 | 0.923955 | 1 | 0.923955 | game-dev | MEDIA | 0.895449 | game-dev,testing-qa | 0.808242 | 1 | 0.808242 |
CppCXY/EmmyLuaCodeStyle | 16,610 | LuaParser/src/Ast/LuaSyntaxTree.cpp | #include "LuaParser/Ast/LuaSyntaxTree.h"
#include "LuaParser/Lexer/LuaTokenTypeDetail.h"
#include "LuaParser/Parse/LuaParser.h"
#include "Util/format.h"
#include <algorithm>
LuaSyntaxTree::LuaSyntaxTree()
: _source(),
_tokenIndex(0) {
}
void LuaSyntaxTree::BuildTree(LuaParser &p) {
_errors.swap(p.GetErrors());
_source = p.GetLuaFile();
StartNode(LuaSyntaxNodeKind::File, p);
auto &events = p.GetEvents();
std::vector<LuaSyntaxNodeKind> parents;
for (std::size_t i = 0; i != events.size(); i++) {
switch (events[i].Type) {
case MarkEventType::NodeStart: {
auto e = events[i];
if (e.U.Start.Kind == LuaSyntaxNodeKind::None) {
continue;
}
parents.push_back(e.U.Start.Kind);
auto parentPos = e.U.Start.Parent;
while (parentPos > 0) {
if (events[parentPos].Type == MarkEventType::NodeStart) {
auto &pe = events[parentPos];
parents.push_back(pe.U.Start.Kind);
parentPos = pe.U.Start.Parent;
pe.U.Start.Kind = LuaSyntaxNodeKind::None;
} else {
break;
}
}
// When debug here will throw error
for (auto rIt = parents.rbegin(); rIt != parents.rend(); rIt++) {
StartNode(*rIt, p);
}
parents.clear();
break;
}
case MarkEventType::EatToken: {
EatComments(p);
EatToken(p);
EatInlineComment(p);
break;
}
case MarkEventType::NodeEnd: {
FinishNode(p);
break;
}
default: {
break;
}
}
}
FinishNode(p);
if (!_nodeOrTokens.empty()) {
_syntaxNodes.reserve(_nodeOrTokens.size() - 1);
for (std::size_t i = 0; i != _nodeOrTokens.size() - 1; i++) {
_syntaxNodes.emplace_back(i + 1);
}
}
}
void LuaSyntaxTree::StartNode(LuaSyntaxNodeKind kind, LuaParser &p) {
if (!IsEatAllComment(kind)) {
EatComments(p);
BuildNode(kind);
} else {
BuildNode(kind);
}
}
void LuaSyntaxTree::EatComments(LuaParser &p) {
auto &tokens = p.GetTokens();
for (auto index = _tokenIndex; index < tokens.size(); index++) {
switch (tokens[index].TokenType) {
case TK_SHORT_COMMENT:
case TK_LONG_COMMENT:
case TK_SHEBANG: {
EatToken(p);
break;
}
default: {
return;
}
}
}
}
void LuaSyntaxTree::EatInlineComment(LuaParser &p) {
auto &tokens = p.GetTokens();
if (_tokenIndex > 0 && _tokenIndex < tokens.size()) {
auto index = _tokenIndex;
switch (tokens[index].TokenType) {
case TK_SHORT_COMMENT:
case TK_LONG_COMMENT:
case TK_SHEBANG: {
auto prevToken = tokens[index - 1];
if (_source->GetLine(prevToken.Range.GetEndOffset()) == _source->GetLine(tokens[index].Range.StartOffset)) {
EatToken(p);
}
break;
}
default: {
return;
}
}
}
}
void LuaSyntaxTree::EatToken(LuaParser &p) {
auto &token = p.GetTokens()[_tokenIndex];
_tokenIndex++;
BuildToken(token);
}
void LuaSyntaxTree::FinishNode(LuaParser &p) {
if (!_nodePosStack.empty()) {
auto nodePos = _nodePosStack.top();
auto &node = _nodeOrTokens[nodePos];
if (node.Type == NodeOrTokenType::Node &&
IsEatAllComment(node.Data.NodeKind)) {
EatComments(p);
} else {
if (_tokenIndex < p.GetTokens().size() && _tokenIndex > 0) {
EatInlineComment(p);
}
}
_nodePosStack.pop();
}
}
void LuaSyntaxTree::BuildNode(LuaSyntaxNodeKind kind) {
auto currentPos = _nodeOrTokens.size();
auto ¤tNode = _nodeOrTokens.emplace_back(kind);
if (!_nodePosStack.empty()) {
auto parentIndex = _nodePosStack.top();
auto &parentNode = _nodeOrTokens[parentIndex];
if (parentNode.FirstChild == 0) {
parentNode.FirstChild = currentPos;
parentNode.LastChild = currentPos;
} else {
auto &lastNode = _nodeOrTokens[parentNode.LastChild];
lastNode.NextSibling = currentPos;
currentNode.PrevSibling = parentNode.LastChild;
parentNode.LastChild = currentPos;
}
currentNode.Parent = parentIndex;
}
_nodePosStack.push(currentPos);
}
void LuaSyntaxTree::BuildToken(LuaToken &token) {
auto currentNodePos = _nodeOrTokens.size();
auto currentTokenPos = _tokens.size();
_tokens.emplace_back(token, currentNodePos);
auto ¤tToken = _nodeOrTokens.emplace_back(currentTokenPos);
if (!_nodePosStack.empty()) {
auto parentIndex = _nodePosStack.top();
auto &parentNode = _nodeOrTokens[parentIndex];
if (parentNode.FirstChild == 0) {
parentNode.FirstChild = currentNodePos;
parentNode.LastChild = currentNodePos;
} else {
auto &lastNode = _nodeOrTokens[parentNode.LastChild];
lastNode.NextSibling = currentNodePos;
currentToken.PrevSibling = parentNode.LastChild;
parentNode.LastChild = currentNodePos;
}
currentToken.Parent = parentIndex;
}
}
const LuaSource &LuaSyntaxTree::GetFile() const {
return *_source;
}
std::size_t LuaSyntaxTree::GetStartOffset(std::size_t index) const {
if (index == 0) {
return 0;
}
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Node) {
auto child = n.FirstChild;
while (IsNode(child)) {
child = GetFirstChild(child);
}
if (child != 0) {
return _tokens[_nodeOrTokens[child].Data.TokenIndex].Start;
} else {
for (auto prevToken = index - 1; prevToken > 0; prevToken--) {
if (_nodeOrTokens[prevToken].Type == NodeOrTokenType::Token) {
auto &token = _tokens[_nodeOrTokens[prevToken].Data.TokenIndex];
return token.Start + token.Length;
}
}
}
} else {
return _tokens[n.Data.TokenIndex].Start;
}
}
return 0;
}
std::size_t LuaSyntaxTree::GetEndOffset(std::size_t index) const {
if (index == 0) {
return 0;
}
std::size_t nodeOrTokenIndex = index;
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Node) {
auto child = n.LastChild;
while (IsNode(child)) {
child = GetLastChild(child);
}
if (child != 0) {
nodeOrTokenIndex = child;
} else {
for (auto prevToken = index - 1; prevToken > 0; prevToken--) {
if (_nodeOrTokens[prevToken].Type == NodeOrTokenType::Token) {
auto &token = _tokens[_nodeOrTokens[prevToken].Data.TokenIndex];
return token.Start + token.Length;
}
}
nodeOrTokenIndex = 0;
}
}
} else if (!_nodeOrTokens.empty()) {
nodeOrTokenIndex = _nodeOrTokens.size() - 1;
} else {
nodeOrTokenIndex = 0;
};
if (nodeOrTokenIndex != 0) {
auto &token = _tokens[_nodeOrTokens[nodeOrTokenIndex].Data.TokenIndex];
if (token.Length != 0) {
return token.Start + token.Length - 1;
} else {
return token.Start;
}
}
return 0;
}
TextRange LuaSyntaxTree::GetTokenRange(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Token) {
auto &token = _tokens[n.Data.TokenIndex];
return TextRange(token.Start, token.Length);
}
}
return TextRange();
}
std::size_t LuaSyntaxTree::GetNextSibling(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
return _nodeOrTokens[index].NextSibling;
}
return 0;
}
std::size_t LuaSyntaxTree::GetPrevSibling(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
return _nodeOrTokens[index].PrevSibling;
}
return 0;
}
std::size_t LuaSyntaxTree::GetFirstChild(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
return _nodeOrTokens[index].FirstChild;
}
return 0;
}
std::size_t LuaSyntaxTree::GetLastChild(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
return _nodeOrTokens[index].LastChild;
}
return 0;
}
std::size_t LuaSyntaxTree::GetFirstToken(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Node) {
auto child = n.FirstChild;
while (IsNode(child)) {
child = GetFirstChild(child);
}
return child;
} else {
return index;
}
}
return 0;
}
std::size_t LuaSyntaxTree::GetLastToken(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Node) {
auto child = n.LastChild;
while (IsNode(child)) {
child = GetLastChild(child);
}
return child;
} else {
return index;
}
}
return 0;
}
std::size_t LuaSyntaxTree::GetPrevToken(std::size_t index) const {
if (index == 0) {
return 0;
}
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Token) {
auto tokenIndex = n.Data.TokenIndex;
if (tokenIndex != 0) {
return _tokens[tokenIndex - 1].NodeIndex;
}
} else {// Node, 可能存在无元素节点
for (auto nodeIndex = index - 1; nodeIndex > 0; nodeIndex--) {
if (IsToken(nodeIndex)) {
return nodeIndex;
}
}
}
}
return 0;
}
std::size_t LuaSyntaxTree::GetNextToken(std::size_t index) const {
if (index == 0) {
return 0;
}
std::size_t tokenNodeIndex = 0;
if (index < _nodeOrTokens.size()) {
auto &n = _nodeOrTokens[index];
if (n.Type == NodeOrTokenType::Token) {
tokenNodeIndex = index;
} else {// Node, 可能存在无元素节点
auto lastTokenIndex = GetLastToken(index);
if (lastTokenIndex != 0) {
tokenNodeIndex = lastTokenIndex;
} else {
// 当前节点是空节点, 则向前查找, 查找前一个token, 就可以轻松得到下一个token
for (auto nodeIndex = index - 1; nodeIndex > 0; nodeIndex--) {
if (IsToken(nodeIndex)) {
tokenNodeIndex = nodeIndex;
break;
}
}
}
}
}
if (tokenNodeIndex != 0) {
auto &token = _nodeOrTokens[tokenNodeIndex];
if (token.Data.TokenIndex + 1 < _tokens.size()) {
return _tokens[token.Data.TokenIndex + 1].NodeIndex;
}
}
return 0;
}
std::size_t LuaSyntaxTree::GetParent(std::size_t index) const {
if (index < _nodeOrTokens.size()) {
return _nodeOrTokens[index].Parent;
}
return 0;
}
LuaSyntaxNodeKind LuaSyntaxTree::GetNodeKind(std::size_t index) const {
if (!IsNode(index)) {
return LuaSyntaxNodeKind::None;
}
return _nodeOrTokens[index].Data.NodeKind;
}
LuaTokenKind LuaSyntaxTree::GetTokenKind(std::size_t index) const {
if (!IsToken(index)) {
return LuaTokenKind(0);
}
return _tokens[_nodeOrTokens[index].Data.TokenIndex].Kind;
}
bool LuaSyntaxTree::IsNode(std::size_t index) const {
if (index == 0 || (_nodeOrTokens.size() <= index)) {
return false;
}
return _nodeOrTokens[index].Type == NodeOrTokenType::Node;
}
bool LuaSyntaxTree::IsToken(std::size_t index) const {
if (index == 0 || (_nodeOrTokens.size() <= index)) {
return false;
}
return _nodeOrTokens[index].Type == NodeOrTokenType::Token;
}
const std::vector<LuaSyntaxNode> &LuaSyntaxTree::GetSyntaxNodes() const {
return _syntaxNodes;
}
std::vector<LuaSyntaxNode> LuaSyntaxTree::GetTokens() const {
std::vector<LuaSyntaxNode> results;
if (_tokens.empty()) {
return results;
}
results.reserve(_tokens.size());
for (auto &token: _tokens) {
results.emplace_back(token.NodeIndex);
}
return results;
}
LuaSyntaxNode LuaSyntaxTree::GetRootNode() const {
return LuaSyntaxNode(1);
}
LuaSyntaxNode LuaSyntaxTree::GetTokenBeforeOffset(std::size_t offset) const {
if (_tokens.empty()) {
return LuaSyntaxNode();
}
auto tokenIt = std::partition_point(
_tokens.begin(), _tokens.end(),
[offset](const IncrementalToken &token) {
return token.Start <= offset;
});
std::size_t tokenIndex = 0;
if (tokenIt == _tokens.end()) {
tokenIndex = _tokens.size() - 1;
} else if (tokenIt == _tokens.begin()) {
tokenIndex = 0;
} else {
tokenIndex = tokenIt - _tokens.begin() - 1;
}
auto &token = _tokens[tokenIndex];
if (token.Start <= offset) {
return LuaSyntaxNode(token.NodeIndex);
}
return LuaSyntaxNode();
}
LuaSyntaxNode LuaSyntaxTree::GetTokenAtOffset(std::size_t offset) const {
if (_tokens.empty()) {
return LuaSyntaxNode();
}
auto tokenIt = std::partition_point(
_tokens.begin(), _tokens.end(),
[offset](const IncrementalToken &token) {
return token.Start <= offset;
});
std::size_t tokenIndex = 0;
if (tokenIt == _tokens.end()) {
tokenIndex = _tokens.size() - 1;
} else if (tokenIt == _tokens.begin()) {
tokenIndex = 0;
} else {
tokenIndex = tokenIt - _tokens.begin() - 1;
}
auto &token = _tokens[tokenIndex];
if (token.Start <= offset && (token.Start + token.Length) > offset) {
return LuaSyntaxNode(token.NodeIndex);
}
return LuaSyntaxNode();
}
std::string LuaSyntaxTree::GetDebugView() {
std::string debugView;
debugView.append("{ Lua Syntax Tree }\n");
auto root = GetRootNode();
std::stack<LuaSyntaxNode> traverseStack;
std::size_t indent = 1;
traverseStack.push(root);
// 非递归深度优先遍历
while (!traverseStack.empty()) {
LuaSyntaxNode node = traverseStack.top();
if (node.IsNode(*this)) {
traverseStack.top() = LuaSyntaxNode(0);
auto children = node.GetChildren(*this);
for (auto rIt = children.rbegin(); rIt != children.rend(); rIt++) {
traverseStack.push(*rIt);
}
debugView.resize(debugView.size() + indent, '\t');
debugView.append(util::format("{{ Node, index: {}, SyntaxKind: {} }}\n",
node.GetIndex(),
detail::debug::GetSyntaxKindDebugName(node.GetSyntaxKind(*this))));
indent++;
} else if (node.IsToken(*this)) {
traverseStack.pop();
debugView.resize(debugView.size() + indent, '\t');
debugView.append(util::format("{{ Token, index: {}, TokenKind: {} }}\n",
node.GetIndex(),
node.GetText(*this)));
} else {
traverseStack.pop();
indent--;
}
}
return debugView;
}
bool LuaSyntaxTree::HasError() const {
return !_errors.empty();
}
bool LuaSyntaxTree::IsEatAllComment(LuaSyntaxNodeKind kind) const {
return kind == LuaSyntaxNodeKind::Block || kind == LuaSyntaxNodeKind::TableFieldList || kind == LuaSyntaxNodeKind::File;
}
const std::vector<LuaParseError> &LuaSyntaxTree::GetErrors() const {
return _errors;
}
| 412 | 0.94026 | 1 | 0.94026 | game-dev | MEDIA | 0.363013 | game-dev | 0.99202 | 1 | 0.99202 |
e3kskoy7wqk/Firefox-for-windows-7 | 3,193 | 2025-06-23.8f20a89077ea0afabda793dbc8362f3e3ff0ffea/ef82d8c7986e8064a01a6145e33b93894f5201d4.diff | diff --git a/widget/windows/nsAppShell.cpp b/widget/windows/nsAppShell.cpp
index 40707022fde7..29e02d565a27 100644
--- a/widget/windows/nsAppShell.cpp
+++ b/widget/windows/nsAppShell.cpp
@@ -106,7 +106,23 @@ class WinWakeLockListener final : public nsIDOMMozWakeLockListener {
context.Version = POWER_REQUEST_CONTEXT_VERSION;
context.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
context.Reason.SimpleReasonString = RequestTypeLPWSTR(aType);
- HANDLE handle = PowerCreateRequest(&context);
+ typedef HANDLE (WINAPI* PowerCreateRequestPtr)(PREASON_CONTEXT);
+ typedef BOOL (WINAPI* PowerSetRequestPtr)(HANDLE, POWER_REQUEST_TYPE);
+
+ static PowerCreateRequestPtr PowerCreateRequestFn = NULL;
+ static PowerSetRequestPtr PowerSetRequestFn = NULL;
+
+ if (!PowerCreateRequestFn || !PowerSetRequestFn) {
+ HMODULE module = GetModuleHandle(L"kernel32.dll");
+ PowerCreateRequestFn = reinterpret_cast<PowerCreateRequestPtr>(
+ GetProcAddress(module, "PowerCreateRequest"));
+ PowerSetRequestFn = reinterpret_cast<PowerSetRequestPtr>(
+ GetProcAddress(module, "PowerSetRequest"));
+
+ if (!PowerCreateRequestFn || !PowerSetRequestFn)
+ return nullptr;
+ }
+ HANDLE handle = PowerCreateRequestFn(&context);
if (!handle) {
WAKE_LOCK_LOG("Failed to create handle for %s, error=%lu",
RequestTypeStr(aType), GetLastError());
@@ -154,7 +170,23 @@ class WinWakeLockListener final : public nsIDOMMozWakeLockListener {
return;
}
- if (PowerSetRequest(handle, aType)) {
+ typedef HANDLE (WINAPI* PowerCreateRequestPtr)(PREASON_CONTEXT);
+ typedef BOOL (WINAPI* PowerSetRequestPtr)(HANDLE, POWER_REQUEST_TYPE);
+
+ static PowerCreateRequestPtr PowerCreateRequestFn = NULL;
+ static PowerSetRequestPtr PowerSetRequestFn = NULL;
+
+ if (!PowerCreateRequestFn || !PowerSetRequestFn) {
+ HMODULE module = GetModuleHandle(L"kernel32.dll");
+ PowerCreateRequestFn = reinterpret_cast<PowerCreateRequestPtr>(
+ GetProcAddress(module, "PowerCreateRequest"));
+ PowerSetRequestFn = reinterpret_cast<PowerSetRequestPtr>(
+ GetProcAddress(module, "PowerSetRequest"));
+
+ if (!PowerCreateRequestFn || !PowerSetRequestFn)
+ return;
+ }
+ if (PowerSetRequestFn(handle, aType)) {
WAKE_LOCK_LOG("Requested %s lock", RequestTypeStr(aType));
} else {
WAKE_LOCK_LOG("Failed to request %s lock, error=%lu",
@@ -170,7 +202,16 @@ class WinWakeLockListener final : public nsIDOMMozWakeLockListener {
}
WAKE_LOCK_LOG("Prepare to release wakelock for %s", RequestTypeStr(aType));
- if (!PowerClearRequest(GetHandle(aType), aType)) {
+ typedef BOOL (WINAPI* PowerClearRequestPtr)(HANDLE, POWER_REQUEST_TYPE);
+ HMODULE module = GetModuleHandle(L"kernel32.dll");
+ PowerClearRequestPtr PowerClearRequestFn =
+ reinterpret_cast<PowerClearRequestPtr>(
+ GetProcAddress(module, "PowerClearRequest"));
+
+ if (!PowerClearRequestFn)
+ return;
+
+ if (!PowerClearRequestFn(GetHandle(aType), aType)) {
WAKE_LOCK_LOG("Failed to release %s lock, error=%lu",
RequestTypeStr(aType), GetLastError());
return;
| 412 | 0.908741 | 1 | 0.908741 | game-dev | MEDIA | 0.66531 | game-dev | 0.530406 | 1 | 0.530406 |
holycake/mhsj | 2,018 | d/sea/npc/shark.c | inherit NPC;
string *first_name = ({ "花皮", "绿背", "双头", "虎齿"});
string *name_words = ({ "鲨"});
void create()
{
string name;
name = first_name[random(sizeof(first_name))];
name += name_words[random(sizeof(name_words))];
set_name(name, ({ "shark" }) );
set("race", "野兽");
set("age", 20);
set("long", "一只模样凶恶的大鲨鱼。\n");
set("str", 20);
set("cor", 30);
set("max_kee", 800);
set("max_sen", 800);
set("limbs", ({ "头部", "身体", "前鳍", "尾巴", "肚皮"}) );
set("verbs", ({ "bite"}) );
set("combat_exp", 100000+random(10000));
set_skill("dodge", 100);
set_skill("unarmed", 100);
set_skill("parry", 100);
set_temp("apply/damage", 20);
set_temp("apply/armor", 20);
set_weight(500000);
setup();
}
void init()
{
::init();
add_action("do_train", "train");
}
int do_train()
{
object me,who;
me =this_object();
who=this_player();
if(me->is_fighting())
return notify_fail("这只海兽正在战斗。\n");
if((string)who->query("family/family_name")!="东海龙宫")
return notify_fail("什么?\n");
message_vision("$N对$n大喊一声:孽畜,看你猖狂到几时!\n\n", who,me);
message_vision("$N扑上来和$n扭打到一起。\n",me,who);
me->kill_ob(who);
who->kill_ob(me);
COMBAT_D->do_attack(me, who, query_temp("weapon"));
me->set("owner",who->query("id"));
return 1;
}
void die()
{
string owner;
object owner_ob;
owner = query("owner");
if(!owner) {
::die(); // added by mon.
return;
}
owner_ob= find_player(owner);
if( owner_ob && (object)query_temp("last_damage_from") == owner_ob ) {
owner_ob->add_temp("dragonforce_practice",
owner_ob->query("spi")*2+random(30));
message_vision("$N低头缩尾,以示降服。\n",this_object());
message_vision("$N灰溜溜地游走了。\n",this_object());
destruct(this_object());
return;
}
::die();
}
| 412 | 0.924686 | 1 | 0.924686 | game-dev | MEDIA | 0.929974 | game-dev | 0.782762 | 1 | 0.782762 |
rudderbucky/shellcore | 17,742 | Assets/Scripts/Game Object Definitions/ShellPart.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// The part script for the shell around a core of a Shellcore (will be salvaged to make a more general part class)
/// </summary>
[RequireComponent(typeof(SpriteRenderer))]
public class ShellPart : MonoBehaviour
{
float detachedTime; // time since detachment
public ShellPart parent = null;
public List<ShellPart> children = new List<ShellPart>();
[SerializeField]
private bool hasDetached; // is the part detached
[HideInInspector]
public SpriteRenderer spriteRenderer;
private Rigidbody2D rigid;
[HideInInspector]
public Entity craft;
public float partHealth; // health of the part (half added to shell, quarter to core)
public float partMass; // mass of the part
private float currentHealth; // current health of part
public bool detachible = true;
private bool collectible;
private int faction;
private Draggable draggable;
private bool rotationDirection = true;
private float rotationOffset;
public GameObject shooter;
public string SpawnID { get; set; }
public EntityBlueprint.PartInfo info;
public string droppedSectorName;
public static int partShader = 0;
public static List<Material> shaderMaterials = null;
public Vector2 colliderExtents;
public Matrix4x4 colliderMatrix;
public bool weapon = false;
public bool IsDamaged()
{
return currentHealth < partHealth;
}
public bool GetDetached()
{
return hasDetached;
}
public int GetFaction()
{
return faction;
}
public void SetCollectible(bool collectible)
{
this.collectible = collectible;
// try setting the part to shiny
if (collectible)
{
SetPartColor(FactionManager.GetFactionColor(GetFaction()));
if (!transform.Find("Minimap Image"))
{
GameObject childObject = new GameObject("Minimap Image");
childObject.transform.SetParent(transform, false);
SpriteRenderer renderer = childObject.AddComponent<SpriteRenderer>();
renderer.sprite = ResourceManager.GetAsset<Sprite>("minimap_sprite");
childObject.AddComponent<MinimapLockRotationScript>().Initialize(); // initialize the minimap dot
}
if (!shinyCheck)
{
shinyCheck = true;
ShinyCheck();
}
}
}
public float GetPartMass()
{
return partMass;
}
public float GetPartHealth()
{
return partHealth; // part health
}
public bool IsAdjacent(ShellPart part)
{
return part.GetComponent<SpriteRenderer>().bounds.Intersects(GetComponent<SpriteRenderer>().bounds);
}
/// <summary>
/// Build Part
/// </summary>
/// <param name="blueprint">blueprint of the part</param>
public static GameObject BuildPart(PartBlueprint blueprint, Entity craft)
{
if (shaderMaterials == null)
{
shaderMaterials = new List<Material>();
shaderMaterials.Add(ResourceManager.GetAsset<Material>("part_shader0"));
shaderMaterials.Add(ResourceManager.GetAsset<Material>("part_shader1"));
}
GameObject holder;
if (!GameObject.Find("Part Holder"))
{
holder = new GameObject("Part Holder");
}
else
{
holder = GameObject.Find("Part Holder");
}
GameObject obj = Instantiate(ResourceManager.GetAsset<GameObject>("base_part"));
obj.transform.SetParent(holder.transform);
//Part sprite
var spriteRenderer = obj.GetComponent<SpriteRenderer>();
spriteRenderer.material = shaderMaterials[partShader];
spriteRenderer.sprite = ResourceManager.GetAsset<Sprite>(blueprint.spriteID);
var part = obj.GetComponent<ShellPart>();
part.partMass = blueprint.mass;
part.partHealth = blueprint.health;
part.currentHealth = part.partHealth;
part.detachible = blueprint.detachible;
part.craft = craft;
var partSys = obj.GetComponent<ParticleSystem>();
var sh = partSys.shape;
if (spriteRenderer.sprite)
{
sh.scale = spriteRenderer.sprite.bounds.extents * 2;
}
var e = partSys.emission;
e.rateOverTime = new ParticleSystem.MinMaxCurve(3 * (blueprint.size + 1));
e.enabled = false;
part.partSys = partSys;
if (spriteRenderer.sprite)
{
part.colliderExtents = spriteRenderer.sprite.bounds.extents;
}
else
{
part.colliderExtents = Vector2.one * 0.5f;
}
return obj;
}
/// <summary>
/// Detach the part from the Shellcore
/// </summary>
public void Detach(bool drop = false)
{
if (hasDetached) return;
if (name != "Shell Sprite")
{
transform.SetParent(null, true);
}
for (int i = 0; i < transform.childCount; i++)
{
if (transform.GetChild(i).name.Contains("Glow"))
{
Destroy(transform.GetChild(i).gameObject);
}
}
detachedTime = Time.time; // update detached time
hasDetached = true; // has detached now
gameObject.AddComponent<Rigidbody2D>(); // add a rigidbody (this might become permanent)
if (name != "Shell Sprite")
{
var group = gameObject.AddComponent<UnityEngine.Rendering.SortingGroup>();
if (group) group.sortingLayerName = "Air Entities";
}
rigid = GetComponent<Rigidbody2D>();
rigid.gravityScale = 0; // adjust the rigid body
rigid.angularDrag = 0;
float randomDir = Random.Range(0f, 360f);
var vec = (new Vector2(Mathf.Cos(randomDir), Mathf.Sin(randomDir))) + (craft && craft.GetComponent<Rigidbody2D>() ? craft.GetComponent<Rigidbody2D>().velocity * 2F : Vector2.zero);
vec = vec.normalized;
if (name != "Shell Sprite")
{
rigid.AddForce(vec * 200f);
}
//rigid.AddTorque(150f * ((Random.Range(0, 2) == 0) ? 1 : -1));
rotationDirection = (Random.Range(0, 2) == 0);
gameObject.layer = 9;
rotationOffset = Random.Range(0f, 360f);
droppedSectorName = SectorManager.instance.current.sectorName;
spriteRenderer.sortingLayerName = "Air Entities";
if (shooter)
{
shooter.GetComponent<SpriteRenderer>().sortingLayerName = "Air Entities";
}
GetComponentInChildren<Ability>()?.SetDestroyed(true);
// when a part detaches it should always be completely visible
var renderers = GetComponentsInChildren<SpriteRenderer>();
foreach (var rend in renderers)
{
rend.color += new Color(0, 0, 0, 1);
}
}
void OnDestroy()
{
if (parent)
{
parent.children.Remove(this);
}
if (AIData.strayParts.Contains(this))
{
AIData.strayParts.Remove(this);
}
}
public void Awake()
{
//Find sprite renderer
spriteRenderer = GetComponent<SpriteRenderer>();
}
// What is this supposed to do?
public void EditorPlayerPartCheck()
{
if (craft is PlayerCore player)
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // create a ray
RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll(ray, Mathf.Infinity); // get an array of all hits
foreach (var hit in hits)
{
if (hit.transform == transform)
{
var pos = CameraScript.instance.GetWorldPositionOfMouse();
}
}
}
}
}
public void SetFaction(int faction)
{
this.faction = faction;
}
public void Start()
{
// initialize instance fields
hasDetached = false;
spriteRenderer.enabled = true;
Destroy(GetComponent<Rigidbody2D>()); // remove rigidbody
// Drone part health penalty
if (craft as Drone)
{
currentHealth /= 4;
}
if (craft is ICarrier)
{
currentHealth = partHealth = partHealth * 2;
}
if (!craft)
craft = transform.root.GetComponent<Entity>();
if (craft)
faction = craft.faction.factionID;
gameObject.layer = 0;
if (GetComponent<Ability>())
{
GetComponent<Ability>().Part = this;
}
if (info.shiny && partSys) // shell does not have a Particle System, and it also can't be shiny
{
StartEmitting();
}
else
{
StartCoroutine(InitColorLerp(0));
}
}
ParticleSystem partSys;
private void AimShooter()
{
if (shooter)
{
if (DialogueSystem.isInCutscene) return;
var weapon = GetComponent<WeaponAbility>();
var targ = weapon.GetTarget();
if (weapon as Ion)
{
float bearing = (weapon as Ion).GetBeamAngle();
shooter.transform.eulerAngles = new Vector3(0, 0, bearing - 90);
return;
}
if (targ != null)
{
var targEntity = targ.GetComponent<IDamageable>();
if (targEntity != null && !FactionManager.IsAllied(targEntity.GetFaction(), craft.faction))
{
Vector3 targeterPos = targ.position;
Vector3 diff = targeterPos - shooter.transform.position;
shooter.transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg) - 90);
}
else
{
shooter.transform.eulerAngles = new Vector3(0, 0, 0);
}
}
else
{
shooter.transform.eulerAngles = new Vector3(0, 0, 0);
}
}
}
/// <summary>
/// Makes the part blink like in the original game
/// </summary>
void Blink()
{
spriteRenderer.enabled = Time.time % 0.125F > 0.0625F; // math stuff that blinks the part
if (shooter)
{
shooter.GetComponent<SpriteRenderer>().enabled = spriteRenderer.enabled;
}
}
private bool shinyCheck = false;
private bool colorLerped = false;
// Update is called once per frame
void Update()
{
if (DevConsoleScript.bugTrackPartDebug && !craft)
{
Debug.LogWarning($"Active part at {transform.position} without craft.");
}
EditorPlayerPartCheck();
if (spriteRenderer)
{
if (shaderMaterials == null)
{
shaderMaterials = new List<Material>();
shaderMaterials.Add(ResourceManager.GetAsset<Material>("part_shader0"));
shaderMaterials.Add(ResourceManager.GetAsset<Material>("part_shader1"));
}
spriteRenderer.material = shaderMaterials[partShader];
}
if (!craft && !hasDetached)
{
hasDetached = true;
detachedTime = 0;
}
if (hasDetached && Time.time - detachedTime < 1) // checks if the part has been detached for more than a second (hardcoded)
{
if (name != "Shell Sprite" && spriteRenderer.sprite)
{
Blink(); // blink
}
else
{
spriteRenderer.enabled = false; // disable sprite renderer
if (shooter)
{
shooter.SetActive(false);
}
}
//rigid.rotation = rigid.rotation + (rotationDirection ? 1f : -1.0f) * 360f * Time.deltaTime;
transform.eulerAngles = new Vector3(0, 0, (rotationDirection ? 1.0f : -1.0f) * 100f * Time.time + rotationOffset);
}
else if (hasDetached)
{
if (DevConsoleScript.bugTrackPartDebug && !craft)
{
Debug.LogWarning($"Active part at {transform.position} going through detachment process.");
}
if (collectible && detachible && !SectorManager.instance.current.partDropsDisabled)
{
rigid.drag = 25;
// add "Draggable" component so that shellcores can grab the part
if (!draggable)
{
draggable = gameObject.AddComponent<Draggable>();
}
spriteRenderer.enabled = true;
if (shooter)
{
shooter.GetComponent<SpriteRenderer>().enabled = true;
}
spriteRenderer.sortingOrder = 0;
transform.eulerAngles = new Vector3(0, 0, (rotationDirection ? 1.0f : -1.0f) * 100f * Time.time + rotationOffset);
}
else
{
if (name != "Shell Sprite" && !(craft as PlayerCore))
{
if (DevConsoleScript.bugTrackPartDebug && !craft)
{
Debug.LogWarning($"Active part at {transform.position} is being destroyed.");
}
Destroy(gameObject);
}
else
{
if (craft is PlayerCore player && name != "Shell Sprite")
{
player.partsToDestroy.Add(this);
}
spriteRenderer.enabled = false; // disable sprite renderer
if (shooter)
{
shooter.SetActive(false);
}
}
}
}
else if (weapon)
{
AimShooter();
}
}
private void ShinyCheck()
{
if (Random.Range(0, 4000) >= 3999 - Mathf.Min(400, Radar.GetRadarChain() * 10))
{
info.shiny = true;
Radar.ResetRadarChain();
StartEmitting();
}
}
private void StartEmitting()
{
var emission = partSys.emission;
emission.enabled = true;
StartCoroutine(InitColorLerp(0));
}
public void lerpColors()
{
StartCoroutine(InitColorLerp(0));
}
private IEnumerator InitColorLerp(float lerpVal)
{
colorLerped = false;
while (lerpVal < 1)
{
lerpVal += 0.05F;
lerpVal = Mathf.Min(lerpVal, 1);
var lerpedColor = Color.Lerp(Color.gray, info.shiny ? FactionManager.GetFactionShinyColor(faction) : FactionManager.GetFactionColor(faction), lerpVal);
SetPartColor(lerpedColor);
yield return new WaitForSeconds(0.025F);
}
colorLerped = true;
}
/// <summary>
/// Take part damage, if it is damaged too much remove the part
/// </summary>
/// <param name="damage">damage to deal</param>
public void TakeDamage(float damage)
{
if (!craft)
{
return;
}
if (!detachible)
{
craft.TakeCoreDamage(damage); // undetachible = core part
}
currentHealth -= damage;
if (currentHealth <= 0 && detachible)
{
craft.RemovePart(this);
}
if (partHealth != 0 && colorLerped)
{
var color = Color.Lerp(Color.gray, info.shiny ? FactionManager.GetFactionShinyColor(faction) : FactionManager.GetFactionColor(faction), currentHealth / partHealth);
SetPartColor(color);
}
}
private MaterialPropertyBlock block;
// ignores parameter alpha, since stealthing changes it
public void SetPartColor(Color color)
{
color.a = (craft && craft.IsInvisible ? (craft.faction.factionID == 0 ? 0.2f : 0f) : color.a);
if (spriteRenderer) spriteRenderer.color = color;
if (shooter && shooter.GetComponent<SpriteRenderer>())
{
shooter.GetComponent<SpriteRenderer>().color = spriteRenderer.color;
}
ParticleSystem.ColorOverLifetimeModule partSysColorMod;
if (partSys)
{
partSysColorMod = partSys.colorOverLifetime;
partSysColorMod.color = new ParticleSystem.MinMaxGradient(color);
}
SetPartShader(color);
}
private void SetPartShader(Color color)
{
if (block == null)
{
block = new();
if (spriteRenderer && spriteRenderer.sprite && spriteRenderer.sprite.texture)
block.SetTexture("_MainTex", spriteRenderer.sprite.texture);
}
if (block != null)
{
block.SetColor("_PerRendColor", color);
if (craft && craft.blueprint && !string.IsNullOrEmpty(craft.blueprint.coreShellSpriteID) && craft.blueprint.coreShellSpriteID.Contains("station_sprite"))
{
block.SetFloat("_Min", 0.07F);
}
if (!detachible)
block.SetFloat("_Symmetry", 0);
else block.SetFloat("_Symmetry", 1);
}
if (shaderMaterials != null
&& shaderMaterials.Count > 0
&& block != null
&& spriteRenderer) spriteRenderer.SetPropertyBlock(block);
}
}
| 412 | 0.897771 | 1 | 0.897771 | game-dev | MEDIA | 0.973985 | game-dev | 0.953762 | 1 | 0.953762 |
neraliu/tainted-phantomjs | 6,534 | src/qt/src/3rdparty/webkit/Source/WebCore/generated/JSSVGPathSegClosePath.cpp | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "JSSVGPathSegClosePath.h"
#include "SVGPathSegClosePath.h"
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSSVGPathSegClosePath);
/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGPathSegClosePathTableValues[2] =
{
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPathSegClosePathConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPathSegClosePathTable = { 2, 1, JSSVGPathSegClosePathTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGPathSegClosePathConstructorTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPathSegClosePathConstructorTable = { 1, 0, JSSVGPathSegClosePathConstructorTableValues, 0 };
class JSSVGPathSegClosePathConstructor : public DOMConstructorObject {
public:
JSSVGPathSegClosePathConstructor(JSC::ExecState*, JSC::Structure*, JSDOMGlobalObject*);
virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
static const JSC::ClassInfo s_info;
static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
protected:
static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSSVGPathSegClosePathConstructor::s_info = { "SVGPathSegClosePathConstructor", &DOMConstructorObject::s_info, &JSSVGPathSegClosePathConstructorTable, 0 };
JSSVGPathSegClosePathConstructor::JSSVGPathSegClosePathConstructor(ExecState* exec, Structure* structure, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(structure, globalObject)
{
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSSVGPathSegClosePathPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSSVGPathSegClosePathConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGPathSegClosePathConstructor, JSDOMWrapper>(exec, &JSSVGPathSegClosePathConstructorTable, this, propertyName, slot);
}
bool JSSVGPathSegClosePathConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSSVGPathSegClosePathConstructor, JSDOMWrapper>(exec, &JSSVGPathSegClosePathConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSSVGPathSegClosePathPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPathSegClosePathPrototypeTable = { 1, 0, JSSVGPathSegClosePathPrototypeTableValues, 0 };
const ClassInfo JSSVGPathSegClosePathPrototype::s_info = { "SVGPathSegClosePathPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSSVGPathSegClosePathPrototypeTable, 0 };
JSObject* JSSVGPathSegClosePathPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSSVGPathSegClosePath>(exec, globalObject);
}
const ClassInfo JSSVGPathSegClosePath::s_info = { "SVGPathSegClosePath", &JSSVGPathSeg::s_info, &JSSVGPathSegClosePathTable, 0 };
JSSVGPathSegClosePath::JSSVGPathSegClosePath(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<SVGPathSegClosePath> impl)
: JSSVGPathSeg(structure, globalObject, impl)
{
ASSERT(inherits(&s_info));
}
JSObject* JSSVGPathSegClosePath::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSSVGPathSegClosePathPrototype(exec->globalData(), globalObject, JSSVGPathSegClosePathPrototype::createStructure(exec->globalData(), JSSVGPathSegPrototype::self(exec, globalObject)));
}
bool JSSVGPathSegClosePath::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGPathSegClosePath, Base>(exec, &JSSVGPathSegClosePathTable, this, propertyName, slot);
}
bool JSSVGPathSegClosePath::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSSVGPathSegClosePath, Base>(exec, &JSSVGPathSegClosePathTable, this, propertyName, descriptor);
}
JSValue jsSVGPathSegClosePathConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSSVGPathSegClosePath* domObject = static_cast<JSSVGPathSegClosePath*>(asObject(slotBase));
return JSSVGPathSegClosePath::getConstructor(exec, domObject->globalObject());
}
JSValue JSSVGPathSegClosePath::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSSVGPathSegClosePathConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
}
#endif // ENABLE(SVG)
| 412 | 0.576555 | 1 | 0.576555 | game-dev | MEDIA | 0.301924 | game-dev | 0.532425 | 1 | 0.532425 |
focus-creative-games/luban_examples | 1,073 | Projects/Dart_json/lib/gen/test/TbDemoGroup_E.dart |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
import 'dart:collection';
import '/gen/test/DemoGroup.dart';
import '/gen/Tables.dart';
final class TbDemoGroup_E {
final List<DemoGroup> _dataList = [];
final Map<int, DemoGroup> _dataMap = {};
TbDemoGroup_E(List<dynamic> _array) {
for (var _buf in _array) {
DemoGroup item = DemoGroup.deserialize(_buf);
_dataList.add(item);
_dataMap[item.id] = item;
}
}
DemoGroup? getOrDefault(int id) {
if (_dataMap.containsKey(id)) {
return _dataMap[id];
}
return null;
}
void resolveRef(Tables tables)
{
for(var _v in _dataList)
{
_v.resolveRef(tables);
}
}
}
| 412 | 0.848624 | 1 | 0.848624 | game-dev | MEDIA | 0.579381 | game-dev,graphics-rendering | 0.891918 | 1 | 0.891918 |
MaartenKok8/PneumaticCraft | 1,343 | api/cofh/api/energy/IEnergyStorage.java | package cofh.api.energy;
/**
* An energy storage is the unit of interaction with Energy inventories.<br>
* This is not to be implemented on TileEntities. This is for internal use only.
* <p>
* A reference implementation can be found at {@link EnergyStorage}.
*
* @author King Lemming
*
*/
public interface IEnergyStorage {
/**
* Adds energy to the storage. Returns quantity of energy that was accepted.
*
* @param maxReceive
* Maximum amount of energy to be inserted.
* @param simulate
* If TRUE, the insertion will only be simulated.
* @return Amount of energy that was (or would have been, if simulated) accepted by the storage.
*/
int receiveEnergy(int maxReceive, boolean simulate);
/**
* Removes energy from the storage. Returns quantity of energy that was removed.
*
* @param maxExtract
* Maximum amount of energy to be extracted.
* @param simulate
* If TRUE, the extraction will only be simulated.
* @return Amount of energy that was (or would have been, if simulated) extracted from the storage.
*/
int extractEnergy(int maxExtract, boolean simulate);
/**
* Returns the amount of energy currently stored.
*/
int getEnergyStored();
/**
* Returns the maximum amount of energy that can be stored.
*/
int getMaxEnergyStored();
}
| 412 | 0.664772 | 1 | 0.664772 | game-dev | MEDIA | 0.331164 | game-dev | 0.603584 | 1 | 0.603584 |
fairygui/FairyGUI-layabox | 3,270 | source/src/fairygui/GTextInput.ts | ///<reference path="GTextField.ts"/>
namespace fgui {
export class GTextInput extends GTextField {
declare _displayObject: Laya.Input;
constructor() {
super();
}
protected createDisplayObject(): void {
this._displayObject = new Laya.Input();
this._displayObject["$owner"] = this;
}
public get nativeInput(): Laya.Input {
return this._displayObject;
}
public get password(): boolean {
return this._displayObject.type == "password";
}
public set password(value: boolean) {
if (value)
this._displayObject.type = "password";
else
this._displayObject.type = "text";
}
public get keyboardType(): string {
return this._displayObject.type;
}
public set keyboardType(value: string) {
this._displayObject.type = value;
}
public set editable(value: boolean) {
this._displayObject.editable = value;
}
public get editable(): boolean {
return this._displayObject.editable;
}
public set maxLength(value: number) {
this._displayObject.maxChars = value;
}
public get maxLength(): number {
return this._displayObject.maxChars;
}
public set promptText(value: string) {
var str: string = UBBParser.defaultParser.parse(value, true);
this._displayObject.prompt = str;
if (UBBParser.defaultParser.lastColor)
this._displayObject.promptColor = UBBParser.defaultParser.lastColor;
}
public get promptText(): string {
return this._displayObject.prompt;
}
public set restrict(value: string) {
this._displayObject.restrict = value;
}
public get restrict(): string {
return this._displayObject.restrict;
}
public get singleLine(): boolean {
return this._singleLine;
}
public set singleLine(value: boolean) {
super.singleLine = value;
this._displayObject.multiline = !value;
}
public requestFocus(): void {
this._displayObject.focus = true;
super.requestFocus();
}
public setup_beforeAdd(buffer: ByteBuffer, beginPos: number): void {
super.setup_beforeAdd(buffer, beginPos);
buffer.seek(beginPos, 4);
var str: string = buffer.readS();
if (str != null)
this.promptText = str;
str = buffer.readS();
if (str != null)
this._displayObject.restrict = str;
var iv: number = buffer.getInt32();
if (iv != 0)
this._displayObject.maxChars = iv;
iv = buffer.getInt32();
if (iv != 0) {
if (iv == 4)
this.keyboardType = Laya.Input.TYPE_NUMBER;
else if (iv == 3)
this.keyboardType = Laya.Input.TYPE_URL;
}
if (buffer.readBool())
this.password = true;
}
}
} | 412 | 0.934741 | 1 | 0.934741 | game-dev | MEDIA | 0.655632 | game-dev,desktop-app | 0.913008 | 1 | 0.913008 |
PacktPublishing/Mastering-Cpp-Game-Development | 5,263 | Chapter11/Include/bullet/LinearMath/btQuickprof.h |
/***************************************************************************************************
**
** Real-Time Hierarchical Profiling for Game Programming Gems 3
**
** by Greg Hjelstrom & Byon Garrabrant
**
***************************************************************************************************/
// Credits: The Clock class was inspired by the Timer classes in
// Ogre (www.ogre3d.org).
#ifndef BT_QUICK_PROF_H
#define BT_QUICK_PROF_H
#include "btScalar.h"
#define USE_BT_CLOCK 1
#ifdef USE_BT_CLOCK
///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling.
class btClock
{
public:
btClock();
btClock(const btClock& other);
btClock& operator=(const btClock& other);
~btClock();
/// Resets the initial reference time.
void reset();
/// Returns the time in ms since the last call to reset or since
/// the btClock was created.
unsigned long int getTimeMilliseconds();
/// Returns the time in us since the last call to reset or since
/// the Clock was created.
unsigned long int getTimeMicroseconds();
/// Returns the time in s since the last call to reset or since
/// the Clock was created.
btScalar getTimeSeconds();
private:
struct btClockData* m_data;
};
#endif //USE_BT_CLOCK
//To disable built-in profiling, please comment out next line
#define BT_NO_PROFILE 1
#ifndef BT_NO_PROFILE
#include <stdio.h>//@todo remove this, backwards compatibility
#include "btAlignedAllocator.h"
#include <new>
///A node in the Profile Hierarchy Tree
class CProfileNode {
public:
CProfileNode( const char * name, CProfileNode * parent );
~CProfileNode( void );
CProfileNode * Get_Sub_Node( const char * name );
CProfileNode * Get_Parent( void ) { return Parent; }
CProfileNode * Get_Sibling( void ) { return Sibling; }
CProfileNode * Get_Child( void ) { return Child; }
void CleanupMemory();
void Reset( void );
void Call( void );
bool Return( void );
const char * Get_Name( void ) { return Name; }
int Get_Total_Calls( void ) { return TotalCalls; }
float Get_Total_Time( void ) { return TotalTime; }
void* GetUserPointer() const {return m_userPtr;}
void SetUserPointer(void* ptr) { m_userPtr = ptr;}
protected:
const char * Name;
int TotalCalls;
float TotalTime;
unsigned long int StartTime;
int RecursionCounter;
CProfileNode * Parent;
CProfileNode * Child;
CProfileNode * Sibling;
void* m_userPtr;
};
///An iterator to navigate through the tree
class CProfileIterator
{
public:
// Access all the children of the current parent
void First(void);
void Next(void);
bool Is_Done(void);
bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); }
void Enter_Child( int index ); // Make the given child the new parent
void Enter_Largest_Child( void ); // Make the largest child the new parent
void Enter_Parent( void ); // Make the current parent's parent the new parent
// Access the current child
const char * Get_Current_Name( void ) { return CurrentChild->Get_Name(); }
int Get_Current_Total_Calls( void ) { return CurrentChild->Get_Total_Calls(); }
float Get_Current_Total_Time( void ) { return CurrentChild->Get_Total_Time(); }
void* Get_Current_UserPointer( void ) { return CurrentChild->GetUserPointer(); }
void Set_Current_UserPointer(void* ptr) {CurrentChild->SetUserPointer(ptr);}
// Access the current parent
const char * Get_Current_Parent_Name( void ) { return CurrentParent->Get_Name(); }
int Get_Current_Parent_Total_Calls( void ) { return CurrentParent->Get_Total_Calls(); }
float Get_Current_Parent_Total_Time( void ) { return CurrentParent->Get_Total_Time(); }
protected:
CProfileNode * CurrentParent;
CProfileNode * CurrentChild;
CProfileIterator( CProfileNode * start );
friend class CProfileManager;
};
///The Manager for the Profile system
class CProfileManager {
public:
static void Start_Profile( const char * name );
static void Stop_Profile( void );
static void CleanupMemory(void)
{
Root.CleanupMemory();
}
static void Reset( void );
static void Increment_Frame_Counter( void );
static int Get_Frame_Count_Since_Reset( void ) { return FrameCounter; }
static float Get_Time_Since_Reset( void );
static CProfileIterator * Get_Iterator( void )
{
return new CProfileIterator( &Root );
}
static void Release_Iterator( CProfileIterator * iterator ) { delete ( iterator); }
static void dumpRecursive(CProfileIterator* profileIterator, int spacing);
static void dumpAll();
private:
static CProfileNode Root;
static CProfileNode * CurrentNode;
static int FrameCounter;
static unsigned long int ResetTime;
};
///ProfileSampleClass is a simple way to profile a function's scope
///Use the BT_PROFILE macro at the start of scope to time
class CProfileSample {
public:
CProfileSample( const char * name )
{
CProfileManager::Start_Profile( name );
}
~CProfileSample( void )
{
CProfileManager::Stop_Profile();
}
};
#define BT_PROFILE( name ) CProfileSample __profile( name )
#else
#define BT_PROFILE( name )
#endif //#ifndef BT_NO_PROFILE
#endif //BT_QUICK_PROF_H
| 412 | 0.97278 | 1 | 0.97278 | game-dev | MEDIA | 0.777482 | game-dev | 0.891557 | 1 | 0.891557 |
fulpstation/fulpstation | 13,144 | code/modules/research/xenobiology/crossbreeding/regenerative.dm | /*
Regenerative extracts:
Work like a legion regenerative core.
Has a unique additional effect.
*/
/obj/item/slimecross/regenerative
name = "regenerative extract"
desc = "It's filled with a milky substance, and pulses like a heartbeat."
effect = "regenerative"
icon_state = "regenerative"
effect_desc = "Completely heals your injuries, with no extra effects."
/obj/item/slimecross/regenerative/proc/core_effect(mob/living/carbon/human/target, mob/user)
return
/obj/item/slimecross/regenerative/proc/core_effect_before(mob/living/carbon/human/target, mob/user)
return
/obj/item/slimecross/regenerative/interact_with_atom(atom/interacting_with, mob/living/user, list/modifiers)
if(!isliving(interacting_with))
return
var/mob/living/H = interacting_with
if(H.stat == DEAD)
to_chat(user, span_warning("[src] will not work on the dead!"))
return ITEM_INTERACT_BLOCKING
if(H != user)
user.visible_message(span_notice("[user] crushes [src] over [H], the milky goo quickly regenerating all of [H.p_their()] injuries!"),
span_notice("You squeeze [src], and it bursts over [H], the milky goo regenerating [H.p_their()] injuries."))
else
user.visible_message(span_notice("[user] crushes [src] over [user.p_them()]self, the milky goo quickly regenerating all of [user.p_their()] injuries!"),
span_notice("You squeeze [src], and it bursts in your hand, splashing you with milky goo which quickly regenerates your injuries!"))
core_effect_before(H, user)
user.do_attack_animation(interacting_with)
H.revive(HEAL_ALL & ~HEAL_REFRESH_ORGANS)
core_effect(H, user)
playsound(H, 'sound/effects/splat.ogg', 40, TRUE)
qdel(src)
return ITEM_INTERACT_SUCCESS
/obj/item/slimecross/regenerative/grey
colour = SLIME_TYPE_GREY //Has no bonus effect.
effect_desc = "Fully heals the target and does nothing else."
/obj/item/slimecross/regenerative/orange
colour = SLIME_TYPE_ORANGE
/obj/item/slimecross/regenerative/orange/core_effect_before(mob/living/target, mob/user)
target.visible_message(span_warning("The [src] boils over!"))
for(var/turf/targetturf in RANGE_TURFS(1,target))
if(!locate(/obj/effect/hotspot) in targetturf)
new /obj/effect/hotspot(targetturf)
/obj/item/slimecross/regenerative/purple
colour = SLIME_TYPE_PURPLE
effect_desc = "Fully heals the target and injects them with some regen jelly."
/obj/item/slimecross/regenerative/purple/core_effect(mob/living/target, mob/user)
target.reagents.add_reagent(/datum/reagent/medicine/regen_jelly,10)
/obj/item/slimecross/regenerative/blue
colour = SLIME_TYPE_BLUE
effect_desc = "Fully heals the target and makes the floor wet."
/obj/item/slimecross/regenerative/blue/core_effect(mob/living/target, mob/user)
if(isturf(target.loc))
var/turf/open/T = get_turf(target)
T.MakeSlippery(TURF_WET_WATER, min_wet_time = 10, wet_time_to_add = 5)
target.visible_message(span_warning("The milky goo in the extract gets all over the floor!"))
/obj/item/slimecross/regenerative/metal
colour = SLIME_TYPE_METAL
effect_desc = "Fully heals the target and encases the target in a locker."
/obj/item/slimecross/regenerative/metal/core_effect(mob/living/target, mob/user)
target.visible_message(span_warning("The milky goo hardens and reshapes itself, encasing [target]!"))
var/obj/structure/closet/C = new /obj/structure/closet(target.loc)
C.name = "slimy closet"
C.desc = "Looking closer, it seems to be made of a sort of solid, opaque, metal-like goo."
if(target.mob_size > C.max_mob_size) //Prevents capturing megafauna or other large mobs in the closets
C.bust_open()
C.visible_message(span_warning("[target] is too big, and immediately breaks \the [C.name] open!"))
else //This can't be allowed to actually happen to the too-big mobs or it breaks some actions
target.forceMove(C)
/obj/item/slimecross/regenerative/yellow
colour = SLIME_TYPE_YELLOW
effect_desc = "Fully heals the target and fully recharges a single item on the target."
/obj/item/slimecross/regenerative/yellow/core_effect(mob/living/target, mob/user)
var/list/batteries = list()
for(var/obj/item/stock_parts/power_store/C in target.get_all_contents())
if(C.charge < C.maxcharge)
batteries += C
if(batteries.len)
var/obj/item/stock_parts/power_store/ToCharge = pick(batteries)
ToCharge.charge = ToCharge.maxcharge
to_chat(target, span_notice("You feel a strange electrical pulse, and one of your electrical items was recharged."))
/obj/item/slimecross/regenerative/darkpurple
colour = SLIME_TYPE_DARK_PURPLE
effect_desc = "Fully heals the target and gives them purple clothing if they are naked."
/obj/item/slimecross/regenerative/darkpurple/core_effect(mob/living/target, mob/user)
var/equipped = 0
equipped += target.equip_to_slot_or_del(new /obj/item/clothing/shoes/sneakers/purple(null), ITEM_SLOT_FEET)
equipped += target.equip_to_slot_or_del(new /obj/item/clothing/under/color/lightpurple(null), ITEM_SLOT_ICLOTHING)
equipped += target.equip_to_slot_or_del(new /obj/item/clothing/gloves/color/purple(null), ITEM_SLOT_GLOVES)
equipped += target.equip_to_slot_or_del(new /obj/item/clothing/head/soft/purple(null), ITEM_SLOT_HEAD)
if(equipped > 0)
target.visible_message(span_notice("The milky goo congeals into clothing!"))
/obj/item/slimecross/regenerative/darkblue
colour = SLIME_TYPE_DARK_BLUE
effect_desc = "Fully heals the target and fireproofs their clothes."
/obj/item/slimecross/regenerative/darkblue/core_effect(mob/living/target, mob/user)
if(!ishuman(target))
return
var/mob/living/carbon/human/H = target
var/fireproofed = FALSE
if(H.get_item_by_slot(ITEM_SLOT_OCLOTHING))
fireproofed = TRUE
var/obj/item/clothing/C = H.get_item_by_slot(ITEM_SLOT_OCLOTHING)
fireproof(C)
if(H.get_item_by_slot(ITEM_SLOT_HEAD))
fireproofed = TRUE
var/obj/item/clothing/C = H.get_item_by_slot(ITEM_SLOT_HEAD)
fireproof(C)
if(fireproofed)
target.visible_message(span_notice("Some of [target]'s clothing gets coated in the goo, and turns blue!"))
/obj/item/slimecross/regenerative/darkblue/proc/fireproof(obj/item/clothing/clothing_piece)
clothing_piece.name = "fireproofed [clothing_piece.name]"
clothing_piece.remove_atom_colour(WASHABLE_COLOUR_PRIORITY)
clothing_piece.add_atom_colour(color_transition_filter(COLOR_NAVY, SATURATION_OVERRIDE), FIXED_COLOUR_PRIORITY)
clothing_piece.max_heat_protection_temperature = FIRE_IMMUNITY_MAX_TEMP_PROTECT
clothing_piece.heat_protection = clothing_piece.body_parts_covered
clothing_piece.resistance_flags |= FIRE_PROOF
/obj/item/slimecross/regenerative/silver
colour = SLIME_TYPE_SILVER
effect_desc = "Fully heals the target and makes their belly feel round and full."
/obj/item/slimecross/regenerative/silver/core_effect(mob/living/target, mob/user)
target.set_nutrition(NUTRITION_LEVEL_FULL - 1)
to_chat(target, span_notice("You feel satiated."))
/obj/item/slimecross/regenerative/bluespace
colour = SLIME_TYPE_BLUESPACE
effect_desc = "Fully heals the target and teleports them to where this core was created."
var/turf/open/T
/obj/item/slimecross/regenerative/bluespace/core_effect(mob/living/target, mob/user)
var/turf/old_location = get_turf(target)
if(do_teleport(target, T, channel = TELEPORT_CHANNEL_QUANTUM)) //despite being named a bluespace teleportation method the quantum channel is used to preserve precision teleporting with a bag of holding
old_location.visible_message(span_warning("[target] disappears in a shower of sparks!"))
to_chat(target, span_danger("The milky goo teleports you somewhere it remembers!"))
if(HAS_TRAIT(target, TRAIT_NO_TELEPORT))
old_location.visible_message(span_warning("[target] sparks briefly, but is prevented from teleporting!"))
/obj/item/slimecross/regenerative/bluespace/Initialize(mapload)
. = ..()
T = get_turf(src)
/obj/item/slimecross/regenerative/sepia
colour = SLIME_TYPE_SEPIA
effect_desc = "Fully heals the target. After 10 seconds, relocate the target to the initial position the core was used with their previous health status."
/obj/item/slimecross/regenerative/sepia/core_effect_before(mob/living/target, mob/user)
to_chat(target, span_notice("You try to forget how you feel."))
target.AddComponent(/datum/component/dejavu)
/obj/item/slimecross/regenerative/cerulean
colour = SLIME_TYPE_CERULEAN
effect_desc = "Fully heals the target and makes a second regenerative core with no special effects."
/obj/item/slimecross/regenerative/cerulean/core_effect(mob/living/target, mob/user)
src.forceMove(user.loc)
var/obj/item/slimecross/X = new /obj/item/slimecross/regenerative(user.loc)
X.name = name
X.desc = desc
user.put_in_active_hand(X)
to_chat(user, span_notice("Some of the milky goo congeals in your hand!"))
/obj/item/slimecross/regenerative/pyrite
colour = SLIME_TYPE_PYRITE
effect_desc = "Fully heals and randomly colors the target."
/obj/item/slimecross/regenerative/pyrite/core_effect(mob/living/target, mob/user)
target.visible_message(span_warning("The milky goo coating [target] leaves [target.p_them()] a different color!"))
target.add_atom_colour(color_transition_filter(rgb(rand(0,255), rand(0,255), rand(0,255)), SATURATION_OVERRIDE), WASHABLE_COLOUR_PRIORITY)
/obj/item/slimecross/regenerative/red
colour = SLIME_TYPE_RED
effect_desc = "Fully heals the target and injects them with some ephedrine."
/obj/item/slimecross/regenerative/red/core_effect(mob/living/target, mob/user)
to_chat(target, span_notice("You feel... <i>faster.</i>"))
target.reagents.add_reagent(/datum/reagent/medicine/ephedrine,3)
/obj/item/slimecross/regenerative/green
colour = SLIME_TYPE_GREEN
effect_desc = "Fully heals the target and changes the spieces or color of a slime or jellyperson."
/obj/item/slimecross/regenerative/green/core_effect(mob/living/target, mob/user)
if(isslime(target))
target.visible_message(span_warning("The [target] suddenly changes color!"))
var/mob/living/basic/slime/target_slime = target
target_slime.random_colour()
if(isjellyperson(target))
target.reagents.add_reagent(/datum/reagent/mutationtoxin/jelly,5)
/obj/item/slimecross/regenerative/pink
colour = SLIME_TYPE_PINK
effect_desc = "Fully heals the target and injects them with some krokodil."
/obj/item/slimecross/regenerative/pink/core_effect(mob/living/target, mob/user)
to_chat(target, span_notice("You feel more calm."))
target.reagents.add_reagent(/datum/reagent/drug/krokodil,4)
/obj/item/slimecross/regenerative/gold
colour = SLIME_TYPE_GOLD
effect_desc = "Fully heals the target and produces a random coin."
/obj/item/slimecross/regenerative/gold/core_effect(mob/living/target, mob/user)
var/newcoin = get_random_coin()
var/obj/item/coin/C = new newcoin(target.loc)
playsound(C, 'sound/items/coinflip.ogg', 50, TRUE)
target.put_in_hand(C)
/obj/item/slimecross/regenerative/oil
colour = SLIME_TYPE_OIL
effect_desc = "Fully heals the target and flashes everyone in sight."
/obj/item/slimecross/regenerative/oil/core_effect(mob/living/target, mob/user)
playsound(src, 'sound/items/weapons/flash.ogg', 100, TRUE)
for(var/mob/living/L in view(user,7))
L.flash_act()
/obj/item/slimecross/regenerative/black
colour = SLIME_TYPE_BLACK
effect_desc = "Fully heals the target and creates an imperfect duplicate of them made of slime, that fakes their death."
/obj/item/slimecross/regenerative/black/core_effect_before(mob/living/target, mob/user)
var/dummytype = target.type
if(ismegafauna(target)) //Prevents megafauna duping in a lame way
dummytype = /mob/living/basic/slime
to_chat(user, span_warning("The milky goo flows over [target], falling into a weak puddle."))
var/mob/living/dummy = new dummytype(target.loc)
to_chat(target, span_notice("The milky goo flows from your skin, forming an imperfect copy of you."))
if(iscarbon(target))
var/mob/living/carbon/T = target
var/mob/living/carbon/D = dummy
T.dna.transfer_identity(D)
D.updateappearance(mutcolor_update=1)
D.real_name = T.real_name
dummy.adjustBruteLoss(target.getBruteLoss())
dummy.adjustFireLoss(target.getFireLoss())
dummy.adjustToxLoss(target.getToxLoss())
dummy.death()
/obj/item/slimecross/regenerative/lightpink
colour = SLIME_TYPE_LIGHT_PINK
effect_desc = "Fully heals the target and also heals the user."
/obj/item/slimecross/regenerative/lightpink/core_effect(mob/living/target, mob/user)
if(!isliving(user))
return
if(target == user)
return
var/mob/living/U = user
U.revive(HEAL_ALL & ~HEAL_REFRESH_ORGANS)
to_chat(U, span_notice("Some of the milky goo sprays onto you, as well!"))
/obj/item/slimecross/regenerative/adamantine
colour = SLIME_TYPE_ADAMANTINE
effect_desc = "Fully heals the target and boosts their armor."
/obj/item/slimecross/regenerative/adamantine/core_effect(mob/living/target, mob/user) //WIP - Find out why this doesn't work.
target.apply_status_effect(/datum/status_effect/slimeskin)
/obj/item/slimecross/regenerative/rainbow
colour = SLIME_TYPE_RAINBOW
effect_desc = "Fully heals the target and temporarily makes them immortal, but pacifistic."
/obj/item/slimecross/regenerative/rainbow/core_effect(mob/living/target, mob/user)
target.apply_status_effect(/datum/status_effect/rainbow_protection)
| 412 | 0.93322 | 1 | 0.93322 | game-dev | MEDIA | 0.973591 | game-dev | 0.928713 | 1 | 0.928713 |
Citadel-Station-13/Citadel-Station-13 | 1,295 | code/_onclick/hud/drones.dm | /datum/hud/dextrous/drone/New(mob/owner)
..()
var/atom/movable/screen/inventory/inv_box
inv_box = new /atom/movable/screen/inventory(null, src)
inv_box.name = "internal storage"
inv_box.icon = ui_style
inv_box.icon_state = "suit_storage"
// inv_box.icon_full = "template"
inv_box.screen_loc = ui_drone_storage
inv_box.slot_id = ITEM_SLOT_DEX_STORAGE
static_inventory += inv_box
inv_box = new /atom/movable/screen/inventory(null, src)
inv_box.name = "head/mask"
inv_box.icon = ui_style
inv_box.icon_state = "mask"
// inv_box.icon_full = "template"
inv_box.screen_loc = ui_drone_head
inv_box.slot_id = ITEM_SLOT_HEAD
static_inventory += inv_box
for(var/atom/movable/screen/inventory/inv in (static_inventory + toggleable_inventory))
if(inv.slot_id)
inv_slots[TOBITSHIFT(inv.slot_id) + 1] = inv
inv.update_icon()
/datum/hud/dextrous/drone/persistent_inventory_update()
if(!mymob)
return
var/mob/living/simple_animal/drone/D = mymob
if(hud_shown)
if(D.internal_storage)
D.internal_storage.screen_loc = ui_drone_storage
D.client.screen += D.internal_storage
if(D.head)
D.head.screen_loc = ui_drone_head
D.client.screen += D.head
else
if(D.internal_storage)
D.internal_storage.screen_loc = null
if(D.head)
D.head.screen_loc = null
..()
| 412 | 0.730616 | 1 | 0.730616 | game-dev | MEDIA | 0.986102 | game-dev | 0.974293 | 1 | 0.974293 |
copasi/COPASI | 38,525 | copasi/sbml/unittests/test000078.cpp | // Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "test000078.h"
#include <sstream>
#include "utilities.hpp"
#include "copasi/CopasiDataModel/CDataModel.h"
#include "copasi/model/CModel.h"
#include "copasi/model/CMetab.h"
#include "copasi/model/CCompartment.h"
#include "copasi/model/CReaction.h"
#include "copasi/function/CEvaluationNode.h"
#include "copasi/function/CEvaluationNodeNumber.h"
#include "copasi/function/CEvaluationNodeVariable.h"
#include "copasi/function/CExpression.h"
#include "copasi/function/CEvaluationTree.h"
#include "copasi/function/CFunctionDB.h"
#include "copasi/function/CKinFunction.h"
#include "copasi/function/CEvaluationTree.h"
#include "copasi/function/CFunctionParameters.h"
#include "copasi/function/CFunctionParameter.h"
#include "sbml/SBMLDocument.h"
#include "sbml/Model.h"
#include "copasi/core/CRootContainer.h"
CDataModel* test000078::pCOPASIDATAMODEL = NULL;
void test000078::setUp()
{
// Create the root container.
CRootContainer::init(0, NULL, false);
// Create the global data model.
pCOPASIDATAMODEL = CRootContainer::addDatamodel();
}
void test000078::tearDown()
{
CRootContainer::destroy();
}
void test000078::test_l2v4_import_unordered_functions()
{
CDataModel* pDataModel = pCOPASIDATAMODEL;
try
{
CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING1));
}
catch (...)
{
// there should not be any exceptions
CPPUNIT_ASSERT(false);
}
CModel* pModel = pDataModel->getModel();
CPPUNIT_ASSERT(pModel != NULL);
CPPUNIT_ASSERT(pModel->getQuantityUnitEnum() == CUnit::Mol);
CPPUNIT_ASSERT(pModel->getVolumeUnitEnum() == CUnit::l);
CPPUNIT_ASSERT(pModel->getTimeUnitEnum() == CUnit::s);
// check if the function definitions were imported correctly
CFunctionDB* pFunDB = CRootContainer::getFunctionList();
const CEvaluationTree* pFun = pFunDB->findFunction("function_1");
CPPUNIT_ASSERT(pFun != NULL);
const CKinFunction* pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 1 parameter called k
// expression is 3.0 * k
const CFunctionParameters* pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 1);
const CFunctionParameter* pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("k"));
const CEvaluationNode* pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::MULTIPLY);
const CEvaluationNode* pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::NUMBER);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DOUBLE);
const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pChild);
CPPUNIT_ASSERT(pNumberNode != NULL);
CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 3.0) / 3.0) < 1e-6);
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
const CEvaluationNodeVariable* pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("k"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild == NULL);
pFun = pFunDB->findFunction("function_2");
CPPUNIT_ASSERT(pFun != NULL);
pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 2 parameters called A and B
// expression is A + B
pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 2);
pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("A"));
pFunParam = (*pFunParams)[1];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("B"));
pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::PLUS);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("B"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("A"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild == NULL);
pFun = pFunDB->findFunction("function_3");
CPPUNIT_ASSERT(pFun != NULL);
pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 2 parameters called k and C
// expression is C - (k * 1.3)
pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 2);
pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("k"));
pFunParam = (*pFunParams)[1];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("C"));
pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::MINUS);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("C"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::MULTIPLY);
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getChild());
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("k"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::NUMBER);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DOUBLE);
pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pChild);
CPPUNIT_ASSERT(pNumberNode != NULL);
CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 1.3) / 1.3) < 1e-6);
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pFun = pFunDB->findFunction("function_4");
CPPUNIT_ASSERT(pFun != NULL);
pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 2 parameters called x and y
// expression is function_2(x,y)/2.0
pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 2);
pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("x"));
pFunParam = (*pFunParams)[1];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("y"));
pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::DIVIDE);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::CALL);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::FUNCTION);
const CEvaluationNodeCall* pCallNode = dynamic_cast<const CEvaluationNodeCall*>(pChild);
CPPUNIT_ASSERT(pCallNode != NULL);
CPPUNIT_ASSERT(pCallNode->getData() == std::string("function_2"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("x"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("y"));
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild()->getSibling());
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::NUMBER);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DOUBLE);
pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pChild);
CPPUNIT_ASSERT(pNumberNode != NULL);
CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 2.0) / 2.0) < 1e-6);
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild == NULL);
pFun = pFunDB->findFunction("function_5");
CPPUNIT_ASSERT(pFun != NULL);
pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 3 parameters called a, b and c
// expression is function_3(c,a) + (function_1(b) - 5.23)
pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 3);
pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("a"));
pFunParam = (*pFunParams)[1];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("b"));
pFunParam = (*pFunParams)[2];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("c"));
pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::PLUS);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::CALL);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::FUNCTION);
pCallNode = dynamic_cast<const CEvaluationNodeCall*>(pChild);
CPPUNIT_ASSERT(pCallNode != NULL);
CPPUNIT_ASSERT(pCallNode->getData() == std::string("function_3"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("c"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("a"));
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild()->getSibling());
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::OPERATOR);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::MINUS);
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::CALL);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::FUNCTION);
pCallNode = dynamic_cast<const CEvaluationNodeCall*>(pChild);
CPPUNIT_ASSERT(pCallNode != NULL);
CPPUNIT_ASSERT(pCallNode->getData() == std::string("function_1"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("b"));
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild()->getSibling()->getChild()->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::NUMBER);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DOUBLE);
pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pChild);
CPPUNIT_ASSERT(pNumberNode != NULL);
CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 5.23) / 5.23) < 1e-6);
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
pFun = pFunDB->findFunction("function_6");
CPPUNIT_ASSERT(pFun != NULL);
pKinFun = dynamic_cast<const CKinFunction*>(pFun);
CPPUNIT_ASSERT(pKinFun != NULL);
// 3 parameters called k1, k2 and k3
// expression is function_5(k1,k2,k3)
pFunParams = &pKinFun->getVariables();
CPPUNIT_ASSERT(pFunParams != NULL);
CPPUNIT_ASSERT(pFunParams->size() == 3);
pFunParam = (*pFunParams)[0];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("k1"));
pFunParam = (*pFunParams)[1];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("k2"));
pFunParam = (*pFunParams)[2];
CPPUNIT_ASSERT(pFunParam != NULL);
CPPUNIT_ASSERT(pFunParam->getObjectName() == std::string("k3"));
pRoot = pKinFun->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(pRoot->mainType() == CEvaluationNode::MainType::CALL);
CPPUNIT_ASSERT(pRoot->subType() == CEvaluationNode::SubType::FUNCTION);
pCallNode = dynamic_cast<const CEvaluationNodeCall*>(pRoot);
CPPUNIT_ASSERT(pCallNode != NULL);
CPPUNIT_ASSERT(pCallNode->getData() == std::string("function_5"));
pChild = dynamic_cast<const CEvaluationNode*>(pRoot->getChild());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("k1"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("k2"));
pChild = dynamic_cast<const CEvaluationNode*>(pChild->getSibling());
CPPUNIT_ASSERT(pChild != NULL);
CPPUNIT_ASSERT(pChild->mainType() == CEvaluationNode::MainType::VARIABLE);
CPPUNIT_ASSERT(pChild->subType() == CEvaluationNode::SubType::DEFAULT);
pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pChild);
CPPUNIT_ASSERT(pVarNode != NULL);
CPPUNIT_ASSERT(pVarNode->getData() == std::string("k3"));
CPPUNIT_ASSERT(pChild->getSibling() == NULL);
CPPUNIT_ASSERT(pModel->getCompartments().size() == 1);
const CCompartment* pCompartment = pModel->getCompartments()[0];
CPPUNIT_ASSERT(pCompartment != NULL);
CPPUNIT_ASSERT(pCompartment->getStatus() == CModelEntity::Status::FIXED);
CPPUNIT_ASSERT(pModel->getMetabolites().size() == 6);
// check metabolites
const CMetab* pMetab = pModel->getMetabolites()[0];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "A");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::REACTIONS);
pMetab = pModel->getMetabolites()[1];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "B");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::REACTIONS);
pMetab = pModel->getMetabolites()[2];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "C");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::ASSIGNMENT);
// check assignment
const CEvaluationTree* pTree = pMetab->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_5");
pMetab = pModel->getMetabolites()[3];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "D");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::ODE);
// check ode
pTree = pMetab->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_2");
pMetab = pModel->getMetabolites()[4];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "E");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::ODE);
// check ode
pTree = pMetab->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_4");
pMetab = pModel->getMetabolites()[5];
CPPUNIT_ASSERT(pMetab != NULL);
CPPUNIT_ASSERT(pMetab->getObjectName() == "F");
CPPUNIT_ASSERT(pMetab->getStatus() == CModelEntity::Status::ODE);
// check ode
pTree = pMetab->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_6");
// check model values
CPPUNIT_ASSERT(pModel->getModelValues().size() == 3);
const CModelValue* pModelValue = pModel->getModelValues()[0];
CPPUNIT_ASSERT(pModelValue != NULL);
CPPUNIT_ASSERT(pModelValue->getObjectName() == "K1");
CPPUNIT_ASSERT(pModelValue->getStatus() == CModelEntity::Status::ASSIGNMENT);
// check assignment
pTree = pModelValue->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_1");
pModelValue = pModel->getModelValues()[1];
CPPUNIT_ASSERT(pModelValue != NULL);
CPPUNIT_ASSERT(pModelValue->getObjectName() == "K2");
CPPUNIT_ASSERT(pModelValue->getStatus() == CModelEntity::Status::FIXED);
pModelValue = pModel->getModelValues()[2];
CPPUNIT_ASSERT(pModelValue != NULL);
CPPUNIT_ASSERT(pModelValue->getObjectName() == "K3");
// check assignment
pTree = pModelValue->getExpressionPtr();
CPPUNIT_ASSERT(pTree != NULL);
pRoot = pTree->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot) != NULL);
CPPUNIT_ASSERT(dynamic_cast<const CEvaluationNodeCall*>(pRoot)->getData() == "function_3");
CPPUNIT_ASSERT(pModel->getReactions().size() == 6);
// check reactions
const CReaction* pReaction = pModel->getReactions()[0];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 1);
const CFunction* pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction1");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
pReaction = pModel->getReactions()[1];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 2);
pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction2");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
pReaction = pModel->getReactions()[2];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 1);
pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction3");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
pReaction = pModel->getReactions()[3];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 0);
pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction4");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
pReaction = pModel->getReactions()[4];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 2);
pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction5");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
pReaction = pModel->getReactions()[5];
CPPUNIT_ASSERT(pReaction != NULL);
CPPUNIT_ASSERT(pReaction->getChemEq().getSubstrates().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getProducts().size() == 1);
CPPUNIT_ASSERT(pReaction->getChemEq().getModifiers().size() == 0);
CPPUNIT_ASSERT(pReaction->isReversible() == true);
// check the kinetic law
CPPUNIT_ASSERT(pReaction->getParameters().size() == 3);
pFunction = pReaction->getFunction();
CPPUNIT_ASSERT(pFunction != NULL);
CPPUNIT_ASSERT(pFunction->getType() == CEvaluationTree::UserDefined);
CPPUNIT_ASSERT(pFunction->getObjectName() == "Function for reaction6");
pRoot = pFunction->getRoot();
CPPUNIT_ASSERT(pRoot != NULL);
}
const char* test000078::MODEL_STRING1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<sbml xmlns=\"http://www.sbml.org/sbml/level2/version4\" level=\"2\" version=\"4\">\n"
" <model id=\"Model_1\" name=\"New Model\">\n"
" <notes>\n"
" <body xmlns=\"http://www.w3.org/1999/xhtml\">\n"
" <p>Model with function call in kinetics and rules.</p>\n"
" <p>This is to check import of unordered function definitions as allowed in L2V4</p>\n"
" </body>\n"
" </notes>\n"
" <listOfFunctionDefinitions>\n"
" <functionDefinition id=\"function_6\" name=\"function_6\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> k1 </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> k2 </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> k3 </ci>\n"
" </bvar>\n"
" <apply>\n"
" <ci> function_5 </ci>\n"
" <ci> k1 </ci>\n"
" <ci> k2 </ci>\n"
" <ci> k3 </ci>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" <functionDefinition id=\"function_4\" name=\"function_4\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> x </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> y </ci>\n"
" </bvar>\n"
" <apply>\n"
" <divide/>\n"
" <apply>\n"
" <ci> function_2 </ci>\n"
" <ci> x </ci>\n"
" <ci> y </ci>\n"
" </apply>\n"
" <cn> 2.0 </cn>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" <functionDefinition id=\"function_5\" name=\"function_5\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> a </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> b </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> c </ci>\n"
" </bvar>\n"
" <apply>\n"
" <plus/>\n"
" <apply>\n"
" <ci> function_3 </ci>\n"
" <ci> c </ci>\n"
" <ci> a </ci>\n"
" </apply>\n"
" <apply>\n"
" <minus/>\n"
" <apply>\n"
" <ci> function_1 </ci>\n"
" <ci> b </ci>\n"
" </apply>\n"
" <cn> 5.23 </cn>\n"
" </apply>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" <functionDefinition id=\"function_2\" name=\"function_2\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> A </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> B </ci>\n"
" </bvar>\n"
" <apply>\n"
" <plus/>\n"
" <ci> B </ci>\n"
" <ci> A </ci>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" <functionDefinition id=\"function_3\" name=\"function_3\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> k </ci>\n"
" </bvar>\n"
" <bvar>\n"
" <ci> C </ci>\n"
" </bvar>\n"
" <apply>\n"
" <minus/>\n"
" <ci> C </ci>\n"
" <apply>\n"
" <times/>\n"
" <ci> k </ci>\n"
" <cn> 1.3 </cn>\n"
" </apply>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" <functionDefinition id=\"function_1\" name=\"function_1\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <lambda>\n"
" <bvar>\n"
" <ci> k </ci>\n"
" </bvar>\n"
" <apply>\n"
" <times/>\n"
" <cn> 3.0 </cn>\n"
" <ci> k </ci>\n"
" </apply>\n"
" </lambda>\n"
" </math>\n"
" </functionDefinition>\n"
" </listOfFunctionDefinitions>\n"
" <listOfCompartments>\n"
" <compartment id=\"compartment_1\" name=\"compartment\" size=\"1\"/>\n"
" </listOfCompartments>\n"
" <listOfSpecies>\n"
" <species id=\"species_1\" name=\"A\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n"
" <species id=\"species_2\" name=\"B\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n"
" <species id=\"species_3\" name=\"C\" compartment=\"compartment_1\" initialConcentration=\"1\" constant=\"false\"/>\n"
" <species id=\"species_4\" name=\"D\" compartment=\"compartment_1\" initialConcentration=\"1\" constant=\"false\"/>\n"
" <species id=\"species_5\" name=\"E\" compartment=\"compartment_1\" initialConcentration=\"1\" constant=\"false\"/>\n"
" <species id=\"species_6\" name=\"F\" compartment=\"compartment_1\" initialConcentration=\"1\" constant=\"false\"/>\n"
" </listOfSpecies>\n"
" <listOfParameters>\n"
" <parameter id=\"parameter_1\" name=\"K1\" value=\"1.1\" constant=\"false\"/>\n"
" <parameter id=\"parameter_2\" name=\"K2\" value=\"1.2\"/>\n"
" <parameter id=\"parameter_3\" name=\"K3\" value=\"1.3\" constant=\"false\"/>\n"
" </listOfParameters>\n"
" <listOfRules>\n"
" <assignmentRule variable=\"parameter_1\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_1 </ci>\n"
" <cn> 4.5 </cn>\n"
" </apply>\n"
" </math>\n"
" </assignmentRule>\n"
" <assignmentRule variable=\"parameter_3\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_3 </ci>\n"
" <cn> 2.0 </cn>\n"
" <ci> parameter_1 </ci>\n"
" </apply>\n"
" </math>\n"
" </assignmentRule>\n"
" <assignmentRule variable=\"species_3\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_5 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <cn> 2.4 </cn>\n"
" <cn> 3.5 </cn>\n"
" </apply>\n"
" </math>\n"
" </assignmentRule>\n"
" <rateRule variable=\"species_4\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_2 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <cn> 3.4 </cn>\n"
" </apply>\n"
" </math>\n"
" </rateRule>\n"
" <rateRule variable=\"species_5\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_4 </ci>\n"
" <cn> 1.4 </cn>\n"
" <ci> parameter_2 </ci>\n"
" </apply>\n"
" </math>\n"
" </rateRule>\n"
" <rateRule variable=\"species_6\">\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <ci> function_6 </ci>\n"
" <ci> parameter_3 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <cn> 3.4 </cn>\n"
" </apply>\n"
" </math>\n"
" </rateRule>\n"
" </listOfRules>\n"
" <listOfReactions>\n"
" <reaction id=\"reaction1\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_1 </ci>\n"
" <ci> parameter_1 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" <reaction id=\"reaction2\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_2 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <ci> parameter_2 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" <reaction id=\"reaction3\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_3 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <ci> species_2 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" <reaction id=\"reaction4\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_4 </ci>\n"
" <ci> species_1 </ci>\n"
" <ci> species_2 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" <reaction id=\"reaction5\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_5 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <ci> parameter_3 </ci>\n"
" <ci> species_2 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" <reaction id=\"reaction6\" reversible=\"true\">\n"
" <listOfReactants>\n"
" <speciesReference species=\"species_1\"/>\n"
" </listOfReactants>\n"
" <listOfProducts>\n"
" <speciesReference species=\"species_2\"/>\n"
" </listOfProducts>\n"
" <kineticLaw>\n"
" <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
" <apply>\n"
" <times/>\n"
" <ci> compartment_1 </ci>\n"
" <apply>\n"
" <ci> function_6 </ci>\n"
" <ci> parameter_1 </ci>\n"
" <ci> parameter_2 </ci>\n"
" <ci> parameter_3 </ci>\n"
" </apply>\n"
" </apply>\n"
" </math>\n"
" </kineticLaw>\n"
" </reaction>\n"
" </listOfReactions>\n"
" </model>\n"
"</sbml>\n"
;
| 412 | 0.736572 | 1 | 0.736572 | game-dev | MEDIA | 0.433516 | game-dev | 0.810644 | 1 | 0.810644 |
proletariatgames/unreal.hx | 1,196 | Haxe/Externs/UE4.19/unreal/FPredictProjectilePathResult.hx | /**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal;
/**
Container for the result of a projectile path trace (using PredictProjectilePath).
**/
@:glueCppIncludes("Classes/Kismet/GameplayStaticsTypes.h")
@:noCopy @:noEquals @:uextern @:ustruct extern class FPredictProjectilePathResult {
/**
Hit along the trace, if tracing with collision was enabled.
**/
@:uproperty public var HitResult : unreal.FHitResult;
/**
Info on the last point we tried to trace to, which may have been beyond the final hit.
**/
@:uproperty public var LastTraceDestination : unreal.FPredictProjectilePathPointData;
/**
Info for each point on the path.
**/
@:uproperty public var PathData : unreal.TArray<unreal.FPredictProjectilePathPointData>;
}
| 412 | 0.891333 | 1 | 0.891333 | game-dev | MEDIA | 0.899703 | game-dev | 0.627589 | 1 | 0.627589 |
oot-pc-port/oot-pc-port | 4,005 | asm/non_matchings/code/z_kaleido_manager/func_800BBDB4.s | glabel func_800BBDB4
/* B32F54 800BBDB4 27BDFFE0 */ addiu $sp, $sp, -0x20
/* B32F58 800BBDB8 AFA40020 */ sw $a0, 0x20($sp)
/* B32F5C 800BBDBC AFB00018 */ sw $s0, 0x18($sp)
/* B32F60 800BBDC0 3C048013 */ lui $a0, %hi(D_8012D1D8) # $a0, 0x8013
/* B32F64 800BBDC4 3C028013 */ lui $v0, %hi(D_8012D1A0) # $v0, 0x8013
/* B32F68 800BBDC8 AFBF001C */ sw $ra, 0x1c($sp)
/* B32F6C 800BBDCC 00008025 */ move $s0, $zero
/* B32F70 800BBDD0 2442D1A0 */ addiu $v0, %lo(D_8012D1A0) # addiu $v0, $v0, -0x2e60
/* B32F74 800BBDD4 2484D1D8 */ addiu $a0, %lo(D_8012D1D8) # addiu $a0, $a0, -0x2e28
/* B32F78 800BBDD8 8C4E0010 */ lw $t6, 0x10($v0)
.L800BBDDC:
/* B32F7C 800BBDDC 8C4F000C */ lw $t7, 0xc($v0)
/* B32F80 800BBDE0 2442001C */ addiu $v0, $v0, 0x1c
/* B32F84 800BBDE4 01CF1823 */ subu $v1, $t6, $t7
/* B32F88 800BBDE8 0203082A */ slt $at, $s0, $v1
/* B32F8C 800BBDEC 10200002 */ beqz $at, .L800BBDF8
/* B32F90 800BBDF0 00000000 */ nop
/* B32F94 800BBDF4 00608025 */ move $s0, $v1
.L800BBDF8:
/* B32F98 800BBDF8 5444FFF8 */ bnel $v0, $a0, .L800BBDDC
/* B32F9C 800BBDFC 8C4E0010 */ lw $t6, 0x10($v0)
/* B32FA0 800BBE00 3C048014 */ lui $a0, %hi(D_80143E98) # $a0, 0x8014
/* B32FA4 800BBE04 0C00084C */ jal osSyncPrintf
/* B32FA8 800BBE08 24843E98 */ addiu $a0, %lo(D_80143E98) # addiu $a0, $a0, 0x3e98
/* B32FAC 800BBE0C 3C048014 */ lui $a0, %hi(D_80143EA0) # $a0, 0x8014
/* B32FB0 800BBE10 24843EA0 */ addiu $a0, %lo(D_80143EA0) # addiu $a0, $a0, 0x3ea0
/* B32FB4 800BBE14 0C00084C */ jal osSyncPrintf
/* B32FB8 800BBE18 02002825 */ move $a1, $s0
/* B32FBC 800BBE1C 3C048014 */ lui $a0, %hi(D_80143ED4) # $a0, 0x8014
/* B32FC0 800BBE20 0C00084C */ jal osSyncPrintf
/* B32FC4 800BBE24 24843ED4 */ addiu $a0, %lo(D_80143ED4) # addiu $a0, $a0, 0x3ed4
/* B32FC8 800BBE28 3C068014 */ lui $a2, %hi(D_80143ED8) # $a2, 0x8014
/* B32FCC 800BBE2C 24C63ED8 */ addiu $a2, %lo(D_80143ED8) # addiu $a2, $a2, 0x3ed8
/* B32FD0 800BBE30 8FA40020 */ lw $a0, 0x20($sp)
/* B32FD4 800BBE34 02002825 */ move $a1, $s0
/* B32FD8 800BBE38 0C031521 */ jal Game_Alloc
/* B32FDC 800BBE3C 24070096 */ li $a3, 150
/* B32FE0 800BBE40 3C038013 */ lui $v1, %hi(D_8012D1D8) # $v1, 0x8013
/* B32FE4 800BBE44 2463D1D8 */ addiu $v1, %lo(D_8012D1D8) # addiu $v1, $v1, -0x2e28
/* B32FE8 800BBE48 3C048014 */ lui $a0, %hi(D_80143EF0) # $a0, 0x8014
/* B32FEC 800BBE4C 3C068014 */ lui $a2, %hi(D_80143F04) # $a2, 0x8014
/* B32FF0 800BBE50 AC620000 */ sw $v0, ($v1)
/* B32FF4 800BBE54 24C63F04 */ addiu $a2, %lo(D_80143F04) # addiu $a2, $a2, 0x3f04
/* B32FF8 800BBE58 24843EF0 */ addiu $a0, %lo(D_80143EF0) # addiu $a0, $a0, 0x3ef0
/* B32FFC 800BBE5C 00402825 */ move $a1, $v0
/* B33000 800BBE60 0C000B58 */ jal LogUtils_CheckNullPointer
/* B33004 800BBE64 24070097 */ li $a3, 151
/* B33008 800BBE68 3C048014 */ lui $a0, %hi(D_80143F1C) # $a0, 0x8014
/* B3300C 800BBE6C 0C00084C */ jal osSyncPrintf
/* B33010 800BBE70 24843F1C */ addiu $a0, %lo(D_80143F1C) # addiu $a0, $a0, 0x3f1c
/* B33014 800BBE74 3C058013 */ lui $a1, %hi(D_8012D1D8) # $a1, 0x8013
/* B33018 800BBE78 8CA5D1D8 */ lw $a1, %lo(D_8012D1D8)($a1)
/* B3301C 800BBE7C 3C048014 */ lui $a0, %hi(D_80143F24) # $a0, 0x8014
/* B33020 800BBE80 24843F24 */ addiu $a0, %lo(D_80143F24) # addiu $a0, $a0, 0x3f24
/* B33024 800BBE84 0C00084C */ jal osSyncPrintf
/* B33028 800BBE88 00B03021 */ addu $a2, $a1, $s0
/* B3302C 800BBE8C 3C048014 */ lui $a0, %hi(D_80143F40) # $a0, 0x8014
/* B33030 800BBE90 0C00084C */ jal osSyncPrintf
/* B33034 800BBE94 24843F40 */ addiu $a0, %lo(D_80143F40) # addiu $a0, $a0, 0x3f40
/* B33038 800BBE98 8FBF001C */ lw $ra, 0x1c($sp)
/* B3303C 800BBE9C 3C018013 */ lui $at, %hi(D_8012D1DC) # $at, 0x8013
/* B33040 800BBEA0 8FB00018 */ lw $s0, 0x18($sp)
/* B33044 800BBEA4 AC20D1DC */ sw $zero, %lo(D_8012D1DC)($at)
/* B33048 800BBEA8 03E00008 */ jr $ra
/* B3304C 800BBEAC 27BD0020 */ addiu $sp, $sp, 0x20
| 412 | 0.75469 | 1 | 0.75469 | game-dev | MEDIA | 0.427089 | game-dev | 0.624275 | 1 | 0.624275 |
EmptyBottleInc/DFU-Tanguy-Multiplayer | 4,673 | Assets/Scripts/Game/MagicAndEffects/EntityEffectBundle.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2022 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using DaggerfallConnect.Save;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Game.Items;
namespace DaggerfallWorkshop.Game.MagicAndEffects
{
/// <summary>
/// Stores effect settings for transport to an entity.
/// </summary>
public class EntityEffectBundle
{
#region Fields
EffectBundleSettings settings;
DaggerfallEntityBehaviour casterEntityBehaviour = null;
DaggerfallUnityItem fromEquippedItem = null;
DaggerfallUnityItem castByItem = null;
int reflectedCount = 0;
#endregion
#region Properties
/// <summary>
/// Gets or sets caster entity (sender) of effect bundle where one is present.
/// Example of caster entity is an enemy mage or monster.
/// </summary>
public DaggerfallEntityBehaviour CasterEntityBehaviour
{
get { return casterEntityBehaviour; }
set { casterEntityBehaviour = value; }
}
/// <summary>
/// Gets or sets effect bundle settings.
/// </summary>
public EffectBundleSettings Settings
{
get { return settings; }
set { settings = value; }
}
/// <summary>
/// True if bundle is from an equipped source item.
/// These bundles will last until player unequips or item breaks (which also unequips item).
/// </summary>
public bool IsFromEquippedItem
{
get { return (fromEquippedItem != null); }
}
/// <summary>
/// Gets or sets the equipped item providing this bundle.
/// </summary>
public DaggerfallUnityItem FromEquippedItem
{
get { return fromEquippedItem; }
set { fromEquippedItem = value; }
}
public DaggerfallUnityItem CastByItem
{
get { return castByItem; }
set { castByItem = value; }
}
/// <summary>
/// Gets the number of times this bundle has been reflected.
/// </summary>
public int ReflectedCount
{
get { return reflectedCount; }
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
public EntityEffectBundle()
{
}
/// <summary>
/// Settings + caster constructor.
/// </summary>
/// <param name="settings">Settings of this effect bundle.</param>
/// <param name="casterEntityBehaviour">Caster of this effect bundle (optional).</param>
public EntityEffectBundle(EffectBundleSettings settings, DaggerfallEntityBehaviour casterEntityBehaviour = null)
{
this.settings = settings;
this.casterEntityBehaviour = casterEntityBehaviour;
}
#endregion
#region Public Methods
/// <summary>
/// Checks if effect bundle contains an effect matching a classic effect record.
/// </summary>
/// <param name="effectRecord">Effect record to compare with native bundle effects.</param>
/// <returns>True if bundle contains effect matching classic effect record.</returns>
public bool HasMatchForClassicEffect(SpellRecord.EffectRecordData effectRecord)
{
int classicKey = BaseEntityEffect.MakeClassicKey((byte)effectRecord.type, (byte)effectRecord.subType);
foreach(EffectEntry entry in settings.Effects)
{
IEntityEffect effectTemplate = GameManager.Instance.EntityEffectBroker.GetEffectTemplate(entry.Key);
if (effectTemplate.Properties.ClassicKey == classicKey)
return true;
}
return false;
}
/// <summary>
/// Increments reflection count.
/// </summary>
public void IncrementReflectionCount()
{
reflectedCount++;
}
public void AddRuntimeFlags(BundleRuntimeFlags flags)
{
settings.RuntimeFlags |= flags;
}
public void RemoveRuntimeFlags(BundleRuntimeFlags flags)
{
settings.RuntimeFlags &= ~flags;
}
#endregion
}
}
| 412 | 0.873373 | 1 | 0.873373 | game-dev | MEDIA | 0.935664 | game-dev | 0.878594 | 1 | 0.878594 |
It-Life/Deer_GameFramework_Wolong | 3,560 | Assets/Standard Assets/ThirdParty/SuperScrollView/Scripts/GridView/LoopGridItemPool.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace SuperScrollView
{
public class GridItemPool
{
GameObject mPrefabObj;
string mPrefabName;
int mInitCreateCount = 1;
List<LoopGridViewItem> mTmpPooledItemList = new List<LoopGridViewItem>();
List<LoopGridViewItem> mPooledItemList = new List<LoopGridViewItem>();
static int mCurItemIdCount = 0;
RectTransform mItemParent = null;
public GridItemPool()
{
}
public void Init(GameObject prefabObj, int createCount, RectTransform parent)
{
mPrefabObj = prefabObj;
mPrefabName = mPrefabObj.name;
mInitCreateCount = createCount;
mItemParent = parent;
mPrefabObj.SetActive(false);
for (int i = 0; i < mInitCreateCount; ++i)
{
LoopGridViewItem tViewItem = CreateItem();
RecycleItemReal(tViewItem);
}
}
public LoopGridViewItem GetItem()
{
mCurItemIdCount++;
LoopGridViewItem tItem = null;
if (mTmpPooledItemList.Count > 0)
{
int count = mTmpPooledItemList.Count;
tItem = mTmpPooledItemList[count - 1];
mTmpPooledItemList.RemoveAt(count - 1);
tItem.gameObject.SetActive(true);
}
else
{
int count = mPooledItemList.Count;
if (count == 0)
{
tItem = CreateItem();
}
else
{
tItem = mPooledItemList[count - 1];
mPooledItemList.RemoveAt(count - 1);
tItem.gameObject.SetActive(true);
}
}
tItem.ItemId = mCurItemIdCount;
return tItem;
}
public void DestroyAllItem()
{
ClearTmpRecycledItem();
int count = mPooledItemList.Count;
for (int i = 0; i < count; ++i)
{
GameObject.DestroyImmediate(mPooledItemList[i].gameObject);
}
mPooledItemList.Clear();
}
public LoopGridViewItem CreateItem()
{
GameObject go = GameObject.Instantiate<GameObject>(mPrefabObj, Vector3.zero, Quaternion.identity, mItemParent);
go.SetActive(true);
RectTransform rf = go.GetComponent<RectTransform>();
rf.localScale = Vector3.one;
rf.anchoredPosition3D = Vector3.zero;
rf.localEulerAngles = Vector3.zero;
LoopGridViewItem tViewItem = go.GetComponent<LoopGridViewItem>();
tViewItem.ItemPrefabName = mPrefabName;
return tViewItem;
}
void RecycleItemReal(LoopGridViewItem item)
{
item.gameObject.SetActive(false);
mPooledItemList.Add(item);
}
public void RecycleItem(LoopGridViewItem item)
{
item.PrevItem = null;
item.NextItem = null;
mTmpPooledItemList.Add(item);
}
public void ClearTmpRecycledItem()
{
int count = mTmpPooledItemList.Count;
if (count == 0)
{
return;
}
for (int i = 0; i < count; ++i)
{
RecycleItemReal(mTmpPooledItemList[i]);
}
mTmpPooledItemList.Clear();
}
}
}
| 412 | 0.763099 | 1 | 0.763099 | game-dev | MEDIA | 0.6505 | game-dev | 0.954581 | 1 | 0.954581 |
Rolisteam/rolisteam | 9,678 | src/libraries/core/src/model/dicealiasmodel.cpp | /***************************************************************************
* Copyright (C) 2009 by Renaud Guezennec *
* https://rolisteam.org/contact *
* *
* Rolisteam is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "model/dicealiasmodel.h"
#include <QColor>
#include <QJsonArray>
#include <QJsonObject>
#include <QObject>
#include "diceparser/dicealias.h"
DiceAliasModel::DiceAliasModel(QObject* parent) : QAbstractListModel(parent)
{
m_header << tr("Pattern") << tr("Value") << tr("Regular Expression") << tr("Disable") << tr("Comments");
}
DiceAliasModel::~DiceAliasModel()
{
/* if(m_diceAliasList!=nullptr)
{
qDeleteAll(*m_diceAliasList);
delete m_diceAliasList;
m_diceAliasList = nullptr;
}*/
}
QVariant DiceAliasModel::data(const QModelIndex& index, int role) const
{
if(!index.isValid())
return {};
auto const& diceAlias= m_diceAliasList.at(index.row());
if(!diceAlias)
return {};
if((Qt::DisplayRole == role) || (Qt::EditRole == role))
{
if(index.column() == PATTERN)
{
return diceAlias->pattern();
}
else if(index.column() == COMMAND)
{
return diceAlias->command();
}
else if(index.column() == METHOD)
{
return !diceAlias->isReplace();
}
else if(index.column() == DISABLE)
{
return !diceAlias->isEnable();
}
else if(index.column() == COMMENT)
{
return diceAlias->comment();
}
}
else if(Qt::BackgroundRole == role)
{
if(!diceAlias->isEnable())
{
return QColor(Qt::red).lighter();
}
}
else if(Qt::TextAlignmentRole == role)
{
if(index.column() == METHOD)
{
return Qt::AlignCenter;
}
}
return QVariant();
}
int DiceAliasModel::rowCount(const QModelIndex& parent) const
{
if(!parent.isValid())
return static_cast<int>(m_diceAliasList.size());
return 0;
}
int DiceAliasModel::columnCount(const QModelIndex&) const
{
return m_header.size();
}
QVariant DiceAliasModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(Qt::DisplayRole == role)
{
if(orientation == Qt::Horizontal)
{
return m_header.at(section);
}
}
return QVariant();
}
/*void DiceAliasModel::setAliases(QList<DiceAlias*>* lst)
{
m_diceAliasList= lst;
}
void DiceAliasModel::appendAlias()
{
addAlias(new DiceAlias(tr("New Alias%1").arg(m_diceAliasList->size()), ""));
}*/
/*void DiceAliasModel::preferencesHasChanged(const QString& pref)
{
if(pref == "isPlayer")
{
m_isGM=
}
}*/
QString DiceAliasModel::convert(const QString& str)
{
auto res= str;
for(auto const& alias : m_diceAliasList)
{
alias->resolved(res);
}
return res;
}
void DiceAliasModel::appendAlias(DiceAlias&& alias)
{
beginInsertRows(QModelIndex(), m_diceAliasList.size(), m_diceAliasList.size());
m_diceAliasList.push_back(std::make_unique<DiceAlias>(alias));
endInsertRows();
auto const& it= m_diceAliasList.end() - 1;
emit aliasAdded((*it).get(), std::distance(m_diceAliasList.begin(), it));
}
Qt::ItemFlags DiceAliasModel::flags(const QModelIndex& index) const
{
if(!index.isValid())
return Qt::NoItemFlags;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled;
}
bool DiceAliasModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
bool result= false;
if(!index.isValid())
return result;
auto const& diceAlias= m_diceAliasList[index.row()];
if(role == Qt::EditRole)
{
switch(index.column())
{
case PATTERN:
diceAlias->setPattern(value.toString());
result= true;
break;
case COMMAND:
diceAlias->setCommand(value.toString());
result= true;
break;
case METHOD:
if(value.toBool())
{
diceAlias->setType(DiceAlias::REGEXP);
}
else
{
diceAlias->setType(DiceAlias::REPLACE);
}
result= true;
break;
case DISABLE:
diceAlias->setEnable(!value.toBool());
result= true;
break;
case COMMENT:
diceAlias->setComment(value.toString());
result= true;
break;
}
}
if(result)
{
emit dataChanged(index, index, QVector<int>() << role);
emit aliasChanged(diceAlias.get(), index.row());
}
return result;
}
const std::vector<std::unique_ptr<DiceAlias>>& DiceAliasModel::aliases() const
{
return m_diceAliasList;
}
void DiceAliasModel::deleteAlias(const QModelIndex& index)
{
if(!index.isValid())
return;
beginRemoveRows(QModelIndex(), index.row(), index.row());
auto const& it= m_diceAliasList.begin() + index.row();
m_diceAliasList.erase(it);
endRemoveRows();
emit aliasRemoved(index.row());
/*NetworkMessageWriter msg(NetMsg::SharePreferencesCategory, NetMsg::removeDiceAlias);
msg.int64(index.row());
msg.sendToServer();*/
}
void DiceAliasModel::upAlias(const QModelIndex& index)
{
if(!index.isValid())
return;
if(index.row() == 0)
return;
if(beginMoveRows(QModelIndex(), index.row(), index.row(), QModelIndex(), index.row() - 1))
{
std::iter_swap(m_diceAliasList.begin() + index.row(), m_diceAliasList.begin() + index.row() - 1);
// m_diceAliasList->swapItemsAt(index.row(), index.row() - 1);
endMoveRows();
emit aliasMoved(index.row(), index.row() - 1);
}
}
void DiceAliasModel::downAlias(const QModelIndex& index)
{
if(!index.isValid())
return;
if(index.row() == static_cast<int>(m_diceAliasList.size()) - 1)
return;
if(beginMoveRows(QModelIndex(), index.row(), index.row(), QModelIndex(), index.row() + 2))
{
std::iter_swap(m_diceAliasList.begin() + index.row(), m_diceAliasList.begin() + index.row() + 1);
endMoveRows();
emit aliasMoved(index.row(), index.row() + 1);
}
}
void DiceAliasModel::topAlias(const QModelIndex& index)
{
if(!index.isValid())
return;
if(index.row() == 0)
return;
if(beginMoveRows(QModelIndex(), index.row(), index.row(), QModelIndex(), 0))
{
std::iter_swap(m_diceAliasList.begin(), m_diceAliasList.begin() + index.row());
endMoveRows();
emit aliasMoved(index.row(), 0);
}
}
void DiceAliasModel::bottomAlias(const QModelIndex& index)
{
if(!index.isValid())
return;
auto size= static_cast<int>(m_diceAliasList.size());
if(index.row() == size - 1)
return;
if(beginMoveRows(QModelIndex(), index.row(), index.row(), QModelIndex(), size))
{
std::iter_swap(m_diceAliasList.end() - 1, m_diceAliasList.begin() + index.row());
endMoveRows();
emit aliasMoved(index.row(), size);
}
}
/*void DiceAliasModel::setGM(bool b)
{
m_isGM= b;
}*/
void DiceAliasModel::clear()
{
beginResetModel();
m_diceAliasList.clear();
endResetModel();
}
/*void DiceAliasModel::load(const QJsonObject& obj)
{
QJsonArray aliases= obj["aliases"].toArray();
for(auto aliasRef : aliases)
{
auto alias= aliasRef.toObject();
auto da= new DiceAlias(alias["command"].toString(), alias["value"].toString(), alias["replace"].toBool(),
alias["enable"].toBool());
da->setComment(alias["comment"].toString());
addAlias(da);
}
}
void DiceAliasModel::save(QJsonObject& obj)
{
QJsonArray dices;
for(auto& dice : *m_diceAliasList)
{
QJsonObject diceObj;
diceObj["command"]= dice->getCommand();
diceObj["value"]= dice->getValue();
diceObj["replace"]= dice->isReplace();
diceObj["enable"]= dice->isEnable();
diceObj["comment"]= dice->getComment();
dices.append(diceObj);
}
obj["aliases"]= dices;
}
void DiceAliasModel::moveAlias(int from, int to)
{
if(!m_isGM)
return;
NetworkMessageWriter msg(NetMsg::SharePreferencesCategory, NetMsg::moveDiceAlias);
msg.int64(from);
msg.int64(to);
msg.sendToServer();
}*/
| 412 | 0.899416 | 1 | 0.899416 | game-dev | MEDIA | 0.179204 | game-dev | 0.962151 | 1 | 0.962151 |
google/orbit | 8,647 | third_party/libutils/include/utils/LruCache.h | /*
* Copyright (C) 2012 The Android Open Source Project
*
* 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 ANDROID_UTILS_LRU_CACHE_H
#define ANDROID_UTILS_LRU_CACHE_H
#include <memory>
#include <unordered_set>
#include "utils/TypeHelpers.h" // hash_t
namespace android {
/**
* GenerationCache callback used when an item is removed
*/
template<typename EntryKey, typename EntryValue>
class OnEntryRemoved {
public:
virtual ~OnEntryRemoved() { };
virtual void operator()(EntryKey& key, EntryValue& value) = 0;
}; // class OnEntryRemoved
template <typename TKey, typename TValue>
class LruCache {
public:
explicit LruCache(uint32_t maxCapacity);
virtual ~LruCache();
enum Capacity {
kUnlimitedCapacity,
};
void setOnEntryRemovedListener(OnEntryRemoved<TKey, TValue>* listener);
size_t size() const;
const TValue& get(const TKey& key);
bool put(const TKey& key, const TValue& value);
bool remove(const TKey& key);
bool removeOldest();
void clear();
const TValue& peekOldestValue();
private:
LruCache(const LruCache& that); // disallow copy constructor
// Super class so that we can have entries having only a key reference, for searches.
class KeyedEntry {
public:
virtual const TKey& getKey() const = 0;
// Make sure the right destructor is executed so that keys and values are deleted.
virtual ~KeyedEntry() {}
};
class Entry final : public KeyedEntry {
public:
TKey key;
TValue value;
Entry* parent;
Entry* child;
Entry(TKey _key, TValue _value) : key(_key), value(_value), parent(nullptr), child(nullptr) {
}
const TKey& getKey() const final { return key; }
};
class EntryForSearch : public KeyedEntry {
public:
const TKey& key;
EntryForSearch(const TKey& key_) : key(key_) {
}
const TKey& getKey() const final { return key; }
};
struct HashForEntry : public std::unary_function<KeyedEntry*, hash_t> {
size_t operator() (const KeyedEntry* entry) const {
return hash_type(entry->getKey());
};
};
struct EqualityForHashedEntries : public std::unary_function<KeyedEntry*, hash_t> {
bool operator() (const KeyedEntry* lhs, const KeyedEntry* rhs) const {
return lhs->getKey() == rhs->getKey();
};
};
// All entries in the set will be Entry*. Using the weaker KeyedEntry as to allow entries
// that have only a key reference, for searching.
typedef std::unordered_set<KeyedEntry*, HashForEntry, EqualityForHashedEntries> LruCacheSet;
void attachToCache(Entry& entry);
void detachFromCache(Entry& entry);
typename LruCacheSet::iterator findByKey(const TKey& key) {
EntryForSearch entryForSearch(key);
typename LruCacheSet::iterator result = mSet->find(&entryForSearch);
return result;
}
std::unique_ptr<LruCacheSet> mSet;
OnEntryRemoved<TKey, TValue>* mListener;
Entry* mOldest;
Entry* mYoungest;
uint32_t mMaxCapacity;
TValue mNullValue;
public:
// To be used like:
// while (it.next()) {
// it.value(); it.key();
// }
class Iterator {
public:
Iterator(const LruCache<TKey, TValue>& cache):
mCache(cache), mIterator(mCache.mSet->begin()), mBeginReturned(false) {
}
bool next() {
if (mIterator == mCache.mSet->end()) {
return false;
}
if (!mBeginReturned) {
// mIterator has been initialized to the beginning and
// hasn't been returned. Do not advance:
mBeginReturned = true;
} else {
std::advance(mIterator, 1);
}
bool ret = (mIterator != mCache.mSet->end());
return ret;
}
const TValue& value() const {
// All the elements in the set are of type Entry. See comment in the definition
// of LruCacheSet above.
return reinterpret_cast<Entry *>(*mIterator)->value;
}
const TKey& key() const {
return (*mIterator)->getKey();
}
private:
const LruCache<TKey, TValue>& mCache;
typename LruCacheSet::iterator mIterator;
bool mBeginReturned;
};
};
// Implementation is here, because it's fully templated
template <typename TKey, typename TValue>
LruCache<TKey, TValue>::LruCache(uint32_t maxCapacity)
: mSet(new LruCacheSet())
, mListener(nullptr)
, mOldest(nullptr)
, mYoungest(nullptr)
, mMaxCapacity(maxCapacity)
, mNullValue(0) {
mSet->max_load_factor(1.0);
};
template <typename TKey, typename TValue>
LruCache<TKey, TValue>::~LruCache() {
// Need to delete created entries.
clear();
};
template<typename K, typename V>
void LruCache<K, V>::setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener) {
mListener = listener;
}
template <typename TKey, typename TValue>
size_t LruCache<TKey, TValue>::size() const {
return mSet->size();
}
template <typename TKey, typename TValue>
const TValue& LruCache<TKey, TValue>::get(const TKey& key) {
typename LruCacheSet::const_iterator find_result = findByKey(key);
if (find_result == mSet->end()) {
return mNullValue;
}
// All the elements in the set are of type Entry. See comment in the definition
// of LruCacheSet above.
Entry *entry = reinterpret_cast<Entry*>(*find_result);
detachFromCache(*entry);
attachToCache(*entry);
return entry->value;
}
template <typename TKey, typename TValue>
bool LruCache<TKey, TValue>::put(const TKey& key, const TValue& value) {
if (mMaxCapacity != kUnlimitedCapacity && size() >= mMaxCapacity) {
removeOldest();
}
if (findByKey(key) != mSet->end()) {
return false;
}
Entry* newEntry = new Entry(key, value);
mSet->insert(newEntry);
attachToCache(*newEntry);
return true;
}
template <typename TKey, typename TValue>
bool LruCache<TKey, TValue>::remove(const TKey& key) {
typename LruCacheSet::const_iterator find_result = findByKey(key);
if (find_result == mSet->end()) {
return false;
}
// All the elements in the set are of type Entry. See comment in the definition
// of LruCacheSet above.
Entry* entry = reinterpret_cast<Entry*>(*find_result);
mSet->erase(entry);
if (mListener) {
(*mListener)(entry->key, entry->value);
}
detachFromCache(*entry);
delete entry;
return true;
}
template <typename TKey, typename TValue>
bool LruCache<TKey, TValue>::removeOldest() {
if (mOldest != nullptr) {
return remove(mOldest->key);
// TODO: should probably abort if false
}
return false;
}
template <typename TKey, typename TValue>
const TValue& LruCache<TKey, TValue>::peekOldestValue() {
if (mOldest) {
return mOldest->value;
}
return mNullValue;
}
template <typename TKey, typename TValue>
void LruCache<TKey, TValue>::clear() {
if (mListener) {
for (Entry* p = mOldest; p != nullptr; p = p->child) {
(*mListener)(p->key, p->value);
}
}
mYoungest = nullptr;
mOldest = nullptr;
for (auto entry : *mSet.get()) {
delete entry;
}
mSet->clear();
}
template <typename TKey, typename TValue>
void LruCache<TKey, TValue>::attachToCache(Entry& entry) {
if (mYoungest == nullptr) {
mYoungest = mOldest = &entry;
} else {
entry.parent = mYoungest;
mYoungest->child = &entry;
mYoungest = &entry;
}
}
template <typename TKey, typename TValue>
void LruCache<TKey, TValue>::detachFromCache(Entry& entry) {
if (entry.parent != nullptr) {
entry.parent->child = entry.child;
} else {
mOldest = entry.child;
}
if (entry.child != nullptr) {
entry.child->parent = entry.parent;
} else {
mYoungest = entry.parent;
}
entry.parent = nullptr;
entry.child = nullptr;
}
}
#endif // ANDROID_UTILS_LRU_CACHE_H
| 412 | 0.989133 | 1 | 0.989133 | game-dev | MEDIA | 0.32036 | game-dev | 0.977237 | 1 | 0.977237 |
MaxPixelStudios/MinecraftDecompiler | 4,019 | modules/remapper/src/main/java/cn/maxpixel/mcdecompiler/remapper/variable/Renamer.java | /*
* MinecraftDecompiler. A tool/library to deobfuscate and decompile jars.
* Copyright (C) 2019-2024 MaxPixelStudios(XiaoPangxie732)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package cn.maxpixel.mcdecompiler.remapper.variable;
import cn.maxpixel.rewh.logging.LogManager;
import cn.maxpixel.rewh.logging.Logger;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Type;
import java.util.Locale;
public class Renamer {
protected static final Logger LOGGER = LogManager.getLogger();
private record Holder(boolean skipZero, @NotNull String... names) {
private Holder(@NotNull String... names) {
this(true, names);
}
}
private static final Object2ObjectOpenHashMap<String, Holder> PREDEF = new Object2ObjectOpenHashMap<>();
static {
Holder h = new Holder("i", "j", "k", "l");
PREDEF.put("int", h);
PREDEF.put("long", h);
PREDEF.put("byte", new Holder(false, "b"));
PREDEF.put("char", new Holder(false, "c"));
PREDEF.put("short", new Holder(false, "short"));
PREDEF.put("double", new Holder(false, "d"));
PREDEF.put("boolean", new Holder("flag"));
PREDEF.put("float", new Holder("f"));
PREDEF.put("String", new Holder("s"));
PREDEF.put("Class", new Holder("oclass"));
PREDEF.put("Long", new Holder("olong"));
PREDEF.put("Byte", new Holder("obyte"));
PREDEF.put("Short", new Holder("oshort"));
PREDEF.put("Boolean", new Holder("obool"));
PREDEF.put("Float", new Holder("ofloat"));
PREDEF.put("Double", new Holder("odouble"));
PREDEF.put("Package", new Holder("opackage"));
PREDEF.put("Enum", new Holder("oenum"));
PREDEF.put("Void", new Holder("ovoid"));
}
protected final Object2IntOpenHashMap<String> vars = new Object2IntOpenHashMap<>();
{
vars.defaultReturnValue(0);
}
public void prepare() {
}
public String addExistingName(String name, int index) {
if (vars.addTo(name, 1) > 0) {
LOGGER.warn("Duplicated variable name: {}", name);
vars.addTo(name, -1);
}
return name;
}
public String getVarName(Type type, int index) {
boolean isArray = false;
if (type.getSort() == Type.ARRAY) {
type = type.getElementType();
isArray = true;
}
String varBaseName = type.getClassName();
if (type.getSort() == Type.OBJECT) varBaseName = varBaseName.substring(varBaseName.lastIndexOf('.') + 1);
Holder holder = isArray ? null : PREDEF.get(varBaseName);
if (holder != null) {
for (int i = 0; ; i++) {
for (String s : holder.names) {
if (i >= vars.getInt(s)) {
int j = vars.addTo(s, 1);
return s + (j == 0 && holder.skipZero ? "" : j);
}
}
}
} else {
varBaseName = varBaseName.replace('$', '_').toLowerCase(Locale.ENGLISH);
if (isArray) varBaseName = "a" + varBaseName;
int count = vars.addTo(varBaseName, 1);
return varBaseName + (count > 0 ? count : "");
}
}
}
| 412 | 0.909744 | 1 | 0.909744 | game-dev | MEDIA | 0.418517 | game-dev | 0.971209 | 1 | 0.971209 |
pvpgn/diablo-hellfire | 7,829 | src/PORTAL.CPP | /*-----------------------------------------------------------------------**
** Diablo
**
** Triggers file
**
** (C)1995 Condor, Inc. All rights reserved.
**
**-----------------------------------------------------------------------**
** $
**-----------------------------------------------------------------------**
**
** File Routines
**-----------------------------------------------------------------------*/
#include "diablo.h"
#pragma hdrstop
#include "portal.h"
#include "gendung.h"
#include "items.h"
#include "player.h"
#include "misdat.h"
#include "missiles.h"
#include "effects.h"
#include "msg.h"
#include "lighting.h"
/*-----------------------------------------------------------------------*
** Global Variables
**-----------------------------------------------------------------------*/
PortalStruct portal[MAXPORTAL];
int WarpDropX[MAXPORTAL] = { 57, 59, 61, 63 };
int WarpDropY[MAXPORTAL] = { 40, 40, 40, 40 };
int portalindex; // current portal in use for myplr
/*-----------------------------------------------------------------------**
** externs
**-----------------------------------------------------------------------*/
void SetMissDir(int mi, int dir);
void DeleteMissile(int mi, int i);
BOOL delta_portal_inited(int i);
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void InitPortals()
{
for (int i = 0; i < MAXPORTAL; i++) {
// Check to see if needs initing or parsed from level delta
if (delta_portal_inited(i))
portal[i].open = FALSE;
}
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void SyncPortal(int i, BOOL open, int x, int y, int level, int ltype)
{
app_assert((DWORD)i < MAXPORTAL);
portal[i].open = open;
portal[i].x = x;
portal[i].y = y;
portal[i].level = level;
portal[i].ltype = ltype;
portal[i].setlvl = FALSE;
}
/*-----------------------------------------------------------------------*
**-----------------------------------------------------------------------*/
void AddWarpMissile(int i, int x, int y)
{
// Don't play sound when loading level
missiledata[MIT_TOWN].mlSFX = -1;
// Fix because portal cant be drawn on top of each other
dMissile[x][y] = 0;
// Put in map and activate
int mi = AddMissile(0, 0, x, y, 0, MIT_TOWN, MI_ENEMYMONST, i, 0, 0);
//check if AddMissile unsuccessful
if (mi == -1)
return; //too many missiles already, so quit
// Force open
SetMissDir(mi, 1);
// Give it a lightsource
//DL - 11/9/97
// This is a serious bug. Under certain situations, missile[i] will be
// uninitialized, causing coordinate (0, 0) to be passed to AddLight().
// When the light is processed later, and the radius is subtracted from
// the (0, 0) coordinate, the light table will be written to with negative
// indicies, causing an array underwrite. This was causing a crash on the
// Mac because it was overwriting the memory block header, trashing the
// application's heap. I don't know what is getting overwritten on the PC
// version. An example of when this will happen is if player 1 creates a
// new game, and player 2 joins it. Both players go to level 1. Player 2
// casts town portal (with cheats on). On player 1's machine,
// AddWarpMissile( will be called with i = 1 (player 2's player index).
// Since there are no missles yet, AddMissile() will use missle index 0, so
// mi wil be 0. But since i is 1, AddLight() will be passed the coordinates
// of missle[1], which doesn't exist, so its coordinates are undefined. In
// this case, they are uninitialized, so they are zero.
// if (currlevel != 0) missile[i]._mlid = AddLight(missile[i]._mix, missile[i]._miy, 15);
if (currlevel != 0) missile[mi]._mlid = AddLight(missile[mi]._mix, missile[mi]._miy, 15);
// play sound while in dungeon
missiledata[MIT_TOWN].mlSFX = LS_SENTINEL;
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void SyncPortals()
{
// Add the warp fields
for (int i = 0; i < MAXPORTAL; i++) {
if (portal[i].open) {
if (currlevel == 0) {
AddWarpMissile(i, WarpDropX[i], WarpDropY[i]);
} else {
if (! setlevel) {
if (portal[i].level == currlevel) AddWarpMissile(i, portal[i].x, portal[i].y);
} else {
if (portal[i].level == setlvlnum) AddWarpMissile(i, portal[i].x, portal[i].y);
}
}
}
}
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void AddInTownPortal(int i)
{
AddWarpMissile(i, WarpDropX[i], WarpDropY[i]);
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void ActivatePortal(int i, int x, int y, int lvl, int lvltype, BOOL sp)
{
app_assert((DWORD)i < MAXPORTAL);
portal[i].open = TRUE;
if (lvl != 0) {
portal[i].x = x;
portal[i].y = y;
portal[i].level = lvl;
portal[i].ltype = lvltype;
portal[i].setlvl = sp;
}
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void DeactivatePortal(int i)
{
app_assert((DWORD)i < MAXPORTAL);
portal[i].open = FALSE;
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
BOOL PortalOnLevel(int i)
{
app_assert((DWORD)i < MAXPORTAL);
if (portal[i].level == currlevel) return(TRUE);
if (currlevel == 0) return(TRUE);
else return(FALSE);
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void RemovePortalMissile(int id)
{
int i, mi;
// Remove current portal
for (i = 0; i < nummissiles; i++) {
mi = missileactive[i];
if ((missile[mi]._mitype == MIT_TOWN) && (missile[mi]._misource == id)) {
dFlags[missile[mi]._mix][missile[mi]._miy] &= BFMASK_MISSILE;
dMissile[missile[mi]._mix][missile[mi]._miy] = 0;
if (portal[id].level != 0) AddUnLight(missile[mi]._mlid);
DeleteMissile(mi, i);
}
}
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void SetCurrentPortal(int p)
{
portalindex = p;
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void GetPortalLevel() {
if (currlevel) {
setlevel = FALSE;
currlevel = 0;
plr[myplr].plrlevel = 0;
leveltype = 0;
return;
}
app_assert((DWORD)portalindex < MAXPORTAL);
if (portal[portalindex].setlvl) {
setlevel = TRUE;
setlvlnum = portal[portalindex].level;
currlevel = portal[portalindex].level;
plr[myplr].plrlevel = setlvlnum;
leveltype = portal[portalindex].ltype;
}
else {
setlevel = FALSE;
currlevel = portal[portalindex].level;
plr[myplr].plrlevel = currlevel;
leveltype = portal[portalindex].ltype;
}
if (portalindex == myplr) {
NetSendCmd(TRUE, CMD_DEACTIVATEPORTAL);
DeactivatePortal(portalindex);
}
}
/*-----------------------------------------------------------------------**
**-----------------------------------------------------------------------*/
void GetPortalLvlPos()
{
app_assert((DWORD)portalindex < MAXPORTAL);
if (!currlevel) {
ViewX = WarpDropX[portalindex] + 1;
ViewY = WarpDropY[portalindex] + 1;
return;
}
ViewX = portal[portalindex].x;
ViewY = portal[portalindex].y;
if (portalindex != myplr) {
ViewX++;
ViewY++;
}
}
| 412 | 0.687652 | 1 | 0.687652 | game-dev | MEDIA | 0.590587 | game-dev | 0.719963 | 1 | 0.719963 |
SlimeKnights/Mantle | 5,918 | src/main/java/slimeknights/mantle/client/book/data/PageData.java | package slimeknights.mantle.client.book.data;
import com.google.gson.JsonElement;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.TrueCondition;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.client.book.BookLoader;
import slimeknights.mantle.client.book.data.content.ContentError;
import slimeknights.mantle.client.book.data.content.PageContent;
import slimeknights.mantle.client.book.data.element.IDataElement;
import slimeknights.mantle.client.book.repository.BookRepository;
import slimeknights.mantle.util.DataLoadedConditionContext;
import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Map;
public class PageData implements IDataItem, IConditional {
public String name = null;
public ResourceLocation type = Mantle.getResource("blank");
public String data = "";
public float scale = 1.0F;
public ICondition condition = TrueCondition.INSTANCE;
/** Contains arbitrary data to be used by custom transformers and other things */
public Map<ResourceLocation, JsonElement> extraData = Collections.emptyMap();
public transient SectionData parent;
public transient BookRepository source;
public transient PageContent content;
@SuppressWarnings("unused") // used implicitly by GSON
public PageData() {
this(false);
}
public PageData(boolean custom) {
if (custom) {
this.data = "no-load";
}
}
@SuppressWarnings("unused") // utility
public String translate(String string) {
return this.parent.translate(string);
}
@Override
public void load() {
if (this.name == null) {
this.name = "page" + this.parent.unnamedPageCounter++;
}
this.name = this.name.toLowerCase();
Class<? extends PageContent> ctype = BookLoader.getPageType(type);
if (!this.data.isEmpty() && !this.data.equals("no-load")) {
Resource pageInfo = this.source.getResource(this.source.getResourceLocation(this.data));
if (pageInfo != null) {
String data = this.source.resourceToString(pageInfo);
if (!data.isEmpty()) {
// Test if the page type is specified within the content iteself
PageTypeOverrider overrider = BookLoader.getGson().fromJson(data, PageTypeOverrider.class);
if (overrider.type != null) {
Class<? extends PageContent> overriddenType = BookLoader.getPageType(overrider.type);
if(overriddenType != null) {
ctype = BookLoader.getPageType(overrider.type);
// Also override the type on the page so that we can read it out in transformers
type = overrider.type;
}
}
if (ctype != null) {
try {
this.content = BookLoader.getGson().fromJson(data, ctype);
} catch (Exception e) {
this.content = new ContentError("Failed to create a page of type \"" + this.type + "\", perhaps the page file \"" + this.data + "\" is missing or invalid?", e);
e.printStackTrace();
}
} else {
this.content = new ContentError("Failed to create a page of type \"" + this.type + "\" as it is not registered.");
}
}
}
}
if (this.content == null) {
if (ctype != null) {
try {
this.content = ctype.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NullPointerException | NoSuchMethodException | InvocationTargetException e) {
this.content = new ContentError("Failed to create a page of type \"" + this.type + "\".", e);
e.printStackTrace();
}
} else {
this.content = new ContentError("Failed to create a page of type \"" + this.type + "\" as it is not registered.");
}
}
try {
this.content.parent = this;
this.content.load();
} catch (Exception e) {
this.content = new ContentError("Failed to load page " + this.parent.name + "." + this.name + ".", e);
e.printStackTrace();
}
this.content.source = this.source;
for (Field f : this.content.getClass().getFields()) {
this.processField(f);
}
}
private void processField(Field f) {
f.setAccessible(true);
if (Modifier.isTransient(f.getModifiers()) || Modifier.isStatic(f.getModifiers()) || Modifier
.isFinal(f.getModifiers())) {
return;
}
try {
Object o = f.get(this.content);
if (o != null) {
this.processObject(o, 0);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void processObject(@Nullable Object o, final int depth) {
if (depth > 4 || o == null)
return;
Class<?> c = o.getClass();
boolean isArray = c.isArray();
if (!isArray) {
if (IDataElement.class.isAssignableFrom(c)) {
((IDataElement) o).load(this.source);
}
return;
}
for (int i = 0; i < Array.getLength(o); i++) {
this.processObject(Array.get(o, i), depth + 1);
}
}
/** Gets the title for the page data, which can be overridden by translation */
public String getTitle() {
String title = this.parent.parent.strings.get(this.parent.name + "." + this.name);
if (title != null) {
return title;
}
title = content.getTitle();
if (title != null && !title.isEmpty()) {
return title;
}
return this.name;
}
@Override
public boolean isConditionMet() {
return condition.test(DataLoadedConditionContext.INSTANCE);
}
private static class PageTypeOverrider {
public ResourceLocation type;
}
}
| 412 | 0.942881 | 1 | 0.942881 | game-dev | MEDIA | 0.382496 | game-dev | 0.989335 | 1 | 0.989335 |
KAMKEEL/CustomNPC-Plus | 1,641 | src/main/java/noppes/npcs/client/gui/model/GuiPresetSave.java | package noppes.npcs.client.gui.model;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import noppes.npcs.client.controllers.Preset;
import noppes.npcs.client.controllers.PresetController;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.entity.data.ModelData;
public class GuiPresetSave extends GuiNPCInterface {
private ModelData data;
private GuiScreen parent;
public GuiPresetSave(GuiScreen parent, ModelData data) {
this.data = data;
this.parent = parent;
xSize = 200;
this.drawDefaultBackground = true;
}
@Override
public void initGui() {
super.initGui();
this.addTextField(new GuiNpcTextField(0, this, guiLeft, guiTop + 70, 200, 20, ""));
this.addButton(new GuiNpcButton(0, guiLeft, guiTop + 100, 98, 20, "Save"));
this.addButton(new GuiNpcButton(1, guiLeft + 100, guiTop + 100, 98, 20, "Cancel"));
}
@Override
protected void actionPerformed(GuiButton btn) {
super.actionPerformed(btn);
GuiNpcButton button = (GuiNpcButton) btn;
if (button.id == 0) {
String name = this.getTextField(0).getText().trim();
if (name.isEmpty())
return;
Preset preset = new Preset();
preset.name = name;
preset.data = data.copy();
PresetController.instance.addPreset(preset);
}
mc.displayGuiScreen(parent);
}
@Override
public void save() {
}
}
| 412 | 0.817074 | 1 | 0.817074 | game-dev | MEDIA | 0.937536 | game-dev | 0.937822 | 1 | 0.937822 |
Fluorohydride/ygopro-scripts | 2,614 | c93751476.lua | --猛炎星-テンレイ
function c93751476.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetOperation(c93751476.regop)
c:RegisterEffect(e1)
--set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(93751476,1))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetCondition(c93751476.setcon)
e2:SetTarget(c93751476.settg)
e2:SetOperation(c93751476.setop)
c:RegisterEffect(e2)
end
function c93751476.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsReason(REASON_EFFECT) and c:IsReason(REASON_DESTROY) then
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(93751476,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_GRAVE)
e1:SetTarget(c93751476.sptg)
e1:SetOperation(c93751476.spop)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
end
function c93751476.spfilter(c,e,tp)
return c:IsSetCard(0x79) and c:IsLevel(4) and not c:IsCode(93751476) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c93751476.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c93751476.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c93751476.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c93751476.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c93751476.setcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO
and e:GetHandler():GetReasonCard():IsSetCard(0x79)
end
function c93751476.filter(c)
return c:IsSetCard(0x7c) and c:IsType(TYPE_SPELL) and c:IsSSetable()
end
function c93751476.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c93751476.filter,tp,LOCATION_DECK,0,1,nil) end
end
function c93751476.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c93751476.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g:GetFirst())
end
end
| 412 | 0.90938 | 1 | 0.90938 | game-dev | MEDIA | 0.964077 | game-dev | 0.94325 | 1 | 0.94325 |
mills32/M3D-for-PlayStation-Portable | 10,808 | M3D_LIBS/bullet-2.82-r2704/Demos/CcdPhysicsDemo/CcdPhysicsDemo.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#define CUBE_HALF_EXTENTS 1
#define EXTRA_HEIGHT 1.f
#include "CcdPhysicsDemo.h"
#include "GlutStuff.h"
#include "GLDebugFont.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h"
#include <stdio.h> //printf debugging
#include "GLDebugDrawer.h"
#if 0
extern btAlignedObjectArray<btVector3> debugContacts;
extern btAlignedObjectArray<btVector3> debugNormals;
#endif
static GLDebugDrawer sDebugDrawer;
CcdPhysicsDemo::CcdPhysicsDemo()
:m_ccdMode(USE_CCD)
{
setDebugMode(btIDebugDraw::DBG_DrawText+btIDebugDraw::DBG_NoHelpText);
setCameraDistance(btScalar(40.));
}
void CcdPhysicsDemo::clientMoveAndDisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//simple dynamics world doesn't handle fixed-time-stepping
//float ms = getDeltaTimeMicroseconds();
///step the simulation
if (m_dynamicsWorld)
{
m_dynamicsWorld->stepSimulation(1./60.,0);//ms / 1000000.f);
//optional but useful: debug drawing
m_dynamicsWorld->debugDrawWorld();
}
renderme();
displayText();
#if 0
for (int i=0;i<debugContacts.size();i++)
{
getDynamicsWorld()->getDebugDrawer()->drawContactPoint(debugContacts[i],debugNormals[i],0,0,btVector3(1,0,0));
}
#endif
glFlush();
swapBuffers();
}
void CcdPhysicsDemo::displayText()
{
int lineWidth=440;
int xStart = m_glutScreenWidth - lineWidth;
int yStart = 20;
if((getDebugMode() & btIDebugDraw::DBG_DrawText)!=0)
{
setOrthographicProjection();
glDisable(GL_LIGHTING);
glColor3f(0, 0, 0);
char buf[124];
glRasterPos3f(xStart, yStart, 0);
switch (m_ccdMode)
{
case USE_CCD:
{
sprintf(buf,"Predictive contacts and motion clamping");
break;
}
case USE_NO_CCD:
{
sprintf(buf,"CCD handling disabled");
break;
}
default:
{
sprintf(buf,"unknown CCD setting");
};
};
GLDebugDrawString(xStart,20,buf);
glRasterPos3f(xStart, yStart, 0);
sprintf(buf,"Press 'p' to change CCD mode");
yStart+=20;
GLDebugDrawString(xStart,yStart,buf);
glRasterPos3f(xStart, yStart, 0);
sprintf(buf,"Press '.' or right mouse to shoot bullets");
yStart+=20;
GLDebugDrawString(xStart,yStart,buf);
glRasterPos3f(xStart, yStart, 0);
sprintf(buf,"space to restart, h(elp), t(ext), w(ire)");
yStart+=20;
GLDebugDrawString(xStart,yStart,buf);
resetPerspectiveProjection();
glEnable(GL_LIGHTING);
}
}
void CcdPhysicsDemo::displayCallback(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderme();
displayText();
//optional but useful: debug drawing to detect problems
if (m_dynamicsWorld)
{
m_dynamicsWorld->debugDrawWorld();
}
#if 0
for (int i=0;i<debugContacts.size();i++)
{
getDynamicsWorld()->getDebugDrawer()->drawContactPoint(debugContacts[i],debugNormals[i],0,0,btVector3(1,0,0));
}
#endif
glFlush();
swapBuffers();
}
void CcdPhysicsDemo::initPhysics()
{
setTexturing(true);
setShadows(true);
m_ShootBoxInitialSpeed = 4000.f;
m_defaultContactProcessingThreshold = 0.f;
///collision configuration contains default setup for memory, collision setup
m_collisionConfiguration = new btDefaultCollisionConfiguration();
// m_collisionConfiguration->setConvexConvexMultipointIterations();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
//m_dispatcher->registerCollisionCreateFunc(BOX_SHAPE_PROXYTYPE,BOX_SHAPE_PROXYTYPE,m_collisionConfiguration->getCollisionAlgorithmCreateFunc(CONVEX_SHAPE_PROXYTYPE,CONVEX_SHAPE_PROXYTYPE));
m_broadphase = new btDbvtBroadphase();
///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
m_solver = sol;
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
m_dynamicsWorld->getSolverInfo().m_solverMode |=SOLVER_USE_2_FRICTION_DIRECTIONS|SOLVER_RANDMIZE_ORDER;
m_dynamicsWorld ->setDebugDrawer(&sDebugDrawer);
//m_dynamicsWorld->getSolverInfo().m_splitImpulse=false;
if (m_ccdMode==USE_CCD)
{
m_dynamicsWorld->getDispatchInfo().m_useContinuous=true;
} else
{
m_dynamicsWorld->getDispatchInfo().m_useContinuous=false;
}
m_dynamicsWorld->setGravity(btVector3(0,-10,0));
///create a few basic rigid bodies
btBoxShape* box = new btBoxShape(btVector3(btScalar(110.),btScalar(1.),btScalar(110.)));
// box->initializePolyhedralFeatures();
btCollisionShape* groundShape = box;
// btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),50);
m_collisionShapes.push_back(groundShape);
//m_collisionShapes.push_back(new btCylinderShape (btVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS)));
m_collisionShapes.push_back(new btBoxShape (btVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS)));
btTransform groundTransform;
groundTransform.setIdentity();
//groundTransform.setOrigin(btVector3(5,5,5));
//We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
{
btScalar mass(0.);
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0);
if (isDynamic)
groundShape->calculateLocalInertia(mass,localInertia);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
body->setFriction(0.5);
//body->setRollingFriction(0.3);
//add the body to the dynamics world
m_dynamicsWorld->addRigidBody(body);
}
{
//create a few dynamic rigidbodies
// Re-using the same collision is better for memory usage and performance
btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
m_collisionShapes.push_back(colShape);
/// Create Dynamic Objects
btTransform startTransform;
startTransform.setIdentity();
btScalar mass(1.f);
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0,0,0);
if (isDynamic)
colShape->calculateLocalInertia(mass,localInertia);
int gNumObjects = 120;//120;
int i;
for (i=0;i<gNumObjects;i++)
{
btCollisionShape* shape = m_collisionShapes[1];
btTransform trans;
trans.setIdentity();
//stack them
int colsize = 10;
int row = (i*CUBE_HALF_EXTENTS*2)/(colsize*2*CUBE_HALF_EXTENTS);
int row2 = row;
int col = (i)%(colsize)-colsize/2;
if (col>3)
{
col=11;
row2 |=1;
}
btVector3 pos(col*2*CUBE_HALF_EXTENTS + (row2%2)*CUBE_HALF_EXTENTS,
row*2*CUBE_HALF_EXTENTS+CUBE_HALF_EXTENTS+EXTRA_HEIGHT,0);
trans.setOrigin(pos);
float mass = 1.f;
btRigidBody* body = localCreateRigidBody(mass,trans,shape);
body->setAnisotropicFriction(shape->getAnisotropicRollingFrictionDirection(),btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
body->setFriction(0.5);
//body->setRollingFriction(.3);
///when using m_ccdMode
if (m_ccdMode==USE_CCD)
{
body->setCcdMotionThreshold(CUBE_HALF_EXTENTS);
body->setCcdSweptSphereRadius(0.9*CUBE_HALF_EXTENTS);
}
}
}
}
void CcdPhysicsDemo::clientResetScene()
{
exitPhysics();
initPhysics();
}
void CcdPhysicsDemo::keyboardCallback(unsigned char key, int x, int y)
{
if (key=='p')
{
switch (m_ccdMode)
{
case USE_CCD:
{
m_ccdMode = USE_NO_CCD;
break;
}
case USE_NO_CCD:
default:
{
m_ccdMode = USE_CCD;
}
};
clientResetScene();
} else
{
DemoApplication::keyboardCallback(key,x,y);
}
}
void CcdPhysicsDemo::shootBox(const btVector3& destination)
{
if (m_dynamicsWorld)
{
float mass = 1.f;
btTransform startTransform;
startTransform.setIdentity();
btVector3 camPos = getCameraPosition();
startTransform.setOrigin(camPos);
setShootBoxShape ();
btRigidBody* body = this->localCreateRigidBody(mass, startTransform,m_shootBoxShape);
body->setLinearFactor(btVector3(1,1,1));
//body->setRestitution(1);
btVector3 linVel(destination[0]-camPos[0],destination[1]-camPos[1],destination[2]-camPos[2]);
linVel.normalize();
linVel*=m_ShootBoxInitialSpeed;
body->getWorldTransform().setOrigin(camPos);
body->getWorldTransform().setRotation(btQuaternion(0,0,0,1));
body->setLinearVelocity(linVel);
body->setAngularVelocity(btVector3(0,0,0));
body->setContactProcessingThreshold(1e30);
///when using m_ccdMode, disable regular CCD
if (m_ccdMode==USE_CCD)
{
body->setCcdMotionThreshold(CUBE_HALF_EXTENTS);
body->setCcdSweptSphereRadius(0.4f);
}
}
}
void CcdPhysicsDemo::exitPhysics()
{
//cleanup in the reverse order of creation/initialization
//remove the rigidbodies from the dynamics world and delete them
int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_dynamicsWorld->removeCollisionObject( obj );
delete obj;
}
//delete collision shapes
for (int j=0;j<m_collisionShapes.size();j++)
{
btCollisionShape* shape = m_collisionShapes[j];
delete shape;
}
m_collisionShapes.clear();
delete m_dynamicsWorld;
delete m_solver;
delete m_broadphase;
delete m_dispatcher;
delete m_collisionConfiguration;
}
| 412 | 0.908105 | 1 | 0.908105 | game-dev | MEDIA | 0.836915 | game-dev | 0.946604 | 1 | 0.946604 |
Maxlego08/zEssentials | 2,482 | src/main/java/fr/maxlego08/essentials/buttons/kit/ButtonKitGet.java | package fr.maxlego08.essentials.buttons.kit;
import fr.maxlego08.essentials.api.EssentialsPlugin;
import fr.maxlego08.essentials.api.kit.Kit;
import fr.maxlego08.essentials.api.user.User;
import fr.maxlego08.essentials.zutils.utils.TimerBuilder;
import fr.maxlego08.menu.api.utils.Placeholders;
import fr.maxlego08.menu.api.button.Button;
import fr.maxlego08.menu.api.engine.InventoryEngine;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.Optional;
public class ButtonKitGet extends Button {
private final EssentialsPlugin plugin;
private final String kitName;
public ButtonKitGet(EssentialsPlugin plugin, String kitName) {
this.plugin = plugin;
this.kitName = kitName;
}
@Override
public void onClick(Player player, InventoryClickEvent event, InventoryEngine inventory, int slot, Placeholders placeholders) {
User user = this.plugin.getUser(player.getUniqueId());
if (user == null) return;
Optional<Kit> optional = this.plugin.getKit(this.kitName);
if (optional.isEmpty()) return;
Kit kit = optional.get();
if (event.getClick().isLeftClick()) {
this.plugin.giveKit(user, kit, false);
} else if (event.getClick().isRightClick()) {
user.openKitPreview(kit);
return;
}
super.onClick(player, event, inventory, slot, placeholders);
}
@Override
public ItemStack getCustomItemStack(Player player) {
Placeholders placeholders = new Placeholders();
Optional<Kit> optional = this.plugin.getKit(this.kitName);
if (optional.isEmpty()) return super.getCustomItemStack(player);
Kit kit = optional.get();
placeholders.register("cooldown", TimerBuilder.getStringTime(kit.getCooldown() * 1000));
return this.getItemStack().build(player, false, placeholders);
}
@Override
public boolean hasPermission() {
return true;
}
@Override
public boolean checkPermission(Player player, InventoryEngine inventory, Placeholders placeholders) {
User user = this.plugin.getUser(player.getUniqueId());
if (user == null) return false;
Optional<Kit> optional = this.plugin.getKit(this.kitName);
return optional.filter(kit -> super.checkPermission(player, inventory, placeholders) && kit.hasPermission(player)).isPresent();
}
}
| 412 | 0.909561 | 1 | 0.909561 | game-dev | MEDIA | 0.957007 | game-dev | 0.928229 | 1 | 0.928229 |
LangYa466/MCPLite-all-source | 4,505 | src/main/java/net/minecraft/item/crafting/RecipesArmorDyes.java | /*
* Decompiled with CFR 0.151.
*/
package net.minecraft.item.crafting;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.world.World;
public class RecipesArmorDyes
implements IRecipe {
@Override
public boolean matches(InventoryCrafting inv, World worldIn) {
ItemStack itemstack = null;
ArrayList<ItemStack> list = Lists.newArrayList();
for (int i = 0; i < inv.getSizeInventory(); ++i) {
ItemStack itemstack1 = inv.getStackInSlot(i);
if (itemstack1 == null) continue;
if (itemstack1.getItem() instanceof ItemArmor) {
ItemArmor itemarmor = (ItemArmor)itemstack1.getItem();
if (itemarmor.getArmorMaterial() != ItemArmor.ArmorMaterial.LEATHER || itemstack != null) {
return false;
}
itemstack = itemstack1;
continue;
}
if (itemstack1.getItem() != Items.dye) {
return false;
}
list.add(itemstack1);
}
return itemstack != null && !list.isEmpty();
}
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack itemstack = null;
int[] aint = new int[3];
int i = 0;
int j = 0;
ItemArmor itemarmor = null;
for (int k = 0; k < inv.getSizeInventory(); ++k) {
ItemStack itemstack1 = inv.getStackInSlot(k);
if (itemstack1 == null) continue;
if (itemstack1.getItem() instanceof ItemArmor) {
itemarmor = (ItemArmor)itemstack1.getItem();
if (itemarmor.getArmorMaterial() != ItemArmor.ArmorMaterial.LEATHER || itemstack != null) {
return null;
}
itemstack = itemstack1.copy();
itemstack.stackSize = 1;
if (!itemarmor.hasColor(itemstack1)) continue;
int l = itemarmor.getColor(itemstack);
float f = (float)(l >> 16 & 0xFF) / 255.0f;
float f1 = (float)(l >> 8 & 0xFF) / 255.0f;
float f2 = (float)(l & 0xFF) / 255.0f;
i = (int)((float)i + Math.max(f, Math.max(f1, f2)) * 255.0f);
aint[0] = (int)((float)aint[0] + f * 255.0f);
aint[1] = (int)((float)aint[1] + f1 * 255.0f);
aint[2] = (int)((float)aint[2] + f2 * 255.0f);
++j;
continue;
}
if (itemstack1.getItem() != Items.dye) {
return null;
}
float[] afloat = EntitySheep.getDyeRgb(EnumDyeColor.byDyeDamage(itemstack1.getMetadata()));
int l1 = (int)(afloat[0] * 255.0f);
int i2 = (int)(afloat[1] * 255.0f);
int j2 = (int)(afloat[2] * 255.0f);
i += Math.max(l1, Math.max(i2, j2));
aint[0] = aint[0] + l1;
aint[1] = aint[1] + i2;
aint[2] = aint[2] + j2;
++j;
}
if (itemarmor == null) {
return null;
}
int i1 = aint[0] / j;
int j1 = aint[1] / j;
int k1 = aint[2] / j;
float f3 = (float)i / (float)j;
float f4 = Math.max(i1, Math.max(j1, k1));
i1 = (int)((float)i1 * f3 / f4);
j1 = (int)((float)j1 * f3 / f4);
k1 = (int)((float)k1 * f3 / f4);
int lvt_12_3_ = (i1 << 8) + j1;
lvt_12_3_ = (lvt_12_3_ << 8) + k1;
itemarmor.setColor(itemstack, lvt_12_3_);
return itemstack;
}
@Override
public int getRecipeSize() {
return 10;
}
@Override
public ItemStack getRecipeOutput() {
return null;
}
@Override
public ItemStack[] getRemainingItems(InventoryCrafting inv) {
ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i) {
ItemStack itemstack = inv.getStackInSlot(i);
if (itemstack == null || !itemstack.getItem().hasContainerItem()) continue;
aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem());
}
return aitemstack;
}
}
| 412 | 0.819058 | 1 | 0.819058 | game-dev | MEDIA | 0.99615 | game-dev | 0.895569 | 1 | 0.895569 |
ellioman/ShaderProject | 7,741 | Assets/Editor/ImageEffects/BloomAndFlaresEditor.cs | using System;
using UnityEditor;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[CustomEditor (typeof(BloomAndFlares))]
class BloomAndFlaresEditor : Editor
{
SerializedProperty tweakMode;
SerializedProperty screenBlendMode;
SerializedObject serObj;
SerializedProperty hdr;
SerializedProperty sepBlurSpread;
SerializedProperty useSrcAlphaAsMask;
SerializedProperty bloomIntensity;
SerializedProperty bloomthreshold;
SerializedProperty bloomBlurIterations;
SerializedProperty lensflares;
SerializedProperty hollywoodFlareBlurIterations;
SerializedProperty lensflareMode;
SerializedProperty hollyStretchWidth;
SerializedProperty lensflareIntensity;
SerializedProperty lensflarethreshold;
SerializedProperty flareColorA;
SerializedProperty flareColorB;
SerializedProperty flareColorC;
SerializedProperty flareColorD;
SerializedProperty lensFlareVignetteMask;
void OnEnable () {
serObj = new SerializedObject (target);
screenBlendMode = serObj.FindProperty("screenBlendMode");
hdr = serObj.FindProperty("hdr");
sepBlurSpread = serObj.FindProperty("sepBlurSpread");
useSrcAlphaAsMask = serObj.FindProperty("useSrcAlphaAsMask");
bloomIntensity = serObj.FindProperty("bloomIntensity");
bloomthreshold = serObj.FindProperty("bloomThreshold");
bloomBlurIterations = serObj.FindProperty("bloomBlurIterations");
lensflares = serObj.FindProperty("lensflares");
lensflareMode = serObj.FindProperty("lensflareMode");
hollywoodFlareBlurIterations = serObj.FindProperty("hollywoodFlareBlurIterations");
hollyStretchWidth = serObj.FindProperty("hollyStretchWidth");
lensflareIntensity = serObj.FindProperty("lensflareIntensity");
lensflarethreshold = serObj.FindProperty("lensflareThreshold");
flareColorA = serObj.FindProperty("flareColorA");
flareColorB = serObj.FindProperty("flareColorB");
flareColorC = serObj.FindProperty("flareColorC");
flareColorD = serObj.FindProperty("flareColorD");
lensFlareVignetteMask = serObj.FindProperty("lensFlareVignetteMask");
tweakMode = serObj.FindProperty("tweakMode");
}
public override void OnInspectorGUI () {
serObj.Update();
GUILayout.Label("HDR " + (hdr.enumValueIndex == 0 ? "auto detected, " : (hdr.enumValueIndex == 1 ? "forced on, " : "disabled, ")) + (useSrcAlphaAsMask.floatValue < 0.1f ? " ignoring alpha channel glow information" : " using alpha channel glow information"), EditorStyles.miniBoldLabel);
EditorGUILayout.PropertyField (tweakMode, new GUIContent("Tweak mode"));
EditorGUILayout.PropertyField (screenBlendMode, new GUIContent("Blend mode"));
EditorGUILayout.PropertyField (hdr, new GUIContent("HDR"));
// display info text when screen blend mode cannot be used
Camera cam = (target as BloomAndFlares).GetComponent<Camera>();
if (cam != null) {
if (screenBlendMode.enumValueIndex==0 && ((cam.hdr && hdr.enumValueIndex==0) || (hdr.enumValueIndex==1))) {
EditorGUILayout.HelpBox("Screen blend is not supported in HDR. Using 'Add' instead.", MessageType.Info);
}
}
if (1 == tweakMode.intValue)
EditorGUILayout.PropertyField (lensflares, new GUIContent("Cast lens flares"));
EditorGUILayout.Separator ();
EditorGUILayout.PropertyField (bloomIntensity, new GUIContent("Intensity"));
bloomthreshold.floatValue = EditorGUILayout.Slider ("threshold", bloomthreshold.floatValue, -0.05f, 4.0f);
bloomBlurIterations.intValue = EditorGUILayout.IntSlider ("Blur iterations", bloomBlurIterations.intValue, 1, 4);
sepBlurSpread.floatValue = EditorGUILayout.Slider ("Blur spread", sepBlurSpread.floatValue, 0.1f, 10.0f);
if (1 == tweakMode.intValue)
useSrcAlphaAsMask.floatValue = EditorGUILayout.Slider (new GUIContent("Use alpha mask", "Make alpha channel define glowiness"), useSrcAlphaAsMask.floatValue, 0.0f, 1.0f);
else
useSrcAlphaAsMask.floatValue = 0.0f;
if (1 == tweakMode.intValue) {
EditorGUILayout.Separator ();
if (lensflares.boolValue) {
// further lens flare tweakings
if (0 != tweakMode.intValue)
EditorGUILayout.PropertyField (lensflareMode, new GUIContent("Lens flare mode"));
else
lensflareMode.enumValueIndex = 0;
EditorGUILayout.PropertyField(lensFlareVignetteMask, new GUIContent("Lens flare mask", "This mask is needed to prevent lens flare artifacts"));
EditorGUILayout.PropertyField (lensflareIntensity, new GUIContent("Local intensity"));
lensflarethreshold.floatValue = EditorGUILayout.Slider ("Local threshold", lensflarethreshold.floatValue, 0.0f, 1.0f);
if (lensflareMode.intValue == 0) {
// ghosting
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.PropertyField (flareColorA, new GUIContent("1st Color"));
EditorGUILayout.PropertyField (flareColorB, new GUIContent("2nd Color"));
EditorGUILayout.EndHorizontal ();
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.PropertyField (flareColorC, new GUIContent("3rd Color"));
EditorGUILayout.PropertyField (flareColorD, new GUIContent("4th Color"));
EditorGUILayout.EndHorizontal ();
}
else if (lensflareMode.intValue == 1) {
// hollywood
EditorGUILayout.PropertyField (hollyStretchWidth, new GUIContent("Stretch width"));
hollywoodFlareBlurIterations.intValue = EditorGUILayout.IntSlider ("Blur iterations", hollywoodFlareBlurIterations.intValue, 1, 4);
EditorGUILayout.PropertyField (flareColorA, new GUIContent("Tint Color"));
}
else if (lensflareMode.intValue == 2) {
// both
EditorGUILayout.PropertyField (hollyStretchWidth, new GUIContent("Stretch width"));
hollywoodFlareBlurIterations.intValue = EditorGUILayout.IntSlider ("Blur iterations", hollywoodFlareBlurIterations.intValue, 1, 4);
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.PropertyField (flareColorA, new GUIContent("1st Color"));
EditorGUILayout.PropertyField (flareColorB, new GUIContent("2nd Color"));
EditorGUILayout.EndHorizontal ();
EditorGUILayout.BeginHorizontal ();
EditorGUILayout.PropertyField (flareColorC, new GUIContent("3rd Color"));
EditorGUILayout.PropertyField (flareColorD, new GUIContent("4th Color"));
EditorGUILayout.EndHorizontal ();
}
}
} else
lensflares.boolValue = false; // disable lens flares in simple tweak mode
serObj.ApplyModifiedProperties();
}
}
}
| 412 | 0.965173 | 1 | 0.965173 | game-dev | MEDIA | 0.58129 | game-dev,graphics-rendering | 0.991856 | 1 | 0.991856 |
Paril/mcskin3d | 3,876 | Models/Convert/ModelQuadruped.cs | #if CONVERT_MODELS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static MCSkin3D.ModelLoader;
namespace MCSkin3D.Models.Convert
{
public class ModelQuadruped : ModelBase
{
public ModelRenderer head;
public ModelRenderer body;
public ModelRenderer leg1;
public ModelRenderer leg2;
public ModelRenderer leg3;
public ModelRenderer leg4;
protected float childYOffset = 8.0F;
protected float childZOffset = 4.0F;
public ModelQuadruped(int p_i1154_1_, float p_i1154_2_)
{
this.head = new ModelRenderer(this, 0, 0);
this.head.addBox(-4.0F, -4.0F, -8.0F, 8, 8, 8, p_i1154_2_, "Head");
this.head.setRotationPoint(0.0F, (float)(18 - p_i1154_1_), -6.0F);
this.body = new ModelRenderer(this, 28, 8);
this.body.addBox(-5.0F, -10.0F, -7.0F, 10, 16, 8, p_i1154_2_, "Body");
this.body.setRotationPoint(0.0F, (float)(17 - p_i1154_1_), 2.0F);
this.leg1 = new ModelRenderer(this, 0, 16);
this.leg1.addBox(-2.0F, 0.0F, -2.0F, 4, p_i1154_1_, 4, p_i1154_2_, "Back Right Leg");
this.leg1.setRotationPoint(-3.0F, (float)(24 - p_i1154_1_), 7.0F);
this.leg2 = new ModelRenderer(this, 0, 16);
this.leg2.addBox(-2.0F, 0.0F, -2.0F, 4, p_i1154_1_, 4, p_i1154_2_, "Back Left Leg");
this.leg2.setRotationPoint(3.0F, (float)(24 - p_i1154_1_), 7.0F);
this.leg3 = new ModelRenderer(this, 0, 16);
this.leg3.addBox(-2.0F, 0.0F, -2.0F, 4, p_i1154_1_, 4, p_i1154_2_, "Front Right Leg");
this.leg3.setRotationPoint(-3.0F, (float)(24 - p_i1154_1_), -5.0F);
this.leg4 = new ModelRenderer(this, 0, 16);
this.leg4.addBox(-2.0F, 0.0F, -2.0F, 4, p_i1154_1_, 4, p_i1154_2_, "Front Left Leg");
this.leg4.setRotationPoint(3.0F, (float)(24 - p_i1154_1_), -5.0F);
}
#if RENDER
/**
* Sets the models various rotation angles then renders the model.
*/
public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale)
{
this.setRotationAngles(p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale, entityIn);
if (this.isChild)
{
float f = 2.0F;
GlStateManager.pushMatrix();
GlStateManager.translate(0.0F, this.childYOffset * scale, this.childZOffset * scale);
this.head.render(scale);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
GlStateManager.scale(1.0F / f, 1.0F / f, 1.0F / f);
GlStateManager.translate(0.0F, 24.0F * scale, 0.0F);
this.body.render(scale);
this.leg1.render(scale);
this.leg2.render(scale);
this.leg3.render(scale);
this.leg4.render(scale);
GlStateManager.popMatrix();
}
else
{
this.head.render(scale);
this.body.render(scale);
this.leg1.render(scale);
this.leg2.render(scale);
this.leg3.render(scale);
this.leg4.render(scale);
}
}
#endif
/**
* Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms
* and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how
* "far" arms and legs can swing at most.
*/
public virtual void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
{
this.head.rotateAngleX = headPitch * 0.017453292F;
this.head.rotateAngleY = netHeadYaw * 0.017453292F;
this.body.rotateAngleX = ((float)Math.PI / 2F);
this.leg1.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
this.leg2.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount;
this.leg3.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount;
this.leg4.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
}
}
}
#endif | 412 | 0.74627 | 1 | 0.74627 | game-dev | MEDIA | 0.869576 | game-dev,graphics-rendering | 0.984573 | 1 | 0.984573 |
rfsheffer/RyHelpfulHelpers | 20,928 | Source/RyRuntime/Private/RyRuntimeObjectHelpers.cpp | // Copyright 2020-2023 Solar Storm Interactive
#include "RyRuntimeObjectHelpers.h"
#include "UObject/ObjectRedirector.h"
#include "RyRuntimeModule.h"
#include "UObject/Package.h"
#include "UObject/UObjectIterator.h"
#include "LatentActions.h"
#include "Runtime/Launch/Resources/Version.h"
#include "Engine/LatentActionManager.h"
#include "TimerManager.h"
#include "Engine/Engine.h"
// Async asset loading extension
#include "Engine/StreamableManager.h"
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::RemoveLatentActionsForObject(UObject* WorldContextObject, UObject* object)
{
if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
{
World->GetLatentActionManager().RemoveActionsForObject(object);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::ClearAllTimersForObject(UObject* WorldContextObject, UObject* object)
{
if (const UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
{
World->GetTimerManager().ClearAllTimersForObject(object);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::CreateObject(TSubclassOf<UObject> objectClass, UObject* outer, UObject*& objectOut)
{
if(!objectClass)
{
objectOut = nullptr;
return;
}
objectOut = NewObject<UObject>(outer ? outer : GetTransientPackage(), objectClass);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::DuplicateObject(TSubclassOf<UObject> objectClass, UObject* object, UObject* outer, UObject*& objectOut)
{
if(!object)
{
objectOut = nullptr;
return;
}
objectOut = ::DuplicateObject(object, outer ? outer : object->GetOuter());
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::IsLiveSoftObjectReference(const TSoftObjectPtr<UObject>& SoftObjectReference)
{
if(SoftObjectReference.IsNull())
return false;
const TPersistentObjectPtr<FSoftObjectPath> persistObjPtr(SoftObjectReference.ToSoftObjectPath());
return persistObjPtr.Get(false) != nullptr;
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
FString URyRuntimeObjectHelpers::SoftObjectToString(const TSoftObjectPtr<UObject>& SoftObjectReference)
{
return SoftObjectReference.ToString();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::IsSoftObjectPending(const TSoftObjectPtr<UObject>& SoftObjectReference)
{
return SoftObjectReference.IsPending();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::IsSoftObjectNull(const TSoftObjectPtr<UObject>& SoftObjectReference)
{
return SoftObjectReference.IsNull();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::IsSoftObjectValid(const TSoftObjectPtr<>& SoftObjectReference)
{
return SoftObjectReference.IsValid();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UPackage* URyRuntimeObjectHelpers::FindOrLoadPackage(const FString& PackageName)
{
UPackage* Pkg = FindPackage(nullptr, *PackageName);
if(!Pkg)
{
Pkg = LoadPackage(nullptr, *PackageName, LOAD_NoWarn | LOAD_Quiet);
}
return Pkg;
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UObject* URyRuntimeObjectHelpers::LoadObjectFromPackage(UPackage* package, const FString& objectName)
{
if(!package)
{
return nullptr;
}
return ::LoadObject<UObject>(package, *objectName);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UPackage* URyRuntimeObjectHelpers::GetPackageOfObject(UObject* object)
{
if(!object)
return nullptr;
return object->GetOutermost();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::MarkObjectPackageDirty(UObject* object, bool callPostEditChange)
{
if(object)
{
const bool result = object->MarkPackageDirty();
#if WITH_EDITOR
if(callPostEditChange)
{
object->PostEditChange();
}
#endif
return result;
}
return false;
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::GetObjectsInPackage(UPackage* package, TArray<UObject*>& ObjectsOut)
{
if(!package)
{
return;
}
if(!package->IsFullyLoaded())
{
package->FullyLoad();
}
for(TObjectIterator<UObject> ObjIt; ObjIt; ++ObjIt)
{
UObject* Object = *ObjIt;
if(Object->IsIn(package))
{
ObjectsOut.Add(Object);
}
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::TryConvertFilenameToLongPackageName(const FString& InFilename, FString& OutPackageName, FString& OutFailureReason)
{
return FPackageName::TryConvertFilenameToLongPackageName(InFilename, OutPackageName, &OutFailureReason);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UObject* URyRuntimeObjectHelpers::LoadObject(const FString& fullObjectPath)
{
UObject* LoadedObject = StaticLoadObject(UObject::StaticClass(), nullptr, *fullObjectPath, nullptr, LOAD_None, nullptr, true, nullptr);
#if WITH_EDITOR
// Look at core redirects if we didn't find the object
if(!LoadedObject)
{
FSoftObjectPath FixupObjectPath = fullObjectPath;
if(FixupObjectPath.FixupCoreRedirects())
{
LoadedObject = ::LoadObject<UObject>(nullptr, *FixupObjectPath.ToString());
}
}
#endif
while(const UObjectRedirector* Redirector = Cast<UObjectRedirector>(LoadedObject))
{
LoadedObject = Redirector->DestinationObject;
}
return LoadedObject;
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
struct FLoadAssetPriorityActionBase : FPendingLatentAction
{
// @TODO: it would be good to have static/global manager?
FSoftObjectPath SoftObjectPath;
FStreamableManager StreamableManager;
TSharedPtr<FStreamableHandle> Handle;
FName ExecutionFunction;
int32 OutputLink;
FWeakObjectPtr CallbackTarget;
virtual void OnLoaded() PURE_VIRTUAL(FLoadAssetPriorityActionBase::OnLoaded, );
FLoadAssetPriorityActionBase(const FSoftObjectPath& InSoftObjectPath, const int32 Priority, const FLatentActionInfo& InLatentInfo)
: SoftObjectPath(InSoftObjectPath)
, ExecutionFunction(InLatentInfo.ExecutionFunction)
, OutputLink(InLatentInfo.Linkage)
, CallbackTarget(InLatentInfo.CallbackTarget)
{
Handle = StreamableManager.RequestAsyncLoad(SoftObjectPath, FStreamableDelegate(), Priority);
}
virtual ~FLoadAssetPriorityActionBase() override
{
if (Handle.IsValid())
{
Handle->ReleaseHandle();
}
}
virtual void UpdateOperation(FLatentResponse& Response) override
{
const bool bLoaded = !Handle.IsValid() || Handle->HasLoadCompleted() || Handle->WasCanceled();
if (bLoaded)
{
OnLoaded();
}
Response.FinishAndTriggerIf(bLoaded, ExecutionFunction, OutputLink, CallbackTarget);
}
#if WITH_EDITOR
virtual FString GetDescription() const override
{
return FString::Printf(TEXT("Load Asset Priority Action Base: %s"), *SoftObjectPath.ToString());
}
#endif
};
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::LoadAssetPriority(UObject* WorldContextObject, const TSoftObjectPtr<UObject> Asset, const int32 Priority,
FOnAssetLoaded OnLoaded, FLatentActionInfo LatentInfo)
{
struct FLoadAssetAction : FLoadAssetPriorityActionBase
{
FOnAssetLoaded OnLoadedCallback;
FLoadAssetAction(const FSoftObjectPath& InSoftObjectPath, const int32 Priority, FOnAssetLoaded InOnLoadedCallback, const FLatentActionInfo& InLatentInfo)
: FLoadAssetPriorityActionBase(InSoftObjectPath, Priority, InLatentInfo)
, OnLoadedCallback(InOnLoadedCallback)
{}
virtual void OnLoaded() override
{
UObject* LoadedObject = SoftObjectPath.ResolveObject();
OnLoadedCallback.ExecuteIfBound(LoadedObject);
}
};
if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
{
FLatentActionManager& LatentManager = World->GetLatentActionManager();
// We always spawn a new load even if this node already queued one, the outside node handles this case
FLoadAssetAction* NewAction = new FLoadAssetAction(Asset.ToSoftObjectPath(), Priority, OnLoaded, LatentInfo);
LatentManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, NewAction);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
struct FLoadPackagePriorityActionBase : FPendingLatentAction
{
FString PackagePath;
FName ExecutionFunction;
int32 OutputLink;
FWeakObjectPtr CallbackTarget;
EAsyncLoadingResult::Type Result;
UPackage* LoadedPackage;
int32 LoadRequest;
FLoadPackageAsyncDelegate LoadCB;
virtual void OnLoaded() PURE_VIRTUAL(FLoadPackagePriorityActionBase::OnLoaded, );
FLoadPackagePriorityActionBase(const FString& packagePath, const int32 priority, const bool blockOnLoad, const FLatentActionInfo& inLatentInfo)
: PackagePath(packagePath)
, ExecutionFunction(inLatentInfo.ExecutionFunction)
, OutputLink(inLatentInfo.Linkage)
, CallbackTarget(inLatentInfo.CallbackTarget)
, Result(EAsyncLoadingResult::Failed)
, LoadedPackage(nullptr)
{
LoadCB.BindRaw(this, &FLoadPackagePriorityActionBase::OnPackageLoadCompleteCB);
#if ENGINE_MAJOR_VERSION >= 5
FPackagePath packagePathStruct;
if(FPackagePath::TryFromPackageName(*PackagePath, packagePathStruct))
{
LoadRequest = LoadPackageAsync(packagePathStruct, NAME_None, LoadCB, PKG_None, INDEX_NONE, priority);
}
else
{
LoadRequest = INDEX_NONE;
}
#else
LoadRequest = LoadPackageAsync(PackagePath, nullptr, nullptr, LoadCB, PKG_None, INDEX_NONE, priority);
#endif
if(LoadRequest != INDEX_NONE)
{
if(blockOnLoad)
{
FlushAsyncLoading(LoadRequest);
}
}
}
void OnPackageLoadCompleteCB(const FName& packagePath, UPackage* loadedPackage, EAsyncLoadingResult::Type result)
{
Result = result;
LoadedPackage = loadedPackage;
LoadRequest = INDEX_NONE;
}
virtual void UpdateOperation(FLatentResponse& Response) override
{
const bool bLoaded = LoadRequest == INDEX_NONE;
if (bLoaded)
{
OnLoaded();
}
Response.FinishAndTriggerIf(bLoaded, ExecutionFunction, OutputLink, CallbackTarget);
}
#if WITH_EDITOR
virtual FString GetDescription() const override
{
return FString::Printf(TEXT("Load Package Priority Action Base: %s"), *PackagePath);
}
#endif
};
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::LoadPackagePriority(UObject* WorldContextObject, const FString& PackagePath, const int32 Priority,
const bool BlockOnLoad, FOnPackageLoaded OnLoaded, FLatentActionInfo LatentInfo)
{
struct FLoadPackageAction : FLoadPackagePriorityActionBase
{
FOnPackageLoaded OnLoadedCallback;
FLoadPackageAction(const FString& packagePath, const int32 priority, const bool blockOnLoad, FOnPackageLoaded onPackageLoaded, const FLatentActionInfo& inLatentInfo)
: FLoadPackagePriorityActionBase(packagePath, priority, blockOnLoad, inLatentInfo)
, OnLoadedCallback(onPackageLoaded)
{}
virtual void OnLoaded() override
{
OnLoadedCallback.ExecuteIfBound(LoadedPackage, static_cast<ERyAsyncLoadingResult>(Result));
}
};
if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
{
FLatentActionManager& LatentManager = World->GetLatentActionManager();
// We always spawn a new load even if this node already queued one, the outside node handles this case
FLoadPackageAction* NewAction = new FLoadPackageAction(PackagePath, Priority, BlockOnLoad, OnLoaded, LatentInfo);
LatentManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, NewAction);
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::RegisterMountPoint(const FString& RootPath, const FString& ContentPath)
{
FPackageName::RegisterMountPoint(RootPath, ContentPath);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::UnRegisterMountPoint(const FString& RootPath, const FString& ContentPath)
{
FPackageName::UnRegisterMountPoint(RootPath, ContentPath);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::MountPointExists(const FString& RootPath)
{
return FPackageName::MountPointExists(RootPath);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
FName URyRuntimeObjectHelpers::GetPackageMountPoint(const FString& InPackagePath, bool InWithoutSlashes)
{
return FPackageName::GetPackageMountPoint(InPackagePath, InWithoutSlashes);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UClass* URyRuntimeObjectHelpers::GetParentClass(UClass* Class)
{
if(!Class)
return nullptr;
return Class->GetSuperClass();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
void URyRuntimeObjectHelpers::GetClassHierarchy(UClass* Class, TArray<UClass*>& ClassHierarchy, const bool includeSelf)
{
UClass* NextClass = Class;
if(NextClass && includeSelf)
{
ClassHierarchy.Add(NextClass);
}
while(NextClass && NextClass->GetSuperClass())
{
ClassHierarchy.Add(NextClass->GetSuperClass());
NextClass = NextClass->GetSuperClass();
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
UObject* URyRuntimeObjectHelpers::GetClassDefaultObject(TSubclassOf<UObject> theClass)
{
if(!theClass)
{
return nullptr;
}
return theClass->GetDefaultObject();
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::SetObjectPropertyValue(UObject* object, const FName PropertyName, const FString& Value, const bool PrintWarnings)
{
if(!object)
{
return false;
}
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION < 25
UProperty *FoundProperty = object->GetClass()->FindPropertyByName(PropertyName);
#else
FProperty *FoundProperty = object->GetClass()->FindPropertyByName(PropertyName);
#endif
if(FoundProperty)
{
void *PropertyPtr = FoundProperty->ContainerPtrToValuePtr<void>(object);
check(PropertyPtr);
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION < 25
if(UNumericProperty *pIntProp = Cast<UNumericProperty>(FoundProperty))
#else
if(FNumericProperty *pIntProp = CastField<FNumericProperty>(FoundProperty))
#endif
{
if(Value.IsNumeric())
{
pIntProp->SetNumericPropertyValueFromString(PropertyPtr, *Value);
return true;
}
else
{
if(PrintWarnings)
{
UE_LOG(LogRyRuntime, Warning, TEXT("SetObjectPropertyValue: Property named '%s' is numeric but the Value string is not"), *PropertyName.ToString());
}
return false;
}
}
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION < 25
else if(UBoolProperty *pBoolProp = Cast<UBoolProperty>(FoundProperty))
#else
else if(FBoolProperty *pBoolProp = CastField<FBoolProperty>(FoundProperty))
#endif
{
pBoolProp->SetPropertyValue(PropertyPtr, FCString::ToBool(*Value));
return true;
}
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION < 25
else if(UStructProperty* StructProperty = Cast<UStructProperty>(FoundProperty))
#else
else if(FStructProperty* StructProperty = CastField<FStructProperty>(FoundProperty))
#endif
{
FName StructType = StructProperty->Struct->GetFName();
if(StructType == NAME_LinearColor)
{
FLinearColor *pCol = (FLinearColor*)PropertyPtr;
return pCol->InitFromString(Value);
}
else if(StructType == NAME_Color)
{
FColor *pCol = (FColor*)PropertyPtr;
return pCol->InitFromString(Value);
}
else if(StructType == NAME_Vector)
{
FVector *pVec = (FVector*)PropertyPtr;
return pVec->InitFromString(Value);
}
else if(StructType == NAME_Rotator)
{
FRotator *pRot = (FRotator*)PropertyPtr;
return pRot->InitFromString(Value);
}
else if(StructType == NAME_Transform)
{
FTransform *pTrans = (FTransform*)PropertyPtr;
return pTrans->InitFromString(Value);
}
}
if(PrintWarnings)
{
UE_LOG(LogRyRuntime, Warning, TEXT("SetObjectPropertyValue: Unsupported property named '%s'"), *PropertyName.ToString());
}
}
else if(PrintWarnings)
{
UE_LOG(LogRyRuntime, Warning, TEXT("SetObjectPropertyValue: Unable to find property in object named '%s'"), *PropertyName.ToString());
}
return false;
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::ObjectHasFlag_ArchetypeObject(UObject* object)
{
return object && object->HasAnyFlags(RF_ArchetypeObject);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::ObjectHasFlag_ClassDefaultObject(UObject* object)
{
return object && object->HasAnyFlags(RF_ClassDefaultObject);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::ObjectHasFlag_BeginDestroyed(UObject* object)
{
return object && object->HasAnyFlags(RF_BeginDestroyed);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::ObjectHasFlag_FinishDestroyed(UObject* object)
{
return object && object->HasAnyFlags(RF_FinishDestroyed);
}
//---------------------------------------------------------------------------------------------------------------------
/**
*/
bool URyRuntimeObjectHelpers::ObjectHasFlag_WasLoaded(UObject* object)
{
return object && object->HasAnyFlags(RF_WasLoaded);
}
| 412 | 0.941292 | 1 | 0.941292 | game-dev | MEDIA | 0.61145 | game-dev | 0.869582 | 1 | 0.869582 |
chsami/Microbot-Hub | 2,940 | src/main/java/net/runelite/client/plugins/microbot/aiofighter/combat/DodgeProjectileScript.java | package net.runelite.client.plugins.microbot.aiofighter.combat;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Projectile;
import net.runelite.api.coords.WorldPoint;
import net.runelite.client.plugins.microbot.Microbot;
import net.runelite.client.plugins.microbot.Script;
import net.runelite.client.plugins.microbot.aiofighter.AIOFighterConfig;
import net.runelite.client.plugins.microbot.util.tile.Rs2Tile;
import net.runelite.client.plugins.microbot.util.walker.Rs2Walker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
@Slf4j
public class DodgeProjectileScript extends Script {
public final ArrayList<Projectile> projectiles = new ArrayList<>();
public boolean run(AIOFighterConfig config) {
mainScheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
if (!config.dodgeProjectiles()) return;
int cycle = Microbot.getClient().getGameCycle();
projectiles.removeIf(projectile -> cycle >= projectile.getEndCycle());
if (projectiles.isEmpty()) return;
WorldPoint[] dangerousPoints = projectiles.stream().map(Projectile::getTargetPoint).toArray(WorldPoint[]::new);
WorldPoint playerLocation = Microbot.getClient().getLocalPlayer().getWorldLocation();
if (projectiles.stream().anyMatch(p -> p.getTargetPoint().distanceTo(playerLocation) < 2)) {
WorldPoint safePoint = calculateSafePoint(playerLocation, dangerousPoints);
Rs2Walker.walkFastCanvas(safePoint);
}
}, 0, 200, TimeUnit.MILLISECONDS);
return true;
}
private WorldPoint calculateSafePoint(WorldPoint playerLocation, WorldPoint[] dangerousPoints) {
// Define the search radius around the player
int searchRadius = 5;
int minDistance = Integer.MAX_VALUE;
WorldPoint bestPoint = playerLocation;
// Search in a square area around the player
for (int dx = -searchRadius; dx <= searchRadius; dx++) {
for (int dy = -searchRadius; dy <= searchRadius; dy++) {
WorldPoint candidate = playerLocation.dx(dx).dy(dy);
// Check if this point is safe (at least 2 tiles away from all dangerous points)
if (Arrays.stream(dangerousPoints).allMatch(p -> p.distanceTo(candidate) >= 2)) {
// If the point is safe, check if it's closer to the player than our current best
int distanceToPlayer = candidate.distanceTo(playerLocation);
if (distanceToPlayer < minDistance && Rs2Tile.isTileReachable(candidate)) {
minDistance = distanceToPlayer;
bestPoint = candidate;
}
}
}
}
return bestPoint;
}
@Override
public void shutdown() {
super.shutdown();
}
}
| 412 | 0.920899 | 1 | 0.920899 | game-dev | MEDIA | 0.881134 | game-dev | 0.896356 | 1 | 0.896356 |
gomint/gomint | 5,847 | gomint-server/src/main/java/io/gomint/server/world/block/Trapdoor.java | /*
* Copyright (c) 2020 Gomint team
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.server.world.block;
import io.gomint.inventory.item.ItemStack;
import io.gomint.math.AxisAlignedBB;
import io.gomint.math.Location;
import io.gomint.math.Vector;
import io.gomint.server.entity.Entity;
import io.gomint.server.entity.EntityLiving;
import io.gomint.server.world.block.state.BooleanBlockState;
import io.gomint.server.world.block.state.DirectionBlockState;
import io.gomint.server.world.block.state.HalfBlockState;
import io.gomint.world.block.BlockTrapdoor;
import io.gomint.world.block.data.Direction;
import io.gomint.world.block.data.Facing;
import java.util.Collections;
import java.util.List;
public abstract class Trapdoor<B> extends Block implements BlockTrapdoor<B> {
private static final DirectionBlockState DIRECTION = new DirectionBlockState(() -> new String[]{"direction"}) {
@Override
protected void calculateValueFromState(Block block, Direction state) {
switch (state) {
case NORTH:
this.value(block, 0);
break;
case EAST:
this.value(block, 2);
break;
case WEST:
this.value(block, 3);
break;
case SOUTH:
default:
this.value(block, 1);
break;
}
}
@Override
public Direction state(Block block) {
switch (this.value(block)) {
case 3:
default:
return Direction.WEST;
case 0:
return Direction.NORTH;
case 1:
return Direction.SOUTH;
case 2:
return Direction.EAST;
}
}
};
private static final BooleanBlockState TOP = new HalfBlockState(() -> new String[]{"upside_down_bit"});
private static final BooleanBlockState OPEN = new BooleanBlockState(() -> new String[]{"open_bit"});
@Override
public boolean open() {
return OPEN.state(this);
}
@Override
public B toggle() {
OPEN.state(this, !this.open());
return (B) this;
}
@Override
public boolean interact(Entity<?> entity, Facing face, Vector facePos, ItemStack<?> item) {
toggle();
return true;
}
@Override
public boolean beforePlacement(EntityLiving<?> entity, ItemStack<?> item, Facing face, Location location, Vector clickVector) {
DIRECTION.detectFromPlacement(this, entity, item, face, clickVector);
OPEN.detectFromPlacement(this, entity, item, face, clickVector);
TOP.detectFromPlacement(this,entity,item,face,clickVector);
return super.beforePlacement(entity, item, face, location, clickVector);
}
@Override
public List<AxisAlignedBB> boundingBoxes() {
float defaultHeight = 0.1875f;
// Basis box
AxisAlignedBB bb;
if (TOP.state(this)) {
// Top closed box
bb = new AxisAlignedBB(
this.location.x(),
this.location.y() + 1 - defaultHeight,
this.location.z(),
this.location.x() + 1,
this.location.y() + 1,
this.location.z() + 1
);
} else {
// Bottom closed box
bb = new AxisAlignedBB(
this.location.x(),
this.location.y(),
this.location.z(),
this.location.x() + 1,
this.location.y() + defaultHeight,
this.location.z() + 1
);
}
// Check for open state
if (OPEN.state(this)) {
switch (DIRECTION.state(this)) {
case NORTH:
bb.bounds(
this.location.x(),
this.location.y(),
this.location.z() + 1 - defaultHeight,
this.location.x() + 1,
this.location.y() + 1,
this.location.z() + 1
);
break;
case SOUTH:
bb.bounds(
this.location.x(),
this.location.y(),
this.location.z(),
this.location.x() + 1,
this.location.y() + 1,
this.location.z() + defaultHeight
);
break;
case WEST:
bb.bounds(
this.location.x() + 1 - defaultHeight,
this.location.y(),
this.location.z(),
this.location.x() + 1,
this.location.y() + 1,
this.location.z() + 1
);
break;
case EAST:
bb.bounds(
this.location.x(),
this.location.y(),
this.location.z(),
this.location.x() + defaultHeight,
this.location.y() + 1,
this.location.z() + 1
);
break;
}
}
return Collections.singletonList(bb);
}
@Override
public B direction(Direction direction) {
DIRECTION.state(this, direction);
return (B) this;
}
@Override
public Direction direction() {
return DIRECTION.state(this);
}
}
| 412 | 0.973942 | 1 | 0.973942 | game-dev | MEDIA | 0.498757 | game-dev | 0.983397 | 1 | 0.983397 |
mastercomfig/tf2-patches-old | 2,892 | src/game/server/hl2/ai_behavior_holster.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "ai_behavior_holster.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DATADESC( CAI_HolsterBehavior )
DEFINE_FIELD( m_bWeaponOut, FIELD_BOOLEAN ),
END_DATADESC();
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CAI_HolsterBehavior::CAI_HolsterBehavior()
{
// m_AssaultCue = CUE_NO_ASSAULT;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CAI_HolsterBehavior::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_RANGE_ATTACK1:
BaseClass::StartTask( pTask );
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CAI_HolsterBehavior::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_RANGE_ATTACK1:
BaseClass::RunTask( pTask );
break;
default:
BaseClass::RunTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_HolsterBehavior::CanSelectSchedule()
{
if ( !GetOuter()->IsInterruptable() )
return false;
if ( GetOuter()->HasCondition( COND_RECEIVED_ORDERS ) )
return false;
if ( GetEnemy() )
{
// make sure weapon is out
if (!m_bWeaponOut)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CAI_HolsterBehavior::SelectSchedule()
{
return BaseClass::SelectSchedule();
}
AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( CAI_HolsterBehavior )
DECLARE_TASK( TASK_HOLSTER_WEAPON )
DECLARE_TASK( TASK_DRAW_WEAPON )
// DECLARE_CONDITION( COND_ )
//=========================================================
//=========================================================
DEFINE_SCHEDULE
(
SCHED_HOLSTER_WEAPON,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_HOLSTER_WEAPON 0"
" "
" Interrupts"
)
DEFINE_SCHEDULE
(
SCHED_DRAW_WEAPON,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_DRAW_WEAPON 0"
" "
" Interrupts"
)
AI_END_CUSTOM_SCHEDULE_PROVIDER()
| 412 | 0.958818 | 1 | 0.958818 | game-dev | MEDIA | 0.768135 | game-dev | 0.922854 | 1 | 0.922854 |
mcmonkeyprojects/Sentinel | 9,225 | src/main/java/org/mcmonkey/sentinel/commands/SentinelCommand.java | package org.mcmonkey.sentinel.commands;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.command.CommandContext;
import net.citizensnpcs.api.command.CommandManager;
import net.citizensnpcs.api.command.Injector;
import net.citizensnpcs.api.command.Requirements;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.trait.Owner;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.*;
import org.mcmonkey.sentinel.SentinelPlugin;
import org.mcmonkey.sentinel.SentinelTrait;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
/**
* Helper class for the Sentinel command.
*/
public class SentinelCommand implements CommandExecutor, TabCompleter {
/**
* Output string representing a message color.
*/
public static final String colorBasic = ChatColor.YELLOW.toString(), colorBad = ChatColor.RED.toString(), colorEmphasis = ChatColor.AQUA.toString();
/**
* Output string representing a success prefix.
*/
public static final String prefixGood = ChatColor.DARK_GREEN + "[Sentinel] " + colorBasic;
/**
* Output string representing a failure prefix.
*/
public static final String prefixBad = ChatColor.DARK_GREEN + "[Sentinel] " + colorBad;
/**
* The "/sentinel" command manager.
*/
public CommandManager manager;
/**
* The main instance of this class.
*/
public static SentinelCommand instance;
/**
* Prepares the command handling system.
*/
public void buildCommandHandler(PluginCommand command) {
instance = this;
manager = new CommandManager();
manager.setInjector(new Injector());
grabCommandField();
manager.register(SentinelAttackCommands.class);
manager.register(SentinelChaseCommands.class);
manager.register(SentinelGreetingCommands.class);
manager.register(SentinelHealthCommands.class);
manager.register(SentinelInfoCommands.class);
manager.register(SentinelIntelligenceCommands.class);
manager.register(SentinelTargetCommands.class);
command.setExecutor(this);
command.setTabCompleter(this);
}
private static Field commandInfoMethodField;
private void grabCommandField() {
try {
Field field = CommandManager.CommandInfo.class.getDeclaredField("method");
field.setAccessible(true);
commandInfoMethodField = field;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean isSentinelRequired(String command, String modifier) {
CommandManager.CommandInfo info = manager.getCommand(command, modifier);
if (info == null) {
return false;
}
try {
Method method = (Method) commandInfoMethodField.get(info);
Requirements[] req = method.getDeclaredAnnotationsByType(Requirements.class);
if (req == null || req.length == 0) {
return false;
}
for (Class<? extends Trait> traitClass : req[0].traits()) {
if (traitClass.equals(SentinelTrait.class)) {
return true;
}
}
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
return false;
}
/**
* Handles a player or server command.
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
String modifier = args.length > 0 ? args[0] : "";
if (!manager.hasCommand(command, modifier) && !modifier.isEmpty()) {
String closest = manager.getClosestCommandModifier(command.getName(), modifier);
if (!closest.isEmpty()) {
sender.sendMessage(prefixBad + "Unknown command. Did you mean:");
sender.sendMessage(prefixGood + " /" + command.getName() + " " + closest);
}
else {
sender.sendMessage(prefixBad + "Unknown command.");
}
return true;
}
NPC selected = CitizensAPI.getDefaultNPCSelector().getSelected(sender);
SentinelTrait sentinel = null;
CommandContext context = new CommandContext(sender, args);
if (context.hasValueFlag("id") && sender.hasPermission("npc.select")) {
try {
selected = CitizensAPI.getNPCRegistry().getById(context.getFlagInteger("id"));
}
catch (NumberFormatException ex) {
sender.sendMessage(prefixBad + "ID input is invalid (not an integer)!");
return true;
}
}
if (selected != null) {
sentinel = selected.getTraitNullable(SentinelTrait.class);
}
Object[] methodArgs;
if (isSentinelRequired(command.getName(), modifier)) {
if (sentinel == null) {
if (selected == null) {
sender.sendMessage(prefixBad + "Must have a Sentinel NPC selected!");
}
else {
sender.sendMessage(prefixBad + "Selected NPC is not a Sentinel! Use /trait sentinel to ensure an NPC becomes a Sentinel.");
}
return true;
}
if (!selected.getOrAddTrait(Owner.class).isOwnedBy(sender) && !sender.hasPermission("citizens.admin")) {
sender.sendMessage(prefixBad + "You do not own this NPC (and you are not an admin).");
return true;
}
methodArgs = new Object[]{sender, sentinel};
}
else {
methodArgs = new Object[]{ sender };
}
return manager.executeSafe(command, args, sender, methodArgs);
}
private static List<String> filterForArg(Collection<String> output, String arg1) {
String low = arg1.toLowerCase();
return output.stream().filter(s -> s.startsWith(low)).collect(Collectors.toList());
}
public static HashSet<String> addTargetTabCompletions = new HashSet<>();
public static HashSet<String> itemPrefixes = new HashSet<>(Arrays.asList("helditem", "offhand", "equipped", "in_inventory"));
public static List<String> materialNames = Arrays.stream(Material.values()).map(m -> m.name().toLowerCase()).collect(Collectors.toList());
static {
addTargetTabCompletions.addAll(Arrays.asList("player:", "npc:", "entityname:", "group:"));
addTargetTabCompletions.addAll(Arrays.asList("helditem:", "offhand:", "equipped:", "in_inventory:"));
addTargetTabCompletions.addAll(Arrays.asList("status:angry", "status:passive"));
addTargetTabCompletions.addAll(Arrays.asList("event:", "event:pvp", "event:pve", "event:pvnpc", "event:pvsentinel", "event:eve", "event:pv:", "event:ev:", "event:npcvnpc", "event:guarded_fight", "event:message:"));
addTargetTabCompletions.addAll(SentinelPlugin.targetOptions.keySet().stream().map(String::toLowerCase).collect(Collectors.toList()));
}
/**
* Handles tab completion for a player or server command.
*/
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
if (s.equals("sentinel") && strings.length == 2) {
NPC npc = CitizensAPI.getDefaultNPCSelector().getSelected(commandSender);
if (npc != null && npc.hasTrait(SentinelTrait.class)) {
SentinelTrait sentinel = npc.getOrAddTrait(SentinelTrait.class);
switch (strings[0].toLowerCase()) {
case "addtarget":
case "addignore":
case "addavoid":
String low = strings[1].toLowerCase();
int colon = low.indexOf(':');
if (colon != -1 && colon + 1 < low.length()) {
String prefix = low.substring(0, colon);
if (itemPrefixes.contains(prefix)) {
List<String> materials = filterForArg(materialNames, low.substring(colon + 1));
materials.add("lore:");
materials.add("name:");
return filterForArg(materials.stream().map(m -> prefix + ":" + m).collect(Collectors.toList()), low);
}
}
return filterForArg(addTargetTabCompletions, low);
case "removetarget":
return filterForArg(sentinel.allTargets.getTargetRemovableStrings(), strings[1]);
case "removeignore":
return filterForArg(sentinel.allIgnores.getTargetRemovableStrings(), strings[1]);
case "removeavoid":
return filterForArg(sentinel.allAvoids.getTargetRemovableStrings(), strings[1]);
}
}
}
return manager.onTabComplete(commandSender, command, s, strings);
}
}
| 412 | 0.934625 | 1 | 0.934625 | game-dev | MEDIA | 0.802703 | game-dev | 0.959761 | 1 | 0.959761 |
juce-framework/JUCE | 13,041 | modules/juce_box2d/box2d/Dynamics/Joints/b2RevoluteJoint.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2RevoluteJoint.h"
#include "../b2Body.h"
#include "../b2TimeStep.h"
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
}
b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_referenceAngle = def->referenceAngle;
m_impulse.SetZero();
m_motorImpulse = 0.0f;
m_lowerAngle = def->lowerAngle;
m_upperAngle = def->upperAngle;
m_maxMotorTorque = def->maxMotorTorque;
m_motorSpeed = def->motorSpeed;
m_enableLimit = def->enableLimit;
m_enableMotor = def->enableMotor;
m_limitState = e_inactiveLimit;
}
void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
bool fixedRotation = (iA + iB == 0.0f);
m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB;
m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB;
m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB;
m_mass.ex.y = m_mass.ey.x;
m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB;
m_mass.ez.y = m_rA.x * iA + m_rB.x * iB;
m_mass.ex.z = m_mass.ez.x;
m_mass.ey.z = m_mass.ez.y;
m_mass.ez.z = iA + iB;
m_motorMass = iA + iB;
if (m_motorMass > 0.0f)
{
m_motorMass = 1.0f / m_motorMass;
}
if (m_enableMotor == false || fixedRotation)
{
m_motorImpulse = 0.0f;
}
if (m_enableLimit && fixedRotation == false)
{
float32 jointAngle = aB - aA - m_referenceAngle;
if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop)
{
m_limitState = e_equalLimits;
}
else if (jointAngle <= m_lowerAngle)
{
if (m_limitState != e_atLowerLimit)
{
m_impulse.z = 0.0f;
}
m_limitState = e_atLowerLimit;
}
else if (jointAngle >= m_upperAngle)
{
if (m_limitState != e_atUpperLimit)
{
m_impulse.z = 0.0f;
}
m_limitState = e_atUpperLimit;
}
else
{
m_limitState = e_inactiveLimit;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = e_inactiveLimit;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_impulse *= data.step.dtRatio;
m_motorImpulse *= data.step.dtRatio;
b2Vec2 P(m_impulse.x, m_impulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z);
}
else
{
m_impulse.SetZero();
m_motorImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
bool fixedRotation = (iA + iB == 0.0f);
// Solve motor constraint.
if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false)
{
float32 Cdot = wB - wA - m_motorSpeed;
float32 impulse = -m_motorMass * Cdot;
float32 oldImpulse = m_motorImpulse;
float32 maxImpulse = data.step.dt * m_maxMotorTorque;
m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve limit constraint.
if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
{
b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
float32 Cdot2 = wB - wA;
b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
b2Vec3 impulse = -m_mass.Solve33(Cdot);
if (m_limitState == e_equalLimits)
{
m_impulse += impulse;
}
else if (m_limitState == e_atLowerLimit)
{
float32 newImpulse = m_impulse.z + impulse.z;
if (newImpulse < 0.0f)
{
b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
b2Vec2 reduced = m_mass.Solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -m_impulse.z;
m_impulse.x += reduced.x;
m_impulse.y += reduced.y;
m_impulse.z = 0.0f;
}
else
{
m_impulse += impulse;
}
}
else if (m_limitState == e_atUpperLimit)
{
float32 newImpulse = m_impulse.z + impulse.z;
if (newImpulse > 0.0f)
{
b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
b2Vec2 reduced = m_mass.Solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -m_impulse.z;
m_impulse.x += reduced.x;
m_impulse.y += reduced.y;
m_impulse.z = 0.0f;
}
else
{
m_impulse += impulse;
}
}
b2Vec2 P(impulse.x, impulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + impulse.z);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + impulse.z);
}
else
{
// Solve point-to-point constraint
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = m_mass.Solve22(-Cdot);
m_impulse.x += impulse.x;
m_impulse.y += impulse.y;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data)
{
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Rot qA(aA), qB(aB);
float32 angularError = 0.0f;
float32 positionError = 0.0f;
bool fixedRotation = (m_invIA + m_invIB == 0.0f);
// Solve angular limit constraint.
if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
{
float32 angle = aB - aA - m_referenceAngle;
float32 limitImpulse = 0.0f;
if (m_limitState == e_equalLimits)
{
// Prevent large angular corrections
float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection);
limitImpulse = -m_motorMass * C;
angularError = b2Abs(C);
}
else if (m_limitState == e_atLowerLimit)
{
float32 C = angle - m_lowerAngle;
angularError = -C;
// Prevent large angular corrections and allow some slop.
C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f);
limitImpulse = -m_motorMass * C;
}
else if (m_limitState == e_atUpperLimit)
{
float32 C = angle - m_upperAngle;
angularError = C;
// Prevent large angular corrections and allow some slop.
C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection);
limitImpulse = -m_motorMass * C;
}
aA -= m_invIA * limitImpulse;
aB += m_invIB * limitImpulse;
}
// Solve point-to-point constraint.
{
qA.Set(aA);
qB.Set(aB);
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
b2Vec2 C = cB + rB - cA - rA;
positionError = C.Length();
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
b2Vec2 impulse = -K.Solve(C);
cA -= mA * impulse;
aA -= iA * b2Cross(rA, impulse);
cB += mB * impulse;
aB += iB * b2Cross(rB, impulse);
}
data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
}
b2Vec2 b2RevoluteJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2RevoluteJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const
{
b2Vec2 P(m_impulse.x, m_impulse.y);
return inv_dt * P;
}
float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_impulse.z;
}
float32 b2RevoluteJoint::GetJointAngle() const
{
b2Body* bA = m_bodyA;
b2Body* bB = m_bodyB;
return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle;
}
float32 b2RevoluteJoint::GetJointSpeed() const
{
b2Body* bA = m_bodyA;
b2Body* bB = m_bodyB;
return bB->m_angularVelocity - bA->m_angularVelocity;
}
bool b2RevoluteJoint::IsMotorEnabled() const
{
return m_enableMotor;
}
void b2RevoluteJoint::EnableMotor(bool flag)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableMotor = flag;
}
float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const
{
return inv_dt * m_motorImpulse;
}
void b2RevoluteJoint::SetMotorSpeed(float32 speed)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_motorSpeed = speed;
}
void b2RevoluteJoint::SetMaxMotorTorque(float32 torque)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_maxMotorTorque = torque;
}
bool b2RevoluteJoint::IsLimitEnabled() const
{
return m_enableLimit;
}
void b2RevoluteJoint::EnableLimit(bool flag)
{
if (flag != m_enableLimit)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableLimit = flag;
m_impulse.z = 0.0f;
}
}
float32 b2RevoluteJoint::GetLowerLimit() const
{
return m_lowerAngle;
}
float32 b2RevoluteJoint::GetUpperLimit() const
{
return m_upperAngle;
}
void b2RevoluteJoint::SetLimits(float32 lower, float32 upper)
{
b2Assert(lower <= upper);
if (lower != m_lowerAngle || upper != m_upperAngle)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_impulse.z = 0.0f;
m_lowerAngle = lower;
m_upperAngle = upper;
}
}
void b2RevoluteJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2RevoluteJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle);
b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit);
b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle);
b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle);
b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor);
b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 412 | 0.973218 | 1 | 0.973218 | game-dev | MEDIA | 0.9253 | game-dev | 0.989853 | 1 | 0.989853 |
SinlessDevil/TestTaskArmageddonica | 7,495 | Assets/Plugins/Zenject/Source/Factories/Pooling/MemoryPoolBase.cs | using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class PoolExceededFixedSizeException : Exception
{
public PoolExceededFixedSizeException(string errorMessage)
: base(errorMessage)
{
}
}
[Serializable]
public class MemoryPoolSettings
{
public int InitialSize;
public int MaxSize;
public PoolExpandMethods ExpandMethod;
public MemoryPoolSettings()
{
InitialSize = 0;
MaxSize = int.MaxValue;
ExpandMethod = PoolExpandMethods.OneAtATime;
}
public MemoryPoolSettings(int initialSize, int maxSize, PoolExpandMethods expandMethod)
{
InitialSize = initialSize;
MaxSize = maxSize;
ExpandMethod = expandMethod;
}
public static readonly MemoryPoolSettings Default = new MemoryPoolSettings();
}
[ZenjectAllowDuringValidation]
public class MemoryPoolBase<TContract> : IValidatable, IMemoryPool, IDisposable
{
Stack<TContract> _inactiveItems;
IFactory<TContract> _factory;
MemoryPoolSettings _settings;
DiContainer _container;
int _activeCount;
[Inject]
void Construct(
IFactory<TContract> factory,
DiContainer container,
[InjectOptional]
MemoryPoolSettings settings)
{
_settings = settings ?? MemoryPoolSettings.Default;
_factory = factory;
_container = container;
_inactiveItems = new Stack<TContract>(_settings.InitialSize);
if (!container.IsValidating)
{
for (int i = 0; i < _settings.InitialSize; i++)
{
_inactiveItems.Push(AllocNew());
}
}
#if UNITY_EDITOR
StaticMemoryPoolRegistry.Add(this);
#endif
}
protected DiContainer Container
{
get { return _container; }
}
public IEnumerable<TContract> InactiveItems
{
get { return _inactiveItems; }
}
public int NumTotal
{
get { return NumInactive + NumActive; }
}
public int NumInactive
{
get { return _inactiveItems.Count; }
}
public int NumActive
{
get { return _activeCount; }
}
public Type ItemType
{
get { return typeof(TContract); }
}
public void Dispose()
{
#if UNITY_EDITOR
StaticMemoryPoolRegistry.Remove(this);
#endif
}
void IMemoryPool.Despawn(object item)
{
Despawn((TContract)item);
}
public void Despawn(TContract item)
{
Assert.That(!_inactiveItems.Contains(item),
"Tried to return an item to pool {0} twice", GetType());
_activeCount--;
_inactiveItems.Push(item);
#if ZEN_INTERNAL_PROFILING
using (ProfileTimers.CreateTimedBlock("User Code"))
#endif
#if UNITY_EDITOR
using (ProfileBlock.Start("{0}.OnDespawned", GetType()))
#endif
{
OnDespawned(item);
}
if (_inactiveItems.Count > _settings.MaxSize)
{
Resize(_settings.MaxSize);
}
}
TContract AllocNew()
{
try
{
var item = _factory.Create();
if (!_container.IsValidating)
{
Assert.IsNotNull(item, "Factory '{0}' returned null value when creating via {1}!", _factory.GetType(), GetType());
OnCreated(item);
}
return item;
}
catch (Exception e)
{
throw new ZenjectException(
"Error during construction of type '{0}' via {1}.Create method!".Fmt(
typeof(TContract), GetType()), e);
}
}
void IValidatable.Validate()
{
try
{
_factory.Create();
}
catch (Exception e)
{
throw new ZenjectException(
"Validation for factory '{0}' failed".Fmt(GetType()), e);
}
}
public void Clear()
{
Resize(0);
}
public void ShrinkBy(int numToRemove)
{
Resize(_inactiveItems.Count - numToRemove);
}
public void ExpandBy(int numToAdd)
{
Resize(_inactiveItems.Count + numToAdd);
}
protected TContract GetInternal()
{
if (_inactiveItems.Count == 0)
{
ExpandPool();
Assert.That(!_inactiveItems.IsEmpty());
}
var item = _inactiveItems.Pop();
_activeCount++;
OnSpawned(item);
return item;
}
public void Resize(int desiredPoolSize)
{
if (_inactiveItems.Count == desiredPoolSize)
{
return;
}
if (_settings.ExpandMethod == PoolExpandMethods.Disabled)
{
throw new PoolExceededFixedSizeException(
"Pool factory '{0}' attempted resize but pool set to fixed size of '{1}'!"
.Fmt(GetType(), _inactiveItems.Count));
}
Assert.That(desiredPoolSize >= 0, "Attempted to resize the pool to a negative amount");
while (_inactiveItems.Count > desiredPoolSize)
{
OnDestroyed(_inactiveItems.Pop());
}
while (desiredPoolSize > _inactiveItems.Count)
{
_inactiveItems.Push(AllocNew());
}
Assert.IsEqual(_inactiveItems.Count, desiredPoolSize);
}
void ExpandPool()
{
switch (_settings.ExpandMethod)
{
case PoolExpandMethods.Disabled:
{
throw new PoolExceededFixedSizeException(
"Pool factory '{0}' exceeded its fixed size of '{1}'!"
.Fmt(GetType(), _inactiveItems.Count));
}
case PoolExpandMethods.OneAtATime:
{
ExpandBy(1);
break;
}
case PoolExpandMethods.Double:
{
if (NumTotal == 0)
{
ExpandBy(1);
}
else
{
ExpandBy(NumTotal);
}
break;
}
default:
{
throw Assert.CreateException();
}
}
}
protected virtual void OnDespawned(TContract item)
{
// Optional
}
protected virtual void OnSpawned(TContract item)
{
// Optional
}
protected virtual void OnCreated(TContract item)
{
// Optional
}
protected virtual void OnDestroyed(TContract item)
{
// Optional
}
}
}
| 412 | 0.971379 | 1 | 0.971379 | game-dev | MEDIA | 0.81105 | game-dev | 0.992534 | 1 | 0.992534 |
TeamHypersomnia/Hypersomnia | 11,310 | src/game/stateless_systems/movement_path_system.cpp | #include <cstddef>
#include "augs/misc/randomization.h"
#include "augs/math/steering.h"
#include "augs/math/make_rect_points.h"
#include "game/cosmos/cosmos.h"
#include "game/cosmos/entity_handle.h"
#include "game/cosmos/logic_step.h"
#include "game/cosmos/for_each_entity.h"
#include "game/messages/interpolation_correction_request.h"
#include "game/messages/queue_deletion.h"
#include "game/messages/will_soon_be_deleted.h"
#include "game/detail/visible_entities.h"
#include "game/stateless_systems/movement_path_system.h"
#include "game/inferred_caches/tree_of_npo_cache.hpp"
#include "game/inferred_caches/organism_cache.hpp"
#include "game/inferred_caches/organism_cache_query.hpp"
#include "game/detail/get_hovered_world_entity.h"
void movement_path_system::advance_paths(const logic_step step) const {
if (!step.get_settings().simulate_decorative_organisms) {
return;
}
auto& cosm = step.get_cosmos();
const auto delta = step.get_delta();
auto step_rng = randomization(cosm.get_total_steps_passed());
auto& grids = cosm.get_solvable_inferred({}).organisms;
static const auto fov_half_degrees = real32((360 - 90) / 2);
static const auto fov_half_degrees_cos = repro::cos(fov_half_degrees);
cosm.for_each_having<components::movement_path>(
[&](const auto& subject) {
const auto& movement_path_def = subject.template get<invariants::movement_path>();
const auto& rotation_speed = movement_path_def.continuous_rotation_speed;
if (augs::is_nonzero(rotation_speed)) {
auto& transform = subject.template get<components::transform>();
transform.rotation += rotation_speed * delta.in_seconds();
}
if (movement_path_def.organism_wandering.is_enabled) {
auto& movement_path = subject.template get<components::movement_path>();
const auto& transform = subject.template get<components::transform>();
const auto& pos = transform.pos;
const auto tip_pos = subject.get_logical_tip(transform);
const auto& def = movement_path_def.organism_wandering.value;
const auto origin = cosm[movement_path.origin];
if (origin.dead()) {
movement_path.origin = ::get_hovered_world_entity(
cosm,
transform.pos,
[&](const auto area_id) {
if (const auto area_entity = cosm[area_id]) {
if (const auto area = area_entity.template find<invariants::area_marker>()) {
if (area->type == area_marker_type::ORGANISM_AREA) {
return true;
}
}
}
return false;
},
render_layer_filter::whitelist(render_layer::AREA_MARKERS),
accuracy_type::EXACT,
{ { tree_of_npo_type::RENDERABLES } }
);
// LOG("New origin for %x: %x", subject, cosm[movement_path.origin]);
/*
Return so that we notice a frozen organism
if for some reason origin gets reset every frame.
*/
return;
}
const auto global_time = cosm.get_total_seconds_passed() + real32(subject.get_id().raw.indirection_index);
const auto global_time_sine = repro::sin(real32(global_time * 2));
const auto max_speed_boost = def.sine_speed_boost;
const auto boost_mult = static_cast<real32>(global_time_sine * global_time_sine);
const auto speed_boost = boost_mult * max_speed_boost;
const auto max_avoidance_speed = 20 + speed_boost / 2;
const auto max_startle_speed = 250 + 4*speed_boost;
const auto max_lighter_startle_speed = 200 + 4*speed_boost;
const auto cohesion_mult = 0.05f;
const auto alignment_mult = 0.08f;
const auto base_speed = def.base_speed;
const auto min_speed = base_speed + speed_boost;
const auto max_speed = base_speed + max_speed_boost;
const auto current_dir = transform.get_direction();
const real32 comfort_zone_radius = movement_path_neighbor_query_radius_v;
const real32 cohesion_zone_radius = 60.f;
const auto current_speed_mult = movement_path.last_speed / max_speed;
const auto wandering_sine = repro::sin(real32(global_time / def.sine_wandering_period * current_speed_mult)) * def.sine_wandering_amplitude * current_speed_mult;
const auto perpendicular_dir = current_dir.perpendicular_cw();
const auto subject_avoidance_rank = def.avoidance_rank;
auto for_each_neighbor_within = [&](const auto radius, auto callback) {
if (!def.enable_flocking) {
return;
}
constexpr auto max_handled_organisms = std::size_t(3);
auto cell_callback = [&](const auto& cell) {
const auto& orgs = cell.organisms;
const auto cnt = std::min(orgs.size(), max_handled_organisms);
for (std::size_t i = 0; i < cnt; ++i) {
const auto org_id = orgs[i];
if (org_id == subject.get_id()) {
/* Don't measure against itself */
continue;
}
const auto typed_neighbor = cosm[org_id];
const auto neighbor_transform = typed_neighbor.get_logic_transform();
const auto neighbor_tip = typed_neighbor.get_logical_tip(neighbor_transform);
const auto offset_dir = (neighbor_tip - tip_pos).normalize();
const auto facing = current_dir.dot(offset_dir);
/*
Facing can be between -1 (180) and 1 (0)
fov_half_degrees_cos = -0.70710...
thus facing must be gequal than fov_half_degrees_cos.
*/
if (facing >= fov_half_degrees_cos) {
callback(typed_neighbor, neighbor_transform, neighbor_tip);
}
}
};
grids.for_each_cell_of_grid(
origin.get_id(),
ltrb::center_and_size(tip_pos, vec2::square(radius * 2)),
cell_callback
);
};
auto velocity = current_dir * min_speed + perpendicular_dir * wandering_sine;
real32 total_startle_applied = 0.f;
auto do_startle = [&](const auto type, const auto damping, const auto steer_mult, const auto max_speed) {
auto& startle = movement_path.startle[type];
//const auto desired_vel = vec2(startle).trim_length(max_speed);
const auto desired_vel = startle;
const auto total_steering = vec2((desired_vel - velocity) * steer_mult * (0.02f + (0.16f * boost_mult))).trim_length(max_speed);
total_startle_applied += total_steering.length() / velocity.length();
velocity += total_steering;
startle.damp(delta.in_seconds(), vec2::square(damping));
};
do_startle(startle_type::LIGHTER, 0.2f, 0.1f, max_lighter_startle_speed);
do_startle(startle_type::IMMEDIATE, 5.f, 1.f, max_startle_speed);
vec2 average_pos;
vec2 average_vel;
unsigned counted_neighbors = 0;
{
auto greatest_avoidance = vec2::zero;
for_each_neighbor_within(comfort_zone_radius, [&](const auto& typed_neighbor, const auto& neighbor_transform, const auto& neighbor_tip) {
const auto& neighbor_wandering_def = typed_neighbor.template get<invariants::movement_path>().organism_wandering;
const auto& neighbor_path = typed_neighbor.template get<components::movement_path>();
if (neighbor_wandering_def.is_enabled) {
if (subject_avoidance_rank > neighbor_wandering_def.value.avoidance_rank) {
/* Don't care about lesser species. */
return;
}
const auto neighbor_vel = neighbor_transform.get_direction() * neighbor_path.last_speed;
const auto avoidance = augs::immediate_avoidance(
tip_pos,
current_dir * movement_path.last_speed,
neighbor_tip,
neighbor_vel,
comfort_zone_radius,
max_avoidance_speed * neighbor_path.last_speed / max_speed
);
greatest_avoidance = std::max(avoidance, greatest_avoidance);
if (typed_neighbor.get_flavour_id() == subject.get_flavour_id()) {
average_pos += neighbor_transform.pos;
average_vel += neighbor_vel;
++counted_neighbors;
}
}
});
velocity += greatest_avoidance;
}
if (counted_neighbors) {
average_pos /= counted_neighbors;
average_vel /= counted_neighbors;
if (cohesion_mult != 0.f) {
const auto total_cohesion = cohesion_mult * total_startle_applied;
velocity += augs::arrive(
velocity,
pos,
average_pos,
velocity.length(),
cohesion_zone_radius
) * total_cohesion;
}
if (alignment_mult != 0.f) {
const auto desired_vel = average_vel.set_length(velocity.length());
const auto steering = desired_vel - velocity;
velocity += steering * alignment_mult;
}
}
const auto total_speed = velocity.length();
const auto bound_avoidance = origin.dispatch([&](const auto& typed_origin) {
if (const auto tr = typed_origin.find_logic_transform()) {
if (const auto size = typed_origin.get_logical_size(); size.area() > 0) {
if (const auto area = typed_origin.template find<invariants::area_marker>()) {
return augs::steer_to_avoid_edges(
velocity,
tip_pos,
augs::make_rect_points(tr->pos, size, tr->rotation),
tr->pos,
60.f,
0.2f
);
}
}
}
return augs::steer_to_avoid_result { vec2::zero, false };
});
auto bound_avoidance_vector = bound_avoidance.seek_vector;
velocity += bound_avoidance_vector;
for (auto& startle : movement_path.startle) {
/*
Decrease startle vectors when nearing the bounds,
to avoid a glitch where fish is conflicted about where to go.
*/
if (startle + bound_avoidance_vector * 6 < startle) {
startle += bound_avoidance_vector * 6;
}
if (bound_avoidance.hit_edge) {
startle = step_rng.randval(0, 1) == 0 ? startle.perpendicular_cw() : startle.perpendicular_ccw();
}
}
movement_path.last_speed = total_speed;
{
const auto speed_mult = total_speed / max_speed;
const auto elapsed_anim_ms = delta.in_milliseconds() * speed_mult;
{
const auto& bubble_effect = def.bubble_effect;
if (bubble_effect.id.is_set()) {
/* Resolve bubbles and bubble intervals */
auto& next_in_ms = movement_path.next_bubble_in_ms;
auto choose_new_interval = [&step_rng, &next_in_ms, &def]() {
const auto interval = def.base_bubble_interval_ms;
const auto h = interval / 1.5f;
next_in_ms = step_rng.randval(interval - h, interval + h);
};
if (next_in_ms < 0.f) {
choose_new_interval();
}
else {
next_in_ms -= elapsed_anim_ms;
if (next_in_ms < 0.f) {
bubble_effect.start(
step,
particle_effect_start_input::orbit_local(subject, transformr(vec2(subject.get_logical_size().x / 3, 0), 0)),
always_predictable_v
);
}
}
}
}
auto& anim_state = subject.template get<components::animation>().state;
anim_state.frame_elapsed_ms += elapsed_anim_ms;
}
{
auto& mut_transform = subject.template get<components::transform>();
mut_transform.rotation = velocity.degrees();//augs::interp(transform.rotation, velocity.degrees(), 50.f * delta.in_seconds());
const auto old_position = transform.pos;
const auto new_position = old_position + velocity * delta.in_seconds();
grids.recalculate_cell_for(origin, subject.get_id(), old_position, new_position);
mut_transform.pos = new_position;
}
}
}
);
}
| 412 | 0.85484 | 1 | 0.85484 | game-dev | MEDIA | 0.763642 | game-dev | 0.833309 | 1 | 0.833309 |
Bozar/godot-4-roguelike-tutorial | 2,903 | autoload/sprite_state.gd | # class_name SpriteState
extends Node2D
var _ref_SpriteCoord: SpriteCoord
var _ref_SpriteTag: SpriteTag
func is_valid_sprite(sprite: Sprite2D) -> bool:
return not sprite.is_queued_for_deletion()
func move_sprite(sprite: Sprite2D, coord: Vector2i,
z_layer: int = sprite.z_index) -> void:
_ref_SpriteCoord.move_sprite(sprite, coord, z_layer)
func get_sprites_by_coord(coord: Vector2i) -> Array:
return _ref_SpriteCoord.get_sprites_by_coord(coord)
func get_sprite_by_coord(main_tag: StringName, coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(main_tag)) -> Sprite2D:
return _ref_SpriteCoord.get_sprite_by_coord(main_tag, coord, z_layer)
func get_main_tag(sprite: Sprite2D) -> StringName:
return _ref_SpriteTag.get_main_tag(sprite)
func get_sub_tag(sprite: Sprite2D) -> StringName:
return _ref_SpriteTag.get_sub_tag(sprite)
func get_sprites_by_tag(main_tag: StringName, sub_tag: StringName) -> Array:
return _ref_SpriteTag.get_sprites_by_tag(main_tag, sub_tag)
func get_sprites_by_main_tag(main_tag: StringName) -> Array:
return _ref_SpriteTag.get_sprites_by_tag(main_tag, "")
func get_sprites_by_sub_tag(sub_tag: StringName) -> Array:
return _ref_SpriteTag.get_sprites_by_tag("", sub_tag)
func get_ground_by_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.GROUND)) -> Sprite2D:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.GROUND, coord, z_layer)
func get_trap_by_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.TRAP)) -> Sprite2D:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.TRAP, coord, z_layer)
func get_building_by_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.BUILDING)) -> Sprite2D:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.BUILDING, coord,
z_layer)
func get_actor_by_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.ACTOR)) -> Sprite2D:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.ACTOR, coord, z_layer)
func has_ground_at_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.GROUND)) -> bool:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.GROUND, coord,
z_layer) != null
func has_trap_at_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.TRAP)) -> bool:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.TRAP, coord, z_layer) \
!= null
func has_building_at_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.BUILDING)) -> bool:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.BUILDING, coord,
z_layer) != null
func has_actor_at_coord(coord: Vector2i,
z_layer: int = ZLayer.get_z_layer(MainTag.ACTOR)) -> bool:
return _ref_SpriteCoord.get_sprite_by_coord(MainTag.ACTOR, coord, z_layer) \
!= null
| 412 | 0.504324 | 1 | 0.504324 | game-dev | MEDIA | 0.801857 | game-dev | 0.575768 | 1 | 0.575768 |
PraxTube/tsumi | 6,476 | src/ui/dialogue/typewriter.rs | use std::str::FromStr;
use unicode_segmentation::UnicodeSegmentation;
use bevy::prelude::*;
use bevy::utils::Instant;
use bevy_yarnspinner::{events::*, prelude::*};
use crate::npc::NpcDialogue;
use crate::utils::DebugActive;
use crate::{GameAssets, GameState};
use super::audio::PlayBlipEvent;
use super::spawn::{create_dialogue_text, DialogueContent, DialogueContinueNode};
use super::DialogueViewSystemSet;
// Write dialogue instantly, for going through dialogue fast.
const DEBUG_SPEED: f32 = 1000.0;
// The average speed over all people.
// It's used to calculate the multiplier of the pauses caused by punctuation.
const AVERAGE_SPEED: f32 = 20.0;
#[derive(Event)]
pub struct TypewriterFinished;
#[derive(Resource)]
pub struct Typewriter {
pub character_name: Option<String>,
pub current_text: String,
pub graphemes_left: Vec<String>,
elapsed: f32,
start: Instant,
last_finished: bool,
current_speed: f32,
}
impl Default for Typewriter {
fn default() -> Self {
Self {
character_name: default(),
current_text: default(),
graphemes_left: default(),
elapsed: default(),
start: Instant::now(),
last_finished: default(),
// We set this high so we can see when things go wrong.
// The speed in game should never be this number!
current_speed: 100.0,
}
}
}
impl Typewriter {
pub fn set_line(&mut self, line: &LocalizedLine) {
*self = Self {
character_name: line.character_name().map(|s| s.to_string()),
current_text: String::new(),
graphemes_left: line
.text_without_character_name()
.graphemes(true)
.map(|s| s.to_string())
.collect(),
// This fn can get called AFTER setting writer speed
current_speed: self.current_speed,
..default()
};
}
pub fn is_finished(&self) -> bool {
self.graphemes_left.is_empty() && !self.current_text.is_empty()
}
fn update_current_text(&mut self) -> String {
if self.is_finished() {
return String::new();
}
self.elapsed += self.start.elapsed().as_secs_f32();
self.start = Instant::now();
let calculated_graphemes = (self.current_speed * self.elapsed).floor() as usize;
let graphemes_left = self.graphemes_left.len();
let grapheme_length_to_take = (calculated_graphemes).min(graphemes_left);
self.elapsed -= grapheme_length_to_take as f32 / self.current_speed;
let graphemes_to_take = self
.graphemes_left
.drain(..grapheme_length_to_take)
.collect::<Vec<String>>()
.concat();
let multiplier = AVERAGE_SPEED / self.current_speed;
if graphemes_to_take.contains('?') {
self.elapsed -= 0.35 * multiplier;
} else if graphemes_to_take.contains(':') {
self.elapsed -= 0.3 * multiplier;
} else if graphemes_to_take.contains('.') {
if let Some(index) = graphemes_to_take.chars().rev().position(|c| c == '.') {
if index + 1 < graphemes_to_take.len()
|| !self.graphemes_left.is_empty() && !self.graphemes_left[0].starts_with('.')
{
self.elapsed -= 0.2 * multiplier;
}
}
} else if graphemes_to_take.contains(',') {
self.elapsed -= 0.1 * multiplier;
}
self.current_text += &graphemes_to_take;
graphemes_to_take.to_string()
}
}
fn write_text(
assets: Res<GameAssets>,
mut typewriter: ResMut<Typewriter>,
mut q_text: Query<&mut Text, With<DialogueContent>>,
mut ev_play_blip: EventWriter<PlayBlipEvent>,
) {
let mut text = match q_text.get_single_mut() {
Ok(r) => r,
Err(_) => return,
};
if typewriter.is_finished() {
return;
}
let added_text = typewriter.update_current_text();
if !added_text.is_empty() && &added_text != " " {
ev_play_blip.send(PlayBlipEvent::new(
&typewriter.character_name.clone().unwrap_or_default(),
));
}
let rest = typewriter.graphemes_left.join("");
*text = create_dialogue_text(&typewriter.current_text, rest, &assets);
}
fn show_continue(
mut q_visibility: Query<&mut Visibility, With<DialogueContinueNode>>,
mut ev_typewriter_finished: EventReader<TypewriterFinished>,
) {
if ev_typewriter_finished.is_empty() {
return;
}
ev_typewriter_finished.clear();
let mut visibility = match q_visibility.get_single_mut() {
Ok(r) => r,
Err(_) => return,
};
*visibility = Visibility::Inherited;
}
fn send_finished_event(
mut typewriter: ResMut<Typewriter>,
mut ev_typewriter_finished: EventWriter<TypewriterFinished>,
) {
if typewriter.is_finished() && !typewriter.last_finished {
ev_typewriter_finished.send(TypewriterFinished);
typewriter.last_finished = true;
}
}
fn set_writer_speed(
debug_active: Res<DebugActive>,
mut typewriter: ResMut<Typewriter>,
mut ev_present_line: EventReader<PresentLineEvent>,
) {
for ev in ev_present_line.read() {
if **debug_active {
typewriter.current_speed = DEBUG_SPEED;
continue;
}
let name = ev
.line
.character_name()
.unwrap_or_default()
.trim_start_matches('_');
let maybe_npc = NpcDialogue::from_str(name);
let speed = if let Ok(npc) = maybe_npc {
match npc {
NpcDialogue::Ami => 18.0,
NpcDialogue::Ima => 18.0,
}
} else {
20.0
};
typewriter.current_speed = speed;
}
}
pub struct DialogueTypewriterPlugin;
impl Plugin for DialogueTypewriterPlugin {
fn build(&self, app: &mut App) {
app.add_systems(
Update,
(
send_finished_event,
write_text,
show_continue,
set_writer_speed,
)
.chain()
.after(YarnSpinnerSystemSet)
.in_set(DialogueViewSystemSet)
.run_if(not(in_state(GameState::AssetLoading))),
)
.init_resource::<Typewriter>()
.add_event::<TypewriterFinished>();
}
}
| 412 | 0.799721 | 1 | 0.799721 | game-dev | MEDIA | 0.398284 | game-dev,desktop-app | 0.921858 | 1 | 0.921858 |
hizzlehoff/FaceCapOSCReceiverExample | 2,817 | Face-Cap OSC Receiver Example/Assets/extOSC/Scripts/Serialization/Packers/OSCPackerAttribute.cs | /* Copyright (c) 2019 ExT (V.Sigalkin) */
#if !NETFX_CORE
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using extOSC.Core.Reflection;
namespace extOSC.Serialization.Packers
{
public class OSCPackerAttribute : OSCPacker<object>
{
#region Protected Static Methods
protected static IEnumerable<MemberInfo> GetMembers(Type type)
{
return type.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(member => Attribute.IsDefined(member, typeof(OSCSerializeAttribute)));
}
#endregion
#region Public Methods
public override Type GetPackerType()
{
return typeof(object);
}
#endregion
#region Protected Methods
protected override object OSCValuesToValue(List<OSCValue> values, ref int start, Type type)
{
var members = GetMembers(type);
var value = Activator.CreateInstance(type);
foreach (var memberInfo in members)
{
var oscValue = values[start];
var property = OSCReflectionProperty.Create(value, memberInfo);
if (property != null && !oscValue.IsNull)
{
property.SetValue(OSCSerializer.Unpack(values, ref start, property.PropertyType));
}
else
{
start++;
}
}
return value;
}
protected override void ValueToOSCValues(List<OSCValue> values, object value)
{
var members = GetMembers(value.GetType());
foreach (var memberInfo in members)
{
var property = OSCReflectionProperty.Create(value, memberInfo);
if (property != null)
{
var propertyValue = property.GetValue();
if (propertyValue == null)
{
values.Add(OSCValue.Null());
continue;
}
OSCSerializer.Pack(values, propertyValue);
}
else
{
throw new NullReferenceException("Property not found!");
}
}
}
protected Type GetMemberType(MemberInfo member)
{
var fieldInfo = member as FieldInfo;
if (fieldInfo != null)
return fieldInfo.FieldType;
var propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
return propertyInfo.PropertyType;
return null;
}
#endregion
}
}
#endif | 412 | 0.95724 | 1 | 0.95724 | game-dev | MEDIA | 0.190719 | game-dev | 0.975797 | 1 | 0.975797 |
PacktPublishing/Beginning-Cpp-Game-Programming | 3,161 | Proj_03_Codes/chapter 15/code/Update.cpp | #include "stdafx.h"
#include "Engine.h"
#include <SFML/Graphics.hpp>
#include <sstream>
using namespace sf;
void Engine::update(float dtAsSeconds)
{
if (m_NewLevelRequired)
{
// These calls to spawn will be moved to a new
// LoadLevel function soon
// Spawn Thomas and Bob
//m_Thomas.spawn(Vector2f(0,0), GRAVITY);
//m_Bob.spawn(Vector2f(100, 0), GRAVITY);
// Make sure spawn is called only once
//m_TimeRemaining = 10;
//m_NewLevelRequired = false;
// Load a level
loadLevel();
}
if (m_Playing)
{
// Update Thomas
m_Thomas.update(dtAsSeconds);
// Update Bob
m_Bob.update(dtAsSeconds);
// Detect collisions and see if characters have reached the goal tile
// The second part of the if condition is only executed
// when thomas is touching the home tile
if (detectCollisions(m_Thomas) && detectCollisions(m_Bob))
{
// New level required
m_NewLevelRequired = true;
// Play the reach goal sound
m_SM.playReachGoal();
}
else
{
// Run bobs collision detection
detectCollisions(m_Bob);
}
// Let bob and thomas jump on each others heads
if (m_Bob.getFeet().intersects(m_Thomas.getHead()))
{
m_Bob.stopFalling(m_Thomas.getHead().top);
}
else if (m_Thomas.getFeet().intersects(m_Bob.getHead()))
{
m_Thomas.stopFalling(m_Bob.getHead().top);
}
// Count down the time the player has left
m_TimeRemaining -= dtAsSeconds;
// Have Thomas and Bob run out of time?
if (m_TimeRemaining <= 0)
{
m_NewLevelRequired = true;
}
}// End if playing
// Check if a fire sound needs to be played
vector<Vector2f>::iterator it;
// Iterate through the vector of Vector2f objects
for (it = m_FireEmitters.begin(); it != m_FireEmitters.end(); it++)
{
// Where is this emitter?
// Store the location in pos
float posX = (*it).x;
float posY = (*it).y;
// is the emiter near the player?
// Make a 500 pixel rectangle around the emitter
FloatRect localRect(posX - 250, posY - 250, 500, 500);
// Is the player inside localRect?
if (m_Thomas.getPosition().intersects(localRect))
{
// Play the sound and pass in the location as well
m_SM.playFire(Vector2f(posX, posY), m_Thomas.getCenter());
}
}
// Set the appropriate view around the appropriate character
if (m_SplitScreen)
{
m_LeftView.setCenter(m_Thomas.getCenter());
m_RightView.setCenter(m_Bob.getCenter());
}
else
{
// Centre full screen around appropriate character
if (m_Character1)
{
m_MainView.setCenter(m_Thomas.getCenter());
}
else
{
m_MainView.setCenter(m_Bob.getCenter());
}
}
// Time to update the HUD?
// Increment the number of frames since the last HUD calculation
m_FramesSinceLastHUDUpdate++;
// Update the HUD every m_TargetFramesPerHUDUpdate frames
if (m_FramesSinceLastHUDUpdate > m_TargetFramesPerHUDUpdate)
{
// Update game HUD text
stringstream ssTime;
stringstream ssLevel;
// Update the time text
ssTime << (int)m_TimeRemaining;
m_Hud.setTime(ssTime.str());
// Update the level text
ssLevel << "Level:" << m_LM.getCurrentLevel();
m_Hud.setLevel(ssLevel.str());
m_FramesSinceLastHUDUpdate = 0;
}
} | 412 | 0.824352 | 1 | 0.824352 | game-dev | MEDIA | 0.984439 | game-dev | 0.916127 | 1 | 0.916127 |
MapServer/MapServer | 8,484 | src/renderers/agg/include/agg_dda_line.h | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes dda_line_interpolator, dda2_line_interpolator
//
//----------------------------------------------------------------------------
#ifndef AGG_DDA_LINE_INCLUDED
#define AGG_DDA_LINE_INCLUDED
#include <stdlib.h>
#include "agg_basics.h"
namespace mapserver
{
//===================================================dda_line_interpolator
template<int FractionShift, int YShift=0> class dda_line_interpolator
{
public:
//--------------------------------------------------------------------
dda_line_interpolator() {}
//--------------------------------------------------------------------
dda_line_interpolator(int y1, int y2, unsigned count) :
m_y(y1),
m_inc(((y2 - y1) << FractionShift) / int(count)),
m_dy(0)
{
}
//--------------------------------------------------------------------
void operator ++ ()
{
m_dy += m_inc;
}
//--------------------------------------------------------------------
void operator -- ()
{
m_dy -= m_inc;
}
//--------------------------------------------------------------------
void operator += (unsigned n)
{
m_dy += m_inc * n;
}
//--------------------------------------------------------------------
void operator -= (unsigned n)
{
m_dy -= m_inc * n;
}
//--------------------------------------------------------------------
int y() const { return m_y + (m_dy >> (FractionShift-YShift)); }
int dy() const { return m_dy; }
private:
int m_y;
int m_inc;
int m_dy;
};
//=================================================dda2_line_interpolator
class dda2_line_interpolator
{
public:
typedef int save_data_type;
enum save_size_e { save_size = 2 };
//--------------------------------------------------------------------
dda2_line_interpolator() = default;
//-------------------------------------------- Forward-adjusted line
dda2_line_interpolator(int y1, int y2, int count) :
m_cnt(count <= 0 ? 1 : count),
m_lft((y2 - y1) / m_cnt),
m_rem((y2 - y1) % m_cnt),
m_mod(m_rem),
m_y(y1)
{
if(m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
m_mod -= count;
}
//-------------------------------------------- Backward-adjusted line
dda2_line_interpolator(int y1, int y2, int count, int) :
m_cnt(count <= 0 ? 1 : count),
m_lft((y2 - y1) / m_cnt),
m_rem((y2 - y1) % m_cnt),
m_mod(m_rem),
m_y(y1)
{
if(m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
//-------------------------------------------- Backward-adjusted line
dda2_line_interpolator(int y, int count) :
m_cnt(count <= 0 ? 1 : count),
m_lft(y / m_cnt),
m_rem(y % m_cnt),
m_mod(m_rem),
m_y(0)
{
if(m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
//--------------------------------------------------------------------
void save(save_data_type* data) const
{
data[0] = m_mod;
data[1] = m_y;
}
//--------------------------------------------------------------------
void load(const save_data_type* data)
{
m_mod = data[0];
m_y = data[1];
}
//--------------------------------------------------------------------
void operator++()
{
m_mod += m_rem;
m_y += m_lft;
if(m_mod > 0)
{
m_mod -= m_cnt;
m_y++;
}
}
//--------------------------------------------------------------------
void operator--()
{
if(m_mod <= m_rem)
{
m_mod += m_cnt;
m_y--;
}
m_mod -= m_rem;
m_y -= m_lft;
}
//--------------------------------------------------------------------
void adjust_forward()
{
m_mod -= m_cnt;
}
//--------------------------------------------------------------------
void adjust_backward()
{
m_mod += m_cnt;
}
//--------------------------------------------------------------------
int mod() const { return m_mod; }
int rem() const { return m_rem; }
int lft() const { return m_lft; }
//--------------------------------------------------------------------
int y() const { return m_y; }
private:
int m_cnt = 0;
int m_lft = 0;
int m_rem = 0;
int m_mod = 0;
int m_y = 0;
};
//---------------------------------------------line_bresenham_interpolator
class line_bresenham_interpolator
{
public:
enum subpixel_scale_e
{
subpixel_shift = 8,
subpixel_scale = 1 << subpixel_shift,
subpixel_mask = subpixel_scale - 1
};
//--------------------------------------------------------------------
static int line_lr(int v) { return v >> subpixel_shift; }
//--------------------------------------------------------------------
line_bresenham_interpolator(int x1, int y1, int x2, int y2) :
m_x1_lr(line_lr(x1)),
m_y1_lr(line_lr(y1)),
m_x2_lr(line_lr(x2)),
m_y2_lr(line_lr(y2)),
m_ver(abs(m_x2_lr - m_x1_lr) < abs(m_y2_lr - m_y1_lr)),
m_len(m_ver ? abs(m_y2_lr - m_y1_lr) :
abs(m_x2_lr - m_x1_lr)),
m_inc(m_ver ? ((y2 > y1) ? 1 : -1) : ((x2 > x1) ? 1 : -1)),
m_interpolator(m_ver ? x1 : y1,
m_ver ? x2 : y2,
m_len)
{
}
//--------------------------------------------------------------------
bool is_ver() const { return m_ver; }
unsigned len() const { return m_len; }
int inc() const { return m_inc; }
//--------------------------------------------------------------------
void hstep()
{
++m_interpolator;
m_x1_lr += m_inc;
}
//--------------------------------------------------------------------
void vstep()
{
++m_interpolator;
m_y1_lr += m_inc;
}
//--------------------------------------------------------------------
int x1() const { return m_x1_lr; }
int y1() const { return m_y1_lr; }
int x2() const { return line_lr(m_interpolator.y()); }
int y2() const { return line_lr(m_interpolator.y()); }
int x2_hr() const { return m_interpolator.y(); }
int y2_hr() const { return m_interpolator.y(); }
private:
int m_x1_lr;
int m_y1_lr;
int m_x2_lr;
int m_y2_lr;
bool m_ver;
unsigned m_len;
int m_inc;
dda2_line_interpolator m_interpolator;
};
}
#endif
| 412 | 0.70991 | 1 | 0.70991 | game-dev | MEDIA | 0.314696 | game-dev | 0.80634 | 1 | 0.80634 |
AlderArts/foe | 175,779 | js/event/outlaws/vaughn-tasks.ts |
import { GetDEBUG } from "../../../app";
import { GAME, MoveToLocation, TimeStep, WORLD, WorldTime } from "../../GAME";
import { Gui } from "../../gui";
import { CombatItems } from "../../items/combatitems";
import { QuestItems } from "../../items/quest";
import { Jobs } from "../../job";
import { IChoice } from "../../link";
import { RigardFlags } from "../../loc/rigard/rigard-flags";
import { Party } from "../../party";
import { IParse, Text } from "../../text";
import { Time } from "../../time";
import { GlobalScenes } from "../global";
import { Miranda } from "../miranda";
import { MirandaFlags } from "../miranda-flags";
import { Player } from "../player";
import { Room69 } from "../room69";
import { Room69Flags } from "../room69-flags";
import { Lei } from "../royals/lei";
import { LeiFlags } from "../royals/lei-flags";
import { Twins } from "../royals/twins";
import { Terry } from "../terry";
import { Outlaws } from "./outlaws";
import { Vaughn } from "./vaughn";
import { VaughnFlags } from "./vaughn-flags";
export namespace VaughnTasksScenes {
export function OnTask() { // TODO add tasks
return VaughnTasksScenes.Lockpicks.OnTask() ||
VaughnTasksScenes.Snitch.OnTask() ||
VaughnTasksScenes.Poisoning.OnTask();
}
export function AnyTaskAvailable() { // TODO add tasks
return VaughnTasksScenes.Lockpicks.Available() ||
VaughnTasksScenes.Snitch.Available() ||
VaughnTasksScenes.Poisoning.Available();
}
export function StartTask() { // TODO add tasks
if (VaughnTasksScenes.Lockpicks.Available()) {
VaughnTasksScenes.Lockpicks.Start();
} else if (VaughnTasksScenes.Snitch.Available()) {
VaughnTasksScenes.Snitch.Start();
} else if (VaughnTasksScenes.Poisoning.Available()) {
VaughnTasksScenes.Poisoning.Start();
}
}
export function TaskPrompt(Prompt: any) {
const parse: IParse = {
};
Text.Clear();
if (VaughnTasksScenes.AnyTaskAvailable()) {
Text.Add("<i>“So, you’re interested in seeing some action? Young people, full of drive and fire… well, I’m not about to stop you from doing what an operative’s supposed to do.”</i> Vaughn thinks a moment, then smiles. <i>“Just so it happens, there’s something that came up which needs handling, and it has to be done the next day. You interested? Remember, you’ll be on the clock if I hand the assignment to you, so don’t accept responsibility for anything that you’re not willing to see through. You’re still thinking of going out there?”</i>", parse);
Text.Flush();
// [Yes][No]
const options: IChoice[] = [];
options.push({ nameStr : "Yes",
tooltip : "Yes, you’ll take it.",
func() {
Text.Clear();
Text.Add("<i>“All right, then. Let’s see what the boss-man wants me to hand down to you today…”</i>", parse);
Text.Flush();
Gui.NextPrompt(VaughnTasksScenes.StartTask);
}, enabled : true,
});
options.push({ nameStr : "No",
tooltip : "No, you’re not sure if you can see the task through.",
func() {
Text.Clear();
Text.Add("Vaughn nods and shrugs at your words. <i>“Better that you say upfront that you can’t do it, rather than accept the job and get creamed, then leave everyone else to pick up the pieces. It’s no big deal; I’ll just pass along the task to someone who’s in the clear. You get points in my book for being honest about it.”</i>", parse);
Text.NL();
Text.Add("Points? Is he keeping score?", parse);
Text.NL();
Text.Add("<i>“Might be, might not be,”</i> Vaughn replies with a completely straight face. <i>“Now, was there something else you wanted of me?”</i>", parse);
Text.Flush();
Prompt();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
} else {
Text.Add("<i>“Hmm.”</i> Vaughn takes his gaze off you and thinks for a moment. <i>“Don’t imagine I’ve got anything for you at the moment; the other operatives pretty much have all our bases covered and the boss-man’s been in a thinking mood, as opposed to a doing one. Maybe you should go out there and move things along - stir up the hive, as they say. That should create all sorts of opportunities for us to get our fingers into some more pies.”</i>", parse);
Text.NL();
Text.Add("All right, then. You’ll ask later.", parse);
Text.NL();
Text.Add("<i>“Don’t just come calling around these parts,”</i> Vaughn calls out after you as you leave. <i>“I’m just one fellow, you know. Pretty sure there’re other folks in camp who could use a hand or two anytime - just have to ask around until you find them.”</i>", parse);
Text.Flush();
Prompt();
}
}
export namespace Lockpicks {
export function Available() {
if (GAME().vaughn.flags.Met >= VaughnFlags.Met.OnTaskLockpicks) { return false; }
return true;
}
export function OnTask() {
return GAME().vaughn.flags.Met === VaughnFlags.Met.OnTaskLockpicks;
}
export function Completed() {
return GAME().vaughn.flags.Met >= VaughnFlags.Met.CompletedLockpicks;
}
// No special requirements. Player should already have access to castle grounds.
// Note to Alder: refer to castle grounds docs. Create flag to see if player has inadvertently met Elodie via castle grounds exploration for use in this.
// Block that exploration scene if this scene has been viewed.
// TODO Note for far future: Do not enable this if/when Majid has been run out of Rigard.
export function Start() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const terry: Terry = GAME().terry;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
Text.Add("<i>“Right, then.”</i> Vaughn pulls down the brim of his hat, turns, and heads for a door at the base of the watchtower. <i>“The boss-man’s decided to let you cut your teeth on something straightforward and simple, so give me a moment here.”</i>", parse);
Text.NL();
Text.Add("With that, Vaughn boots open the door and heads inside, lighting a candle in a holder by the doorway as he does so. The base of the watchtower is occupied by a storeroom of sorts, and as you look on, Vaughn picks out a leather pouch from one of the shelves before tossing it to you in a lazy arc.", parse);
Text.NL();
Text.Add("<i>“Here, catch.”</i>", parse);
Text.NL();
Text.Add("You do so. Whatever’s in the pouch is cold and hard, clearly made from metal, and they jingle as they hit the palm of your hand.", parse);
Text.NL();
Text.Add("<i>“Fresh from upriver,”</i> Vaughn explains as he closes the storeroom door behind him with a flourish and adjusts his hat. <i>“Quality thieves’ tools.”</i>", parse);
Text.NL();
Text.Add("Oh? You undo the string that holds the pouch closed, and are faced with quite the menagerie of interesting implements: various pieces of metal bent in interesting ways, a sharp, silent glass cutter, a hammer no longer than the width of your palm, and other more… exotic-looking things.", parse);
Text.NL();
if (party.InParty(terry)) {
parse.foxvixen = terry.mfPronoun("fox", "vixen");
parse.himher = terry.himher();
Text.Add("<i>“Hmph,”</i> Terry says with a disdainful sniff, the [foxvixen] peering over your shoulder to scrutinize the toolset. <i>“Amateurs.”</i>", parse);
Text.NL();
Text.Add("Is that supposed to mean anything?", parse);
Text.NL();
Text.Add("<i>“Weeelll… I suppose they’ll do - assuming that you aren’t actually going after a mark that’s got any serious security. Yeah, they’ll get the job done in most cases. Most. And if they’re not going to be enough, then you’d be wanting a professional handling it.”</i>", parse);
Text.NL();
Text.Add("Like [himher], then?", parse);
Text.NL();
Text.Add("<i>“You know what? Forget I said anything.”</i>", parse);
Text.NL();
Text.Add("Maybe you will, and maybe you won’t. You’ll be keeping that in mind for later…", parse);
Text.NL();
}
Text.Add("<i>“Anyway,”</i> Vaughn continues, <i>“we need these delivered to one of our people in the castle. Word’s had it that you’ve recently gained access to the castle grounds, so you’re the most obvious courier we have on hand.”</i>", parse);
Text.NL();
Text.Add("How would he know that, anyway?", parse);
Text.NL();
Text.Add("<i>“We have eyes and ears in the city that most overlook. Now, while it’s not a matter of life and death, we’d still like these delivered promptly. Just for this first task, you get a little leeway when it comes to time, but I hope that you don’t abuse said leeway. We’d all like to get off to a good start here, get moving on the right foot.”</i>", parse);
Text.NL();
Text.Add("Oh, so he’s going easy on you, is he?", parse);
Text.NL();
Text.Add("Vaughn shrugs and pulls the brim of his hat over his eyes. <i>“Could be. Learn to walk before you try to run, as the old saying goes.”</i>", parse);
Text.NL();
Text.Add("All right, you get his point. Now, who are you supposed to pass these along to, where are you going to meet him or her, and how will you recognize each other?", parse);
Text.NL();
Text.Add("<i>“We’ve got someone in the castle proper, girl by the name of Elodie; that’s who you need to hand these to. Every day in the evening, she gets let out of the castle for an hour or so to settle her personal affairs in the city. Get yourself to the small park to the west of the castle, and she’ll be on the bench by the pond. As for recognizing each other… there’s a reason we have a sign, you know.”</i>", parse);
Text.NL();
Text.Add("Right, right. You’re just getting used to this whole outlaw business yourself.", parse);
Text.NL();
Text.Add("<i>“Which is why we’re trying to ease you in all nice-like.”</i> Vaughn thinks a moment, then shakes his head. <i>“That’s the long and short of it, [playername]. Go there in the evening, small park to the west of the castle. Girl by the name of Elodie, pretty young, likely to be dressed all formal-like, because castle servant, you see. Hand her the thieves’ tools, then come back to me for a debrief.”</i>", parse);
Text.NL();
Text.Add("All right, that sounds straightforward enough. You’ll be there and back without too much trouble.", parse);
Text.NL();
Text.Add("<i>“Right. High Command is counting on you to work hard in forwarding the cause, and all that other motivational stuff I’m supposed to be saying, but I honestly think is a bunch of crap. Have fun out there, and don’t come back to me before the job is done.”</i>", parse);
Text.Flush();
TimeStep({hour: 1});
GAME().vaughn.taskTimer = new Time(0, 0, 3, 0, 0);
party.Inv().AddItem(QuestItems.OutlawLockpicks);
GAME().vaughn.flags.Met = VaughnFlags.Met.OnTaskLockpicks;
Gui.NextPrompt();
// #add “Tools” option to castle grounds.
}
export function ElodieAvailable() {
return WorldTime().hour >= 16 && WorldTime().hour < 21;
}
// Triggered in castle grounds
export function MeetingElodie() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const rigard = GAME().rigard;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
// Correct time
if (!VaughnTasksScenes.Lockpicks.ElodieAvailable()) {
Text.Add("You arrive at the park and spy the bench by the pond, but there’s currently no one sitting on it at the moment, let alone someone who could be your contact. What was the meeting time again? Sometime in the evening? Maybe you should come back then.", parse);
Text.Flush();
TimeStep({minute: 10});
Gui.NextPrompt();
return;
}
const metElodie = rigard.flags.Nobles & RigardFlags.Nobles.Elodie;
Text.Add("Evening lends a calm air to the castle grounds, and you arrive at the park as instructed. With the day drawing to a close, servants and nobles alike are enjoying what small amount of free time there’s to be had - this close to the castle proper, extra care is taken by the groundskeepers to ensure the flowerbeds are pristine and the lakes clear.", parse);
Text.NL();
Text.Add("<b>“No walking on the grass”</b> - elsewhere, that might be a joke, but it wouldn’t do to test the resolve of the patrols that’re charged with enforcing such.", parse);
Text.NL();
Text.Add("After a little looking around, you spy the bench that Vaughn singled out - an elegantly carved two-seater facing a small pond. Seated on it is a young woman, a small brown bag full of breadcrumbs in her hands as she reaches into it and scatters them onto the water’s surface, much to the local ducks’ delight.", parse);
Text.NL();
if (metElodie) {
Text.Add("You recognize her immediately: the maid who was staring at you on the streets of the castle grounds some time back. She’s with the outlaws? Well, it would explain why she was eyeing you, or how she managed to blend into the crowd so effortlessly. The result of plenty of practice, no doubt.", parse);
Text.NL();
Text.Add("Well, it seems like you’ll get the chance to confront her, regardless of how either of you feels about it.", parse);
Text.NL();
Text.Add("Clearly, she’s felt your gaze upon her, for she looks up and meets your eyes, brushing a few stray strands of rust-brown hair out of the way. You do your best to be discreet in quickly sketching the outlaws’ symbol in the air, then let out the breath you’d been holding when she quickly sketches the three-fingered paw back at you and picks up her headdress from the bench.", parse);
Text.NL();
Text.Add("<i>“Ah, so my suspicions were right. You <b>are</b> with us, then.”</i>", parse);
Text.NL();
Text.Add("What kind of suspicions did she have about you that she was staring at you in the street?", parse);
Text.NL();
Text.Add("<i>“The kind someone in my position should have when an unknown quantity turns up. Now hurry, beside me. And don’t be so self-conscious, you’re drawing attention.”</i>", parse);
} else {
Text.Add("You take a moment to size up the young woman. Dressed in a long-sleeved blouse, apron and long skirts all dyed in the royal colors, there’s little doubt that she’s a servant of some sort - her outfit just screams “maid”, although to whom and in what standing, you’re not completely sure.", parse);
Text.NL();
Text.Add("Judging by the white linen gloves she’s wearing and the headdress lying on the bench beside her, though, you’re guessing that she does serve someone quite important for her daily dress to require such. Neat and clean, but deliberately muted, her attire’s clearly designed to be presentable and elegant without running the risk of outshining any important personages nearby.", parse);
Text.NL();
Text.Add("All in all, she looks really young - couldn’t be more than eighteen or nineteen, which only makes her ample bosom stand out on her still maturing frame. A touch of morph blood in her veins, perhaps? A silvered brooch pinned on her breast marks her as being in the castle’s employ which is probably why she’s been left largely alone while waiting for you. Raucous though the local lads may be, they presumably know enough to run the risk of displeasing someone within the castle.", parse);
Text.NL();
Text.Add("Clearly, she’s felt your gaze upon her, for she looks up and meets your eyes, brushing a few stray strands of rust-brown hair out of the way. You do your best to be discreet in quickly sketching the outlaws’ symbol in the air, then let out the breath you’d been holding when she quickly sketches the three-fingered paw back at you and picks up her headdress from the bench.", parse);
Text.NL();
Text.Add("<i>“Hurry, beside me. And don’t be so self-conscious, you’re drawing attention.”</i>", parse);
}
Text.NL();
Text.Add("Well, that’s an invitation if you ever had one. Easing yourself onto the bench beside her, you lean back and try to look nonchalant as she continues feeding the ducks.", parse);
Text.NL();
Text.Add("She’s Elodie?", parse);
Text.NL();
Text.Add("<i>“Yes, and you’re [playername], the one who came through the portal. You have them?”</i>", parse);
Text.NL();
Text.Add("Wordlessly, you produce the bag of thieves’ tools and slide them across to Elodie. She palms the bag, draws it open and peers inside, scrutinizing its contents before tying it closed and tucking it away into her apron.", parse);
Text.NL();
Text.Add("<i>“Send the badger my regards.”</i>", parse);
Text.NL();
Text.Add("Brusque, isn’t she? Since there’s the possibility that you’re going to be working together from now on, shouldn’t you at least introduce yourselves properly?", parse);
Text.NL();
Text.Add("Elodie doesn’t reply immediately, instead looking about her for… well, you’re not sure what it is she’s looking for. The ducks quack happily as she throws another handful of breadcrumbs onto the lake’s surface. <i>“Right. The next person I’m supposed to meet this evening isn’t here yet, so I’ve some time to spare. I’m Elodie, handmaiden to the Queen - or rather, one of the many handmaidens to the Queen.”</i>", parse);
Text.NL();
Text.Add("Right. That would explain the fancy outfit.", parse);
Text.NL();
Text.Add("<i>“This isn’t ‘fancy’. Trust me, you haven’t seen fancy when it comes to what goes on within the castle.”</i>", parse);
Text.NL();
Text.Add("Fine, fine. Still, it surprises you that the outlaws would have someone so close to the royal family. With someone in Elodie’s position, you’d have thought they’d have made a move by now. Is that what the thieves’ tools are for?", parse);
Text.NL();
Text.Add("<i>“How much do you know about Majid?”</i> Elodie replies. <i>“Do you know, for example, that before he became vizier to our good king Rewyn, he was a common criminal?”</i>", parse);
Text.NL();
Text.Add("No… you didn’t know that. Come to think about it, you don’t really know that much about his past, even though everything you’ve heard about him tends to be bad news.", parse);
Text.NL();
Text.Add("<i>“Oh, he was somewhat high up, as criminals reckon themselves. Nevertheless, our dear vizier was a criminal all the same, and I have little doubt he still is.”</i> She jangles the pouch in her apron. <i>“The evidence I need is close, I’m sure of that. All I have to do is actually get my hands on it…”</i>", parse);
Text.NL();
Text.Add("Well, good luck with that.", parse);
Text.NL();
Text.Add("<i>“Yes.”</i> She looks around once more, then eyes you. <i>“I suggest that you be on your way soon. My next contact is about to arrive. Say hello to the people in the forest for me.”</i>", parse);
Text.NL();
Text.Add("Right. You just need to ask one more thing… there isn’t any way that she could help get you into the castle, is there?", parse);
Text.NL();
Text.Add("<i>“No. Let’s put it in perspective: it took me seven years to work my way up from scullery girl to handmaiden to the Queen, during which I took more than a few liberties which I realize could have gone very, very badly for me had I been less lucky. Getting into the castle isn’t something that’s easily done. You’re obviously resourceful to worm your way into the grounds on such short notice, but I can’t help you with this one.”</i>", parse);
Text.NL();
Text.Add("All right. Well, there doesn’t seem like there’s anything else for you here. Standing up, you dust off your seat and leave the park just in time to see a well-dressed man take a seat besides Elodie and strike up a conversation, just like you did. As you look on, her previously hard demeanor quickly melts away into one of shy, girlish innocence at the drop of a hat, a changing of masks. The last glimpse you have of Elodie is that of her squeaking in surprise and giggling nervously as her contact pinches her butt.", parse);
Text.NL();
Text.Add("Seems like her evenings are quite busy… well, it’s none of your business. Time to head back and report in, then.", parse);
Text.Flush();
party.Inv().RemoveItem(QuestItems.OutlawLockpicks);
GAME().vaughn.flags.Met = VaughnFlags.Met.LockpicksElodie;
TimeStep({hour: 1});
Gui.NextPrompt();
}
// Automatically triggers when approaching Vaughn after completing the task.
export function Debrief() {
const player: Player = GAME().player;
const outlaws: Outlaws = GAME().outlaws;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
Text.Add("<i>“Ah, you’re back.”</i> Vaughn tips his hat at you as you approach. <i>“Passed them along just fine, didn’t you?”</i>", parse);
Text.NL();
Text.Add("Yes, you did.", parse);
Text.NL();
if (vaughn.taskTimer.Expired()) {
Text.Add("<i>“Right, right. Remember what I said about not taking your time and acting as if everything’s going to wait forever until you go and start things? Well, perhaps you didn’t, because those picks arrived later than they ought to have.</i>", parse);
Text.NL();
Text.Add("<i>“It’s not too much of a problem now - better late than never, as some say - but from here on out, late is going to be never. You’ll want to be punctual, because if you act like someone who can’t be relied upon, don’t be surprised when people don’t rely on you to get the job done.”</i>", parse);
Text.NL();
Text.Add("Right, right, you’ll be punctual from here on out.", parse);
Text.NL();
Text.Add("<i>“As I said, it’s better to not accept and let others do the job than accept and not show up. I mean it - people are going to be very, <b>very</b> upset if you waste all their hard work just because you showed up late. Consider this fair warning; this isn’t your family’s business, as the saying goes. Now, back to the point. What were you about to say?”</i>", parse);
Text.NL();
} else {
outlaws.relation.IncreaseStat(100, 1);
}
Text.Add("Seems like even the castle isn’t free of the shenanigans that’re sweeping the kingdom.", parse);
Text.NL();
Text.Add("Vaughn removes his hat and wipes his brow, swivelling his ears in your direction. <i>“What? You mean the place where the people responsible for all this crap live is supposed to be free of the crap itself? Spirits forbid, you’d have expected them to know not to shit where they eat, but hey, seems like it’s just the opposite. I don’t envy Elodie, but that girl’s got some fire within her. She’s the only person we’ve got inside the castle, and that took years to set up.”</i>", parse);
Text.NL();
Text.Add("You were told as much, yes.", parse);
Text.NL();
Text.Add("<i>“Well, that seems to wrap it up. I do hope that girl doesn’t get in over her head - she has a thing for anything remotely related to the vizier, but there’s no stopping her.</i>", parse);
Text.NL();
Text.Add("<i>“As for you, [playername], I can’t give you much in return, but maybe you should head down to Raine’s and get something hot to eat. I’ll indent a bottle of moonshine in your name; it’s the least I can do. Amazing what you can do with water, wild fruit and a little sugar - just remember to turn in the bottles when you’re done. Glass is hard to come by these days.”</i>", parse);
Text.NL();
Text.Add("With that, he plonks his hat onto his head once more, and lights up a cigarette before heading into the watchtower’s confines.", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.CompletedLockpicks;
outlaws.relation.IncreaseStat(100, 3);
TimeStep({hour: 1});
Gui.NextPrompt();
}
}
export namespace Snitch {
export function Available() {
if (GAME().vaughn.flags.Met >= VaughnFlags.Met.CompletedSnitch) { return false; }
return true;
}
export function OnTask() {
return GAME().vaughn.flags.Met === VaughnFlags.Met.OnTaskSnitch;
}
export function Completed() {
return GAME().vaughn.flags.Met >= VaughnFlags.Met.CompletedSnitch;
}
// Disable this and jump ahead to task 3 if Miranda has been permanently recruited.
export function Start() {
const player: Player = GAME().player;
const miranda: Miranda = GAME().miranda;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
Text.Add("<i>“All right, then. Let’s see how good you are at a little sneaking about, then.”</i>", parse);
Text.NL();
Text.Add("What does he have in mind? Is he going to ask you to filch something?", parse);
Text.NL();
Text.Add("Vaughn grins. <i>“Actually, just the opposite. The boss-man would like you to put something where it shouldn’t be.”</i>", parse);
Text.NL();
Text.Add("That does sound interesting. Why, he should tell you more about what he has in mind.", parse);
Text.NL();
Text.Add("<i>“We’ve had a little problem with a certain constable in the City Watch shaking down the beggars on the streets, keeping them from even the usual spots which by tacit agreement, they’re allowed to ply their trade. Fellow by the name of Terrell… seriously, what kind of guy shakes down beggars for two coins’ worth of protection money?</i>", parse);
Text.NL();
Text.Add("<i>“Needless to say, the beggars are rather fed up with the situation, and since they’re our eyes and ears on the streets, it’s behooved the boss-man to step in and offer his support. Stand up for the poor and dispossessed, you know? Play the noble spirit and dish out a little justice?”</i>", parse);
Text.NL();
Text.Add("What a lofty goal. Vaughn and you lock eyes for a moment, then his grin twists into a smirk as he reaches into his vest and pulls out a folded slip of rough, stained paper. He thrusts it at you, and you catch it. Unfolding the paper, it’s a hand-drawn map of several blocks in the residential district, with lines drawn in the streets and times scribbled on the margins. You look up at Vaughn, and he shrugs.", parse);
Text.NL();
Text.Add("<i>“Funny thing about a corrupt fellow, I’ve noticed, is how he can’t keep it contained to just one or two instances. No, once a bastard goes on the take, he tends to grab as much as he can get. What you’re holding in your hands shows a number of surprise inspections on various establishments which took place place in the last week, establishments which were suspected of running illegal, untaxed games of chance. Oddly enough, despite the information they had, the City Watch turned up nothing in their raids.”</i>", parse);
Text.NL();
Text.Add("Terrell?", parse);
Text.NL();
Text.Add("<i>“Now you’re catching on. He sold out the watch, gave away the patrol route, and for what? A handful of coins? Frankly, we’re doing the watch a favor. If he’d kept to pushing around the poor and homeless, no one’d given a fuck. As it is, though… fellow’s overextended himself, and that makes it so much easier for us to take him down. As it stands, getting his bill of sale to the gambling dens was tricker than we’d expected, but we have him now.</i>", parse);
Text.NL();
parse.num = (WorldTime().hour < 12) ? "two" : "three";
Text.Add("<i>“There’s going to be a locker inspection at the City Watch headquarters at six in the evening [num] days from now. Now, we aren’t about to show our faces around the City Watch headquarters, but they don’t know you. Get in there before then, plant this evidence in his locker, and step back to watch the fireworks. Now, I don’t know how to find his locker or how you’ll get into his things, so you’ll be alone in that regard. Nevertheless, it’s the best way for his superiors to sniff him out in a natural fashion, and we’d prefer that by far.”</i>", parse);
Text.NL();
Text.Add("If the evidence is solid, then why shouldn’t you just walk into the commander’s office and slam it down on the desk? It should stand on its own merits, shouldn’t it?", parse);
Text.NL();
Text.Add("Quirking an eyebrow, Vaughn stares at you for a good half-minute or so, then bursts out in laughter. <i>“Oh, that’s a good one, [playername]. For a moment there, I thought you were actually serious. I mean, who thinks the watch is going to take some stranger’s word over one of their own? Really really good joke, you nearly got me.”</i>", parse);
Text.NL();
Text.Add("Um… okay.", parse);
Text.NL();
Text.Add("<i>“All right, then. You’ve got your orders, don’t come back to me until you’ve got something to report.”</i> Vaughn dismisses you with a wave of a hand. <i>“Oh, and stay out of trouble. Things have been getting worse and worse in Rigard of late, and I’d rather not see you end up on the inside of a cell - or worse. Good luck.”</i>", parse);
Text.NL();
// TODO: This kinda doesn't work with recruited Miranda
Text.Add("As you walk away, though, you can’t help but wonder about what Vaughn said. Sure, you may not know many of the watch personally, but you’re pretty sure Miranda’s on the straight and narrow. If the map is as solid evidence as Vaughn claims it is, then you should be able to talk Miranda around to your point of view. The more you consider the idea, the more it sounds like a viable alternative to sneaking into the City Watch headquarters - and probably easier, too, especially if you’re not confident that you’re skilled enough to not get caught in the act.", parse);
Text.NL();
if (miranda.Nasty()) {
Text.Add("Of course, given that the two of you aren’t on the best of terms at the moment, you might have to do more than just talk her into listening to you.", parse);
Text.NL();
}
Text.Add("Well, what happens next is up to you. It’s not as if you don’t know where to find the City Watch headquarters… that, or Miranda when she’s off-duty.", parse);
Text.Flush();
TimeStep({hour: 1});
vaughn.flags.Met = VaughnFlags.Met.OnTaskSnitch;
const step = WorldTime().TimeToHour(18);
if (WorldTime().hour < 12) {
vaughn.taskTimer = new Time(0, 0, 2, step.hour, step.minute);
} else {
vaughn.taskTimer = new Time(0, 0, 3, step.hour, step.minute);
}
// #add Evidence option to Miranda at the Maidens' Bane.
// #add Evidence option to City Watch grounds.
Gui.NextPrompt();
}
export function MirandaTalk(options: any[], onDuty: any) {
const miranda: Miranda = GAME().miranda;
const vaughn: Vaughn = GAME().vaughn;
if (vaughn.taskTimer.Expired()) { return; }
if (vaughn.flags.Met === VaughnFlags.Met.OnTaskSnitch && miranda.flags.Snitch === 0) {
options.push({ nameStr : "Snitch",
tooltip : "Present your evidence against Terrell to Miranda and ask the dobie if anything can be done.",
func() {
VaughnTasksScenes.Snitch.Miranda(onDuty);
}, enabled : true,
});
}
}
export function Miranda(onDuty: any) {
const player: Player = GAME().player;
const vaughn: Vaughn = GAME().vaughn;
const miranda: Miranda = GAME().miranda;
let parse: IParse = {
playername : player.name,
};
Text.Clear();
if (onDuty) {
Text.Add("You take a look around, spotting several of Miranda’s colleagues nearby. Perhaps you should try to find somewhere more private to present her with Vaughn’s evidence. It’ll definitely be easier to sway her if she’s on her own, if it comes to that.", parse);
Text.Flush();
// Just leave it at that, the old menu stays
return;
}
// else #else, Triggered at the Maidens’ Bane
parse = player.ParserTags(parse);
Text.Add("Well, you’re here, Miranda’s here, and no one’s looking directly at the both of you. You’ve decided on doing this, might as well get it over with. Convincing Miranda to take action without asking too many inconvenient questions might not be the easiest of tasks, but it’s still more appealing than tampering with someone’s possessions in the City Watch headquarters.", parse);
Text.NL();
Text.Add("Let’s see whether you get off on the right foot, then. Calling over a serving wench, you order a couple of drinks, then settle in as they’re brought to your table.", parse);
Text.NL();
if (miranda.Nice()) {
Text.Add("<i>“Ho!”</i> Miranda exclaims as you pull the evidence out of your possessions. <i>“What’s this we have here?”</i>", parse);
Text.NL();
Text.Add("Slowly, you unfold the paper and explain to Miranda what all this is supposed to mean. Does she have any memory of the most recent crackdown on illegal gambling dens?", parse);
Text.NL();
Text.Add("<i>“I’m not surprised that you heard about it - everyone down at the yard’s been grumbling about it day and night. Of course I still remember it clear as day - my feet still hurt from tramping up and down the streets, rushing from place to place. And for what? Nothing at all. We had good info. We’d been watching each one for a week at least. And when we finally come in to shut them down and round them up, suddenly everything’s just hunky-dory.”</i> The dobie makes a show of spitting onto the table. <i>“All that time wasted, and for what? They’ll move their shows somewhere else, and we’ll have to find them all over again. Could take weeks. Months.”</i>", parse);
Text.NL();
Text.Add("Right, right. Seeing as how Miranda’s exhausted all her vitriol for now, you deem it safe to draw her attention to the paper. Does that handwriting seem familiar? Maybe the times scribbled in the margins? Or the city block - or at least, you think that’s what it is - depicted here in crudely-drawn squares and rectangles?", parse);
Text.NL();
Text.Add("The dobie frowns at you over her drink. <i>“What’re you getting at, [playername]? That’s -”</i>", parse);
Text.NL();
Text.Add("All of a sudden, Miranda’s eyes harden, and she pushes her drink away, the entirety of her attention focused on the little scrap of paper laid out in front of her. She reads it all the way through, then once more, and a final time. Taking her tankard in hand, Miranda slowly tightens her grip - you can actually see the dobie’s knuckles tighten under skin and fur until the tankard crumples and folds in her hand. Cheap beer spills out from the container’s remains, wetting the table - you rush to pull Vaughn’s evidence out of the way and urge her to calm down before she breaks the table, too.", parse);
Text.NL();
Text.Add("Miranda clearly chafes at the thought of calming herself, but acquiesces while you call for someone to clean up the mess and add the broken tankard to your tab. <i>“I knew it. One might’ve been chance. Two would’ve been suspicious - but every single sting we were supposed to make that day being bummed out like that? Someone sold us out!”</i>", parse);
Text.NL();
Text.Add("Right. Does she have an idea of who it is?", parse);
Text.NL();
Text.Add("<i>“Think so.”</i> Miranda looks down at the paper again and claps one meaty fist against the other’s palm. <i>“Look, the bastard even had the times when we were expected to arrive - since the times were only mentioned at last week’s muster, that narrows it down to those present then, and there’s only one bastard amongst those who writes like that. I never liked him… bastard. Can I have this thing?”</i>", parse);
Text.NL();
Text.Add("Why, of course. You’re more than willing to let her have the evidence - you were supposed to plant it anyway, so it’s not as if Vaughn’s expecting you to return it to him. Smiling, you tell Miranda she’s more than welcome to have it. She’ll need something to show her superiors, after all.", parse);
Text.NL();
Text.Add("Miranda growls and pockets the paper. <i>“First thing once I get back to the yard, I’m kicking down the door to the commander’s office and planting this straight on the desk, but first, a drink for the nerves. Feel fit to bust one any moment now - you kind of expect thugs and their sort to have no sense of decency, but when it’s one of our own…</i>", parse);
Text.NL();
Text.Add("<i>“Got to ask you, though. Where’d you find this? Doesn’t seem like it’s the sort of thing one finds lying around. I know you wandering types have your ways - I used to find all sorts of crazy shit back in my time with the Black Hounds - but I still gotta ask.”</i>", parse);
Text.NL();
Text.Add("And right on cue, the inconvenient question. While Miranda might be more reasonable than most of the City Watch, you’re not quite about to confess to her you’re with the outlaws - even if she didn’t want to lock you up, she’d be obligated to, and you know her well enough to bet on her fulfilling that obligation. That leaves either refusing to answer the question, or outright lying to her, regrettable as it may be.", parse);
Text.NL();
Text.Add("Decisions, decisions…", parse);
Text.Flush();
// [Refuse][Lie]
const options: IChoice[] = [];
options.push({ nameStr : "Refuse",
tooltip : "You’re not going to deceive her, but you’re not going to tell the whole truth, either.",
func() {
Text.Clear();
Text.Add("A friend, you tell Miranda. You can’t reveal his name because that would get him into trouble - he spoke to you trusting that he wouldn’t be snitched on. The evidence is good, and you’re willing to stake your reputation on it.", parse);
Text.NL();
Text.Add("<i>“Snitches get stitches, as they say in the slums,”</i> Miranda agrees morosely. Her replacement drink arrives, and throwing back her head, she gulps down half the tankard in one go. <i>“I understand, but that means if the commander starts asking questions, I’ll have to name you as the snitch instead of whoever passed this to you - no problems there, right?”</i>", parse);
Text.NL();
Text.Add("You <i>did</i> just say you were willing to stake your reputation on it. To be frank, if it weren’t for the fact that another watchman would have greater clout and a better grip on the situation, you’d have walked into the yard yourself instead of seeking her out.", parse);
Text.NL();
Text.Add("<i>“Yeah, I get what you’re saying. Good old doggy here, she’ll carry your papers where they need to go. Y’know, what with you not knowing who was selling us out, I’m kinda glad you came to me.”</i>", parse);
Text.NL();
Text.Add("You reply that while she may be many things, you know that Miranda isn’t a sell-out.", parse);
Text.NL();
Text.Add("<i>“Aw, shucks. Flattery isn’t going to get you anywhere with me, you know.”</i> Miranda polishes off the rest of her drink, then slams the empty tankard on the table. It takes a couple of tries for her to get Vaughn’s evidence folded up again, but at last she manages it. <i>“Thanks for passing this along and thinking of me, though. I’ll definitely remember this.”</i>", parse);
miranda.relation.IncreaseStat(100, 5);
Gui.PrintDefaultOptions();
}, enabled : true,
});
options.push({ nameStr : "Lie",
tooltip : "What’s a little white lie? Justice is served, and you don’t want to see the inside of a cell.",
func() {
Text.Clear();
Text.Add("Right. You quickly try and think of a plausible lie, and tell Miranda that you got the evidence off one of the den’s employees who’s harboring a grudge against his current boss. Now, you have to watch out for your informants, so you’re not going to tell Miranda just <i>who</i> it is, but suffice to say that while it took a little effort, it certainly wasn’t impossible for said informant to get the bill of sale.", parse);
Text.NL();
Text.Add("<i>“That’s it?”</i> Miranda’s replacement drink arrives, and the dobie takes it in hand, peering into the beer’s murky, foamy depths before quaffing half the tankard in one go. <i>“And here I was, thinking you were going to cook up some cock-and-bull story full of details, instead of just that.”</i>", parse);
Text.NL();
Text.Add("What? Were you supposed to have done that? You thought to keep it short and to the point, since you know that she’s not the kind to take nicely to any kind of bullshitting on anyone’s part.", parse);
Text.NL();
Text.Add("<i>“No, no. That’s actually how a good number of stakeouts get started in the first place - someone we know and trust comes up and tips us off. Much like what you’re doing right now, although of course I haven’t known you as long as some of those ‘good citizens’ we know.”</i>", parse);
Text.NL();
Text.Add("But she believes that your information is good?", parse);
Text.NL();
Text.Add("<i>“The times, the locations… right down to the patrol route, it all checks out. You couldn’t have come up with this on your own, [playername], you weren’t at the muster when we all discussed these. You must’ve gotten your hands on this somehow, and it wasn’t from one of us.”</i> Miranda nods, then polishes off the rest of her drink. <i>“Although I’ll say, if I get egg - or worse - on my face because of you, then you know who I’m going to be looking for…”</i>", parse);
miranda.relation.IncreaseStat(100, 3);
Gui.PrintDefaultOptions();
}, enabled : true,
});
Gui.Callstack.push(() => {
Text.NL();
Text.Add("Right. You sip at your drink, and watch Miranda shuffle out of her seat. She’s going already?", parse);
Text.NL();
Text.Add("<i>“Terrell, the bastard…I’d love to stay and drink some more, [playername], but this is more important than you’d imagine. Aria’s tits, we’re the <b>City Watch</b>, not the Royal Guard. We may not have fancy livery or talk all fancy, but we’ve got what counts. Our swords may not be shiny, but they’re damn well sharp - and most importantly, we’re supposed to have each others’ backs.”</i>", parse);
Text.NL();
Text.Add("With that, Miranda reaches into her pockets and draws out a handful of coins. <i>“For you,”</i> the dobie says, muttering to herself. <i>“Pay for my drink and the broken crap, and buy yourself a couple of drinks, okay? You’ve just done me a big favor. Now, if you don’t mind, I’ve got some heads to crack…”</i>", parse);
Text.NL();
Text.Add("You watch Miranda storm off, and the palpable heaviness in the air lifts with her passing. Yeah… regardless of what happens next, Terrell’s fate isn’t one that you’d wish upon anyone. By the look of things, you can probably head back to Vaughn and tell him of your success, even if you didn’t come by it the way he expected.", parse);
Text.Flush();
if (miranda.Attitude() < MirandaFlags.Attitude.Nice) {
miranda.flags.Attitude = MirandaFlags.Attitude.Nice;
}
TimeStep({hour: 1});
vaughn.flags.Met = VaughnFlags.Met.SnitchMirandaSuccess;
miranda.flags.Snitch |= MirandaFlags.Snitch.SnitchedOnSnitch;
miranda.snitchTimer = vaughn.taskTimer.Clone();
Gui.NextPrompt();
});
Gui.SetButtonsFromList(options, false, undefined);
} else {
Text.Add("<i>“Why’re you being so nice to me all of a sudden?”</i> Miranda practically snarls, the dobie eyeing you suspiciously as a serving wench brings the both of you your drinks - tankards of cheap beer, by the looks of it. <i>“You want something from me, don’t you?”</i>", parse);
Text.NL();
Text.Add("Well, it’s not that you <i>want</i> something from her, but if she could give you her attention for a moment… biting your lip, you draw out Vaughn’s evidence and hope that she’s in an accepting mood this evening.", parse);
Text.NL();
Text.Add("Unfortunately, she isn’t. Miranda turns away from you without even so much as looking at what’s in your hands or touching her drink. <i>“Not interested.”</i>", parse);
Text.NL();
Text.Add("Damn it, can she just get over it for a moment and pay you mind for ten minutes? She can go straight back to being ornery after hearing you out and you can take things from there, but this is important!", parse);
Text.NL();
Text.Add("<i>“Oh? Important?”</i>", parse);
Text.NL();
Text.Add("Yes, important.", parse);
Text.NL();
Text.Add("<i>“How important?”</i>", parse);
Text.NL();
Text.Add("<i>Very</i> important.", parse);
Text.NL();
Text.Add("Miranda snorts, the dobie folding her arms under her bosom. <i>“That important, eh? Well, if it’s so important to you, I’m sure you wouldn’t mind sucking me off. Can’t think straight, not with an itch in my dick, and if this crap is so important to you, then you can put up with it for a little while.”</i>", parse);
Text.NL();
Text.Add("Hey, wait a minute -", parse);
Text.NL();
Text.Add("<i>“Thought you said it was important,”</i> Miranda replies, the dobie’s muzzle twisting in a crude leer. <i>“So you can put up with your distaste of my dick and suck me off under the table here and now, or you can forget about whatever it is you want to bother me about.”</i>", parse);
Text.NL();
Text.Add("Seems like Miranda’s in a positively foul mood, and entreating with her any further is probably only going to make things worse; she’s clearly intent on punishing you for walking out of her. So… what are you going to do now? Are you going to give in to the dobie’s demand for you to blow her, or not?", parse);
Text.Flush();
// [Yes][No]
const options: IChoice[] = [];
options.push({ nameStr : "Yes",
tooltip : "If that’s what she wants…",
func() {
Text.Clear();
Text.Add("You wait in stony silence for a few minutes, the hubbub of the Maiden’s Bane swirling about the two of you, but Miranda really isn’t going to relent.", parse);
Text.NL();
Text.Add("Fine. If this is what it’ll take, then you’ll do it.", parse);
Text.NL();
Text.Add("<i>“So, it <b>is</b> that important to you,”</i> Miranda sneers. <i>“Get under and start sucking, slut.”</i>", parse);
Text.NL();
parse.l = player.HasLegs() ? "on all fours - the table’s not even high enough for you to sit on your knees -" : "and dirty";
Text.Add("Blowing a canid guardswoman under the table in a crowded bar… somehow, you get a distinct sense of deja vu about this whole thing. Well, you’ve decided to do this, time to get it over with; the less you dwell on it, the less it’ll hurt. You push aside your chair, get down [l] and crawl under the table. The floor of the Maiden’s Bane, while not exactly filthy, isn’t what you’d call clean, and it’s dark and ever so slightly damp under the old table. While all you can see from here is other peoples’ feet, you get the distinct impression that everyone else in the barroom can see you - and even if they couldn’t, it’s not as if they’re not going to figure out what’s going on.", parse);
Text.NL();
Text.Add("Before you know it, Miranda already has her shaft out, emerging from her uniform like a thick, juicy sausage. Guess she’s no stranger to the motions - with a lazy grunt, she spreads her legs wide open, letting you take in the full implications of what you’ve just agreed to do. Pushing forward her throbbing shaft, Miranda rubs it against your lips, letting you get a good taste of dobie dick, complete with a bead of pre-cum at the top. Is the thought of getting back at you making her <i>that</i> excited?", parse);
Text.NL();
parse.h = player.Hair().Bald() ? "head" : "hair";
if (player.Slut() < 50) {
Text.Add("You instinctively try to turn your head away at the sheer size of that massive member, but Miranda reaches under the table and grabs you by the [h], forcing your attention back where she wants it.", parse);
Text.NL();
Text.Add("<i>“Open up, you wimp. You picked the fight with me, now accept your punishment,”</i> she snarls, then yanks hard on your [h]. As you open your mouth to gasp from the sudden movement, the dobie guardswoman thrusts forward, plunging her cock between your lips and ramming it against the back of your throat, making you gag. Your eyes bulge at the sheer <i>girth</i> you’re forced to take in your maw, its taste coating your tongue and filling your nose, but Miranda doesn’t care. <i>“There, now suck! I'll beat you if you try to bite!”</i>", parse);
Text.NL();
Text.Add("Judging by the sheer vindictive edge in her voice, she clearly means every word of it, too. Feeling Miranda’s ramrod-straight shaft slip in and out of your gullet, you hold your proverbial nose and begin.", parse);
} else {
Text.Add("Despite how massive it is, your eyes can’t help but be drawn to Miranda’s member. While the more sensible portion of your mind - or at least, what’s left of it - helpfully suggests that putting that in your mouth probably isn’t the best of ideas, the rest of you has other ideas. Besides, if you’re going to have to do this, you might as well enjoy it.", parse);
Text.NL();
Text.Add("Seizing hold of that dobie dong, you let your fingers play over its heated, pulsating length even as Miranda pats you on the head like an animal.", parse);
Text.NL();
Text.Add("<i>“I thought you hated dick?”</i> the guardswoman jeers. <i>“Or is it just my dick that’s so disgusting to you? I don’t know whether I should be even more disgusted with you, or just plain honored.</i>", parse);
Text.NL();
Text.Add("<i>“Now start sucking, slut.”</i>", parse);
Text.NL();
Text.Add("She wants you to suck? Fine, you’ll suck alright.", parse);
}
Text.NL();
Text.Add("With a muffled moan, you relax your mouth and throat as best as you can to get the job done and give your tongue space to at least try and do <i>something</i>. It’s hard, considering that it’s hard to even breathe, ", parse);
if (player.sexlevel >= 3) {
Text.Add("but you at least manage to get some wiggle room around Miranda’s mountainous shaft and run your tongue along the base of her shaft as she thrusts back and forth.", parse);
Text.NL();
Text.Add("<i>“Not too shabby,”</i> Miranda grunts as she works away, her words punctuated by small gasps of breath. <i>“Knew you’d come around to my way of thinking sooner or later, slut.”</i>", parse);
} else {
Text.Add("and it’s quite the futile endeavor - your mouth simply isn’t flexible enough for that. Not as if you could protest, even if you’d the mind to - all you can do is to go with the flow and try your best to prevent yourself from choking, or even worse, throwing up.", parse);
}
Text.NL();
Text.Add("Miranda stifles a moan, her doggy dick hardening even more until you can distinctly feel every ridge and pulsing vein against your tongue and the roof of your mouth. There’s little doubt her intention is to make this short and sharp, but even so, you’re surprised when she picks up the pace, steady pounding turning into a frenzied ramming as if she were in a race to get herself off as quickly as possible.", parse);
Text.NL();
Text.Add("Clearly, Miranda’s decided that your grace period is over, and begins to skullfuck you vigorously, taking this opportunity to vent her accumulated frustrations on your person. You can’t quite see anything above the dobie’s waist, but by the way the chair she’s sitting on is creaking and the occasional thumping from the table’s surface above, she’s trying to steady herself; judging by how hard your head is being slapped back with each of Miranda’s thrusts, you’re not surprised.", parse);
Text.NL();
Text.Add("There’s not much you can do now but ride this one out - slightly disoriented by the rapid, violent movements your head and neck are being subjected to, you’re taken by surprise when Miranda cums hard and fast. Next thing you know, a meaty hand is pressing into your face, separating you from Miranda’s shaft with an audible pop.", parse);
Text.NL();
Text.Add("<i>“Oh no, you don’t get to swallow and hide it,”</i> the dobie growls. <i>“I want everyone in the barroom to see you painted all over. That should be a laugh.”</i>", parse);
Text.NL();
parse.arm = player.Armor() ? Text.Parse(" and gets into your [armor]", parse) : "";
Text.Add("Not that you have the time or presence of mind to reply - you can actually hear the drinks rattle on the table above you as Miranda blasts load after load of thick, steaming cum all over your face and [breasts]. It seeps into your clothing[arm], leaving a distinct slippery stickiness all over your [skin] before dripping onto the wooden floor. Whoever’s slated to clean this up afterwards is going to have a nasty time dealing with the thick pool of spunk that’s gathering about the table legs.", parse);
Text.NL();
Text.Add("<i>“Fine, we’re done. Get up. Clean yourself off if you want - there’s no way you’re making yourself look good now.”</i>", parse);
Text.NL();
Text.Add("It’s over already? That was quicker than you’d expected, if rather more intense. Still reeling from the intensity of the facefuck you’ve just received, cum dribbling from your chin and neck, you shuffle out from under the table and wipe yourself off with the back of your hand. As Miranda predicted, the effort is pretty much useless at actually getting you to anywhere nearing presentable, and it results in is more people staring at you. Thankfully - or not - the onlookers have the good graces to turn away quickly when they realize what’s happening, leaving you and Miranda to stew in the aftermath of your hasty blowjob.", parse);
Text.NL();
Text.Add("<i>“Right.”</i> Miranda grins nastily at you, then leans back in her seat before polishing off the last of her beer. You note that she hasn’t bothered to put her dick back in her pants yet, perhaps to mock you. <i>“Let’s see what you’ve got for me, then. This is going to be good.”</i>", parse);
Text.NL();
Text.Add("What? Oh, right. What you came here for in the first place. Grimacing, you pull out Vaughn’s evidence once more, and slap it down on the table. By some miracle, it’s managed to escape unscathed, and Miranda takes it in her hands before unfolding it. The dobie’s lips move silently as she scans the paper - you hadn’t thought it possible that she could be any madder than she was already, but her expression steadily darkens like an ominous stormcloud. By the time she’s finished poring over the paper, Miranda looks practically rabid and ready to kill at the drop of a hat.", parse);
Text.NL();
Text.Add("<i>“Another drink!”</i> she barks at the closest serving wench. <i>“Not the cheap crap, but give me the distilled stuff from the cellar. And make it quick.”</i>", parse);
Text.NL();
Text.Add("As the poor girl scurries off, Miranda reads through Vaughn’s evidence once more, only pausing to shoot you the occasional suspicious glance through narrowed eyes. When the drink arrives, Miranda waves off the girl as she attempts to serve, snatches the freshly opened bottle and chugs several mouthfuls in one go.", parse);
Text.NL();
Text.Add("<i>“No. This can’t be right. It can’t be... but it explains so much. How each and every one of the dens we hit had managed to pack in their stuff by the time we came. The damn bastards, they seemed overly smug… there was a snitch amongst those who’d turned up at muster for the briefing the other day, and I think I damn well know who.</i>", parse);
Text.NL();
Text.Add("<i>“How the fuck did you get your hands on this?”</i>", parse);
Text.NL();
Text.Add("The only thing that’d probably make Miranda any more pissed than she currently is would be to tell her that you’re with the outlaws, and yet you know she’s got a nose for bullshit. You pare down the story as much as you think’s necessary, saying that your source would rather stay unnamed, but you’ll take responsibility for the evidence’s veracity if needed. Miranda doesn’t look wholly convinced, but at last she nods with a soft growl. It’s a little surprising at how easily she swallowed your words, but you <i>did</i> just blow her, and it’s clear she’s not exactly balanced at the moment.", parse);
Text.NL();
Text.Add("<i>“Fine. I get it. Most people who tip us off don’t want to be named, because snitches get stitches, as everyone knows - and I’m going to personally give some to that snitch the moment I get back to the yard. Them gambling dens have enough problems with those crooks squabbling over who gets to be top dog, this is probably one of those again. If you’re going to take responsibility for this…”</i> Miranda lets her voice trail off for a moment. <i>“Fuck it. I can’t believe this, but there’s no doubt it’s his handwriting. I’d recognize that chicken scrawl anywhere.”</i>", parse);
Text.NL();
Text.Add("You put on your most innocent face. Whose handwriting?", parse);
Text.NL();
Text.Add("<i>“That’s for me to know and for you to shut the fuck up about. This is watch business now, and it goes all the way up to the commander.”</i> By now, Miranda’s dick has softened enough for her to shove it back into her pants, which she does before standing up. <i>“I’m getting back to the watch house. No time to waste.”</i>", parse);
Text.NL();
Text.Add("With that, the dobie kicks in her chair and makes to leave, but not before turning back to you.", parse);
Text.NL();
Text.Add("<i>“You know, [playername], you sucked me off and you gave me a lead into why our stings have been coming up empty all the time of late. If this goes down right… well, this is bigger than just you and me. I’m willing to call it even between us if you are.", parse);
Text.NL();
Text.Add("Huh, now that’s a surprise. You wouldn’t have imagined it’d be like Miranda to let you off this easily, but she did say the words loud and clear. It’s an opportunity that you might not get easily again, should you pass it up…", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.SnitchMirandaSuccess;
miranda.flags.Snitch |= MirandaFlags.Snitch.SnitchedOnSnitch;
miranda.flags.Snitch |= MirandaFlags.Snitch.Sexed;
miranda.snitchTimer = vaughn.taskTimer.Clone();
TimeStep({hour: 2});
// [Yes][No]
const options: IChoice[] = [];
options.push({ nameStr : "Yes",
tooltip : "Yeah, you’ve had enough of this. Time to call the score even… for now.",
func() {
Text.Clear();
Text.Add("Fine, fine. Having Miranda mad at you all the time was exhausting on the nerves, anyways - getting her off your back would be a small relief.", parse);
Text.NL();
Text.Add("<i>“Hmph. Don’t think that this means I’m going to start wagging my tail when you get close. All we’re now is even - and hopefully, you’ve learned better than to piss me off again.”</i> Miranda smacks one meaty fist against a palm. <i>“Now, if you’ll excuse me, I have some business to take care of.”</i>", parse);
Text.NL();
Text.Add("With that, she turns and storms away, leaving you alone in the Maiden’s Bane.", parse);
Text.Flush();
miranda.flags.Attitude = MirandaFlags.Attitude.Neutral;
miranda.relation.IncreaseStat(100, 5);
Gui.NextPrompt();
}, enabled : true,
});
options.push({ nameStr : "No",
tooltip : "Refuse to call it quits.",
func() {
Text.Clear();
Text.Add("Miranda shows you her teeth. <i>“Well, if that’s the way you want it, asshole. More fun for me, I suppose. Guess I’ll be facefucking your slutty little mouth for a little while longer, or maybe that’s what you want? Not now, though. I’ll deal with you later, after I’ve finished cracking some skulls back at the yard.”</i>", parse);
Text.NL();
Text.Add("With that, the dobie turns and storms off, leaving you wondering if continuing to receive Miranda’s enmity was the best of ideas.", parse);
Text.Flush();
Gui.NextPrompt();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
}, enabled : true,
});
options.push({ nameStr : "No",
tooltip : "No. You’re not standing for this. You’ll take your chances at the watch headquarters.",
func() {
Text.Clear();
Text.Add("Screw this. While you might have expected that Miranda would be a hard sell, you hadn’t expected her to be <i>this</i> vindictive. Leaving your drink untouched, you quickly pay for it and stand up, making for the door.", parse);
Text.NL();
Text.Add("<i>“Running away again?”</i> Miranda jeers from behind you. You don’t look back. <i>“You’re really that afraid of a dick? It’s not as if it’ll bite you.”</i>", parse);
Text.NL();
Text.Add("No, it might not bite you, but it’ll damn well do worse. Ah, fuck - this was a bad idea, anyway. You’ll just take your chances at the watch headquarters.", parse);
Text.Flush();
TimeStep({minute: 30});
miranda.flags.Snitch |= MirandaFlags.Snitch.RefusedSex;
Gui.NextPrompt();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
}
}
// Triggered via [Evidence] - Break into the watchmens’ lockers and plant the evidence. while in the City Watch area.
export function PlantEvidence() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const terry: Terry = GAME().terry;
let parse: IParse = {
playername : player.name,
};
parse = terry.ParserPronouns(parse);
Text.Clear();
Text.Add("Right. No moment like the present. To say that trying to get up to shenanigans here makes one tense, when the place is crawling with watchmen day and night - well, that’s an understatement if you ever heard of one. Still, you’ve got to keep your cool - if anyone starts asking what you’re doing here, you’ll probably say… hmm… that’s you’re looking for Miranda. Yeah, that sounds about as good a cover story as you’ll be able to pass off.", parse);
Text.NL();
Text.Add("Finding the locker room isn’t too hard, though. You figure that it’s got to be reasonably close to the barracks for easy access by the watchmen coming on and off shift, so that’s where you begin. Thankfully, most of the off-duty watchmen are currently taken in by a running game of Cavalcade, so it’s relatively easy to slip past them and deeper into the building. Sure, you may not have done anything yet, but the fewer people remember that you were here, the better. With that thought in mind, you nip into the locker room, doing your best to look like you have every right to be there even though you aren’t formally with the City Watch.", parse);
Text.NL();
Text.Add("The room itself is plain and sparse. Clearly, it was built when the watch was much smaller in strength than it’s today. While the lockers aren’t actually rusting - the City Watch has at least <i>that</i> much discipline - they’ve nevertheless gained a tarnish with age that no amount of metal polish and lemon juice will remove. This, of course, might have something to do with how closely they’re packed together in neat rows, with barely enough space for one to move between them comfortably.", parse);
Text.NL();
Text.Add("The middle of the room is occupied by a number of benches, on which several off-duty watchmen are lounging and chatting.", parse);
Text.NL();
Text.Add("You weigh your odds as you scan the names on the lockers, trying to find Terrell’s - no such luck yet, although you do spot one with the name “Miranda” stenciled on it. The cramped conditions in the locker room probably mean that you’ll have some modicum of cover while trying to break into his things, although how effective it’ll be when the place is crawling with watchmen coming and going is another matter.", parse);
parse.comp = party.Num() === 2 ? party.Get(1).name : "your companions";
if (party.Num() > 1) {
Text.Add(" You could use [comp] to obscure the view along the long, narrow lines of lockers, too.", parse);
}
Text.NL();
Text.Add("Then there’s the matter of actually getting into Terrell’s things. By the looks of it, each locker is uniform in both make and lock, and a brief inspection of the locks reveals them to be of a simple turnbolt mechanism. There’s enough space that you might be able to slide a card or something between frame and door to jimmy the lock both ways, or if you’ve the aptitude to do so, you could try picking the lock proper. Either that, or maybe if you had enough skill, you could magic the lock open, will the bolt to rise or play with a bit of air…", parse);
Text.NL();
if (party.InParty(terry)) {
Text.Add("Of course, why bother with all this when you’ve got Terry with you? [HeShe]’s a professional thief, you could just ask [himher] to do the job for you and get it over with.", parse);
Text.NL();
}
Text.Add("While most of the off-duty watchmen might be occupied with the dice game out in the barracks, anyone might come around any time and start asking inconvenient questions. You probably don’t have too much time to make your move, so you ought to choose your next action carefully.", parse);
Text.Flush();
const rogue = Jobs.Rogue.Unlocked(player);
// [Lock][Magic][Terry]
const options: IChoice[] = [];
options.push({ nameStr : "Lock",
tooltip : Text.Parse("[Jimmy] the lock.", {Jimmy: rogue ? "Pick" : "Jimmy"}),
func() {
Text.Clear();
if (rogue) {
Text.Add("Well, no time to waste. You stoop and quickly inspect the lock one last time, then get to work. Having been trained in the ways of the rogue, you find the attempt easier than most might expect, but success is by no means guaranteed.", parse);
} else {
Text.Add("Well, you aren’t making any progress standing around like this. Stooping to give the lock one last inspection, you work as best as you can to get the bolt lifted. The locker may not be the most sturdily made, but it’s still a worthy enough opponent that it might give you a little trouble.", parse);
}
Text.NL();
let dex = player.Dex() + Math.random() * 20;
dex += rogue ? 20 : 0;
const check = 60;
if (GetDEBUG()) {
const r = rogue ? " (bonus for Rogue)" : "";
Text.Add(`Dex check: ${dex}${r} vs ${check}`, undefined, "bold");
Text.NL();
}
// #lock success
if (dex >= check) {
Text.Add("Moments tick by, and with each one that passes, your heart beats a little faster. Is someone going to look down the line of lockers and see what you’re up to? Your fingers begin to shake a little, but you get things under control, and at last, at last - there’s a faint but satisfying <i>thunk</i> of the bolt lifting and you take hold of the locker door and pull it open.", parse);
Text.NL();
Text.Add("Right. Where to put the evidence so that it looks natural? You eye the locker’s contents - a few sets of uniforms, cleaning tools for said uniforms, what looks like a dried snack in a tied paper bag - ah, looks like there’re some notebooks near the back. You flip through them, hoping to find something incriminating, but Terrell clearly isn’t enough of an idiot to leave something like that in his locker moments before the inspection. Boy, is he going to be surprised.", parse);
Text.NL();
Text.Add("Stuffing Vaughn’s evidence between the notebook’s pages, you quickly set everything back as it was - slipping the deadbolt down is far easier than lifting it, and you waste no time slipping out of the locker room and from the watch headquarters altogether. The resulting fireworks might be fun to watch, but they’re probably much safer when viewed at a distance - you don’t want to risk anyone remembering that you were around earlier in the day.", parse);
Text.NL();
Text.Add("With nothing left for you here, perhaps it’d be best to report back to Vaughn and let him know the job’s done.", parse);
vaughn.flags.Met = VaughnFlags.Met.SnitchWatchhousSuccess;
} else {
Text.Add("Perhaps too worthy an opponent, in fact. Fumbling leads to frustration, which only leads to more fumbling - while you manage to lift the bolt slightly on a couple of tries, it always evades your efforts at the last moment and falls down onto the latch.", parse);
Text.NL();
Text.Add("You’re running out of time, and keenly aware of that fact. The watchmen in the barracks outside are going to be finishing their game soon, judging by the sound of their raised voices and enthusiastic whoops, and your breath whistles through your gritted teeth as your final attempt subsides into failure.", parse);
Text.NL();
Text.Add("Footsteps. The locker room will be flooded with tired, exhilarated watchmen in a matter of moments - even if you’d the locker door open before you right now, there’d be no time to plant the evidence. Quickly, you nip away from the line and slip out just in time to avoid a dog-tired patrol stomping in from the streets.", parse);
Text.NL();
Text.Add("You’re probably not going to get another chance to be alone in the barracks for some time now… but at least you tried. Best to head back to Vaughn and hope he isn’t too hard on you for your failure.", parse);
vaughn.flags.Met = VaughnFlags.Met.SnitchWatchhousFail;
}
Text.Flush();
TimeStep({minute: 30});
Gui.NextPrompt();
}, enabled : true,
});
const mage = Jobs.Mage.Unlocked(player);
if (mage) {
options.push({ nameStr : "Magic",
tooltip : "Try and get the bolt to lift with a bit of magic.",
func() {
Text.Clear();
parse.phisher = player.mfTrue("his", "her");
Text.Add("Right. Getting a bolt to move quietly and silently… that should be child’s play for someone who can conjure up fire with a snap of [phisher] fingers, right? You size up your opponent one last time - while it would be easier to blast the door open as opposed to the finesse required to stealthily lift the bolt, it’d also create no end of unfortunate repercussions you’d rather avoid.", parse);
Text.NL();
Text.Add("Well, you’re wasting time standing around here. Narrowing your eyes, you focus your concentration and begin.", parse);
Text.NL();
let mag = player.Int() + Math.random() * 20;
const magStage2 = GlobalScenes.MagicStage2();
if (magStage2) { mag += 20; }
const check = 50;
if (GetDEBUG()) {
const m = magStage2 ? " (bonus for tier 2 magic)" : "";
Text.Add(`Int check: ${mag}${m} vs ${check}`, undefined, "bold");
Text.NL();
}
if (mag >= check) {
Text.Add("The going is slow but steady. Too quickly and you’ll make a whole lot of noise, too slow and you might lost your grip, sending the bolt clattering back into place. Through the narrow slit between door and frame, you watch a glint of metal rise and finally, a gentle tug on the door has the locker open and bare for your perusal.", parse);
Text.NL();
Text.Add("Great. Time to find a good place to plant the evidence before you’re discovered - Terrell’s locker is full of spare uniform sets, a boot-cleaning kit, a small tin of brass polish, what looks like an oily snack in a brown paper bag - entirely mundane and boring stuff. You’re just about considering whether to simply slip the papers into the breast pocket of his uniform when you notice a small stack of notebooks buried near the back. ", parse);
Text.NL();
Text.Add("Now <i>those</i> look interesting. While flipping through them doesn’t reveal anything incriminating in and of itself amidst the pages - mostly old patrol logs and notes - it’d make a good and believable place for you to plant Vaughn’s papers. Wasting no time, you slip them between the notebooks’ pages, then do your best to arrange everything like it was before closing the door. Turning the bolt down is easy - all you need is a little push, and it falls back into the latch with a clang.", parse);
Text.NL();
Text.Add("Maybe a little too loud for comfort, but you don’t need to be too worried about that anymore. Quickly, you nip out of the locker room and through the barracks, and not one moment too soon; the watchmen are just about done with their game of dice, and various whoops of excitement denote the conclusion of the last round. You don’t look back - best that everyone forget that you were ever here today…", parse);
Text.NL();
Text.Add("Well, that seems to be that. You’re not about to hang around when the fireworks go off - perhaps you should head back to the outlaws’ and report in to Vaughn. It’d probably be safer for you that way.", parse);
vaughn.flags.Met = VaughnFlags.Met.SnitchWatchhousSuccess;
} else {
Text.Add("Try as you might, your concentration keeps slipping - that damned bolt will rise just a little, then teasingly plonk straight back onto the latch. Not that the mounting frustration is doing any wonders for your concentration, and that in turn causes more mistakes until your breath is coming through your gritted teeth. You don’t have much time to do this, and you’re keenly aware of that fact - the locker room being sparsely occupied right now is probably a lucky fluke, all things considered.", parse);
Text.NL();
Text.Add("All of a sudden, there’s a loud clang from the lock, the sound of the bolt striking something with considerable force. Had you meant to do that? You don’t remember so, but you must have - and with quite the amount of noise, too.", parse);
Text.NL();
Text.Add("Footsteps, not just from the barracks, but within the room itself - perhaps you ought to have been paying more attention to your surroundings, but it’s too late for that now as you nip out from the line of lockers and out of the locker room even as the footsteps begin to converge upon Terrell’s locker. Damn it! For a second or two, blowing the locker’s door wide open seems like a good idea in retrospect…", parse);
Text.NL();
Text.Add("No time to lose, though - the watchmen know something’s up, and you’d rather not have anyone inconveniently remember that you were snooping about today. It’s only when you’re out of the watch house and on the street by the walls that you dare to catch your breath and look back.", parse);
Text.NL();
Text.Add("Well, fireworks sure’ve went off, but not quite the ones you expected. Seems like there’s no hope of successfully getting the job done now, not with the City Watch alerted to your shenanigans - perhaps it’d be best if you headed back to Vaughn and see what he has to say.", parse);
vaughn.flags.Met = VaughnFlags.Met.SnitchWatchhousFail;
}
Text.Flush();
TimeStep({minute: 30});
Gui.NextPrompt();
}, enabled : true,
});
}
if (party.InParty(terry)) {
options.push({ nameStr : "Terry",
tooltip : "Have Terry open the locker for you.",
func() {
Text.Clear();
Text.Add("<i>“Really?”</i> Terry moans in an exaggerated display of exasperation. <i>“That? You want me to work on that flimsy old thing? My talents are wasted here, I tell you.”</i>", parse);
Text.NL();
Text.Add("Well, if it’s that simple, [heshe] should have no trouble getting it done. Or do you have to command [himher] to do it?", parse);
Text.NL();
parse.bitterly = terry.Relation() < 30 ? " bitterly" : "";
parse.MasterMistress = player.mfTrue("Master", "Mistress");
parse.foxvixen = terry.mfPronoun("fox", "vixen");
Text.Add("<i>“Yeah, yeah,”</i> Terry replies, unshouldering [hisher] pack, chuckling[bitterly]. <i>“Your wish is my command, <b>[MasterMistress]</b>. Only problem would be all these eyes about, they’re making me nervous. Cover me while I work, will you?”</i>", parse);
Text.NL();
Text.Add("You stand on one side, hopefully obscuring Terry from anyone happening to peek down the long row of lockers. The [foxvixen] works away industriously, and in about half a minute, there’s a faint click and the locker door swings open.", parse);
Text.NL();
Text.Add("<i>“All done. As I said, child’s play to anyone who knows what [heshe]’s doing.”</i>", parse);
Text.NL();
Text.Add("You pet Terry on the head and praise [himher] for being such a clever little [foxvixen]. Certainly, choosing to take [himher] along on this little field trip was a good decision.", parse);
Text.NL();
Text.Add("<i>“Yeah, yeah.”</i> Terry shrugs off the praised with feigned indifference. <i>“Hurry up before someone notices that we’re not supposed to be here, will you?”</i>", parse);
Text.NL();
Text.Add("Right, right. Flinging open the locker, you’re greeted with a - well, it’s not a mess, but you wouldn’t call it neat, either. A couple sets of uniform take up most of the space, along with some needle and thread, boot polish, a brush… pretty standard for a watchman’s locker, really.", parse);
Text.NL();
Text.Add("You root around a bit, trying to find where Terrell keeps his personal belongings, and find a small corner in which a couple of notebooks have been stashed, along with a couple of letters of a more personal nature. Flipping through the notebooks reveals nothing incriminating in and of itself - mostly that the fellow’s pretty good at writing reports - but it looks like as good a place as any to plant Vaughn’s evidence.", parse);
Text.NL();
Text.Add("<i>“Hurry up!”</i> Terry whispers from beside you. <i>“Make up your mind!”</i>", parse);
Text.NL();
Text.Add("[HeShe] has a point. Seeing no better spot, you stick the evidence in between the notebook’s pages and quickly and quietly shut the locker door. Terry works [hisher] magic with [hisher] tools once more, and the door’s firmly locked again.", parse);
Text.NL();
Text.Add("Mission accomplished, time to get out of here - bringing Terry and [hisher] expertise along really made this a whole lot smoother than it could’ve been otherwise. Some of the watchmen still at their dice game look up at you as you leave, and you give them what you hope is a friendly smile and wave before slipping out of the watch headquarters. You shouldn’t be anywhere nearby when the sparks start to fly - best to head back to Vaughn and see what he has to say.", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.SnitchWatchhousSuccess;
TimeStep({minute: 30});
Gui.NextPrompt();
}, enabled : true,
});
}
Gui.SetButtonsFromList(options, false, undefined);
}
export function DebriefAvailable() {
const vaughn: Vaughn = GAME().vaughn;
return vaughn.flags.Met > VaughnFlags.Met.OnTaskSnitch &&
vaughn.flags.Met < VaughnFlags.Met.CompletedSnitch;
}
export function Debrief() {
const player: Player = GAME().player;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
if (vaughn.flags.Met === VaughnFlags.Met.SnitchMirandaSuccess) {
Text.Add("<i>“Right! So you’re back,”</i> Vaughn says, greeting you with a tip of his hat. <i>“I heard from our eyes on the street that quite the raucous caucus took place down at the Watch headquarters a little while ago. Quite the magnificent one, by all accounts. I wish I’d been there to see it myself, but duty calls and all.”</i>", parse);
Text.NL();
Text.Add("Why, there was some kind of shake-up? Oh dear. It certainly had nothing to do with you; it’s not as if you were even anywhere near the place when things went down.", parse);
Text.NL();
Text.Add("Vaughn chortles, a sharp yipping sound. <i>“Oh, that’s true all right. Seems like one of their members somehow managed to get her hands on a certain piece of evidence, then made a beeline for the commander’s office. I hear there was a bit of a dust-up involved, and Terrell, the poor bastard, is currently stuck with the drunks and shifts in a holding cell while his case is being looked at.”</i>", parse);
Text.NL();
Text.Add("Corruption in the City Watch? How terrible. Good thing that they were willing to clean up their act, and all the better that it was one of their own who did the unmasking.", parse);
Text.NL();
Text.Add("<i>“Either way, the bastard’s not going to be harassing the poor and downtrodden for a while yet. Permanently, I hope.”</i> Vaughn takes a deep breath, and lets it all out in a huge, contented sigh. <i>“You know, [playername], that was quite unexpected of you. I wouldn’t have gone to the City Watch myself, even if they’re less crooked than the Royal Guard.”</i>", parse);
Text.NL();
Text.Add("Oh, but you didn’t just go to the watch. You went to one of them whom you trusted to keep to the straight and narrow. That’s a big difference there.", parse);
Text.NL();
Text.Add("<i>“Indeed. Watchmen who don’t take bullshit were never that many to begin with, and they’re practically a dying breed nowadays.</i>", parse);
VaughnTasksScenes.Snitch.DebriefSuccess(parse);
} else if (vaughn.flags.Met === VaughnFlags.Met.SnitchWatchhousSuccess) {
Text.Add("<i>“Ah, you’re back,”</i> Vaughn says, greeting you with a tip of his hat. The fox-morph seems uncharacteristically merry, and you have a guess as to why. <i>“Did you have a good time?”</i>", parse);
Text.NL();
Text.Add("It was quite the wonderful time. You didn’t dare to hang around to watch the fireworks like he suggested, but unless Terrell got back to his locker, found where you’d hidden the evidence and disposed of it - quite the unlikely case - then one could consider this mission accomplished.", parse);
Text.NL();
Text.Add("<i>“And so it was. We gave instructions to our people on the street to keep our dear friend busy for the day, up to the point where he was almost late for the inspection. Good times, good times. By all accounts, the reaction was quite… intense on both sides. No one likes a snitch, and that goes double for watchmen. Our people didn’t manage to find out what happened afterwards, but one can only assume he’s going to be off the streets for a little while yet, or at least until the investigation’s concluded.</i>", parse);
VaughnTasksScenes.Snitch.DebriefSuccess(parse);
} else {
Text.Add("As you approach, Vaughn tilts his head up to look you in the eye. <i>“Welcome back, [playername]. Allow me to extend my condolences.”</i>", parse);
Text.NL();
Text.Add("What, does he know already?", parse);
Text.NL();
Text.Add("<i>“We had people watching the watch house for activity, good or bad. They’re rather quick and reliable at what they do - I got word a couple hours before you arrived.”</i>", parse);
Text.NL();
Text.Add("Ugh. That’s fast.", parse);
Text.NL();
Text.Add("<i>“And perhaps now you understand why a son of a bitch like Terrell pissing off the little people we rely on is such a big deal to us.”</i>", parse);
Text.NL();
Text.Add("Yeah, about that…", parse);
Text.NL();
Text.Add("Vaughn shrugs and waves off your imminent apology. <i>“Eh, the job was a crapshoot anyways. Getting into the watch house and planting it… Maria could’ve managed it, but some of the watchmen know her face. Still, I’d have hoped that you’d be able to do it, but you tried and failed. Yeah, sure, the boss-man would say that you failed anyway, but you didn’t chicken out, and that’s a point in your favor.”</i>", parse);
Text.NL();
Text.Add("How nice of him. Well, what happens now?", parse);
Text.NL();
Text.Add("<i>“We find another way to use this damning evidence. Either that, or if it takes too long… as I said, corrupt bastards like Terrell will take all that they think they can grab, and he’s not the kind who’s smart enough to cover his tracks consistently. I have a feeling that he’ll slip up again before long.</i>", parse);
VaughnTasksScenes.Snitch.DebriefFailure(parse);
}
}
export function OutOfTime() {
const vaughn: Vaughn = GAME().vaughn;
return VaughnTasksScenes.Snitch.OnTask() && vaughn.taskTimer.Expired();
}
export function DebriefOutOfTime() {
const player: Player = GAME().player;
const outlaws: Outlaws = GAME().outlaws;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
Text.Add("By the time you can see Vaughn’s face, it’s clear that he’s not happy with you. The fox-morph is practically fuming as he eyes your approach, his hat shifting slightly as the ears underneath swivel this way and that.", parse);
Text.NL();
Text.Add("<i>“So, finally decided to turn up, did you?”</i>", parse);
Text.NL();
Text.Add("Now, wait a second here. If -", parse);
Text.NL();
Text.Add("<i>“Either you chickened out, or you couldn’t be bothered, <b>or</b> you’re the kind who thinks that nothing important will ever happen if you don’t personally go there and make it happen,”</i> Vaughn snaps in reply, cutting off your words. <i>“I’d rather believe the first of you rather than the third, ‘cause while I can understand a coward, I’ve no patience for assholes.”</i>", parse);
Text.NL();
Text.Add("Yeah, he’s not in a listening mood, and to be fair, he has every right to be mad with you.", parse);
Text.NL();
Text.Add("<i>“If you couldn’t turn up, you needn’t have given your word. All it’d have taken would be to say ‘hey, I don’t think I can do this, pass it along to someone else.’ That’s all it’d have taken. Now, we’ve got to clean up your mess, and I don’t like it one bit.</i>", parse);
Text.NL();
Text.Add("<i>“Sure, as I said, corrupt bastards like Terrell will take all that they think they can grab, and he’s not the kind who’s smart enough to cover his tracks consistently. I have a feeling that he’ll slip up again before long. Still, that doesn’t excuse you not showing up - we had people watching the watchmen for hours on end, waiting to see the fireworks, and they never got the show that they were promised.”</i>", parse);
Text.NL();
Text.Add("He had people watching?", parse);
Text.NL();
Text.Add("<i>“Well, yes, and they were more than willing to come, ‘cause they thought that the bastard was going to get his dues. Seems like they were disappointed, but them’s the breaks.</i>", parse);
outlaws.relation.DecreaseStat(0, -4);
VaughnTasksScenes.Snitch.DebriefFailure(parse);
}
export function DebriefSuccess(parse: IParse) {
const party: Party = GAME().party;
const outlaws: Outlaws = GAME().outlaws;
const vaughn: Vaughn = GAME().vaughn;
Text.NL();
Text.Add("<i>“Well, that seems like that’s that,”</i> Vaughn says. <i>“Your help’s much appreciated, and with any luck, Terrell’s going to find himself in quite a bit of hot soup for the foreseeable future. Justice is served, righteousness prevails, and all that other stuff I’m supposed to say but I was never really very good at.”</i>", parse);
Text.NL();
Text.Add("Oh, it was a pleasure.", parse);
Text.NL();
Text.Add("<i>“Dunno if it’s a pleasure or not, but it damn well felt good to receive the news of the bastard’s demise. Here, it’s not much, but I set these aside for you from the last consignment which came in. We don’t have any actual <b>money</b> to spare at the moment, so goods is all that I can reward you with.”</i>", parse);
Text.NL();
Text.Add("Received 5x Energy Potions.<br>", parse, "bold");
Text.Add("Received 5x Speed Potions.", parse, "bold");
Text.NL();
party.Inv().AddItem(CombatItems.EPotion, 5);
party.Inv().AddItem(CombatItems.SpeedPotion, 5);
outlaws.relation.IncreaseStat(100, 3);
Text.Add("<i>“I think that’s all I have for you at the moment, [playername]. Stay safe out there, and check back in sometime with me. I may have something else for you later on.”</i>", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.CompletedSnitch;
TimeStep({hour: 1});
Gui.NextPrompt();
}
export function DebriefFailure(parse: IParse) {
const vaughn: Vaughn = GAME().vaughn;
Text.NL();
Text.Add("<i>“One more thing. You still have the evidence, don’t you?”</i>", parse);
Text.NL();
Text.Add("Well, yes, at least you still have that. Vaughn sticks out his hand, and you press the paper into his gloved palm. He mumbles something that’s neither here nor there, then snorts.", parse);
Text.NL();
Text.Add("<i>“Fine. At least we still can probably put this to good use in due time… although that time should be soon, and the plan probably won’t involve you, [playername]. You had your break and you blew it, so that’s that; at least we’re more than capable of rolling with the punches here.</i>", parse);
Text.NL();
Text.Add("<i>“Now, I’ve got nothing else for you, so just move along. Maybe in the future you’ll be given the opportunity to get back into the boss-man’s good graces, but right now, I’ve got to get Maria over and discuss how to best go about cleaning up your mess.”</i>", parse);
Text.NL();
Text.Add("With that, he turns away from you and storms into the darkness of the camp, leaving you to stew in your failure.", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.CompletedSnitch;
TimeStep({hour: 1});
Gui.NextPrompt();
}
}
export namespace Poisoning {
export function Available() {
const vaughn: Vaughn = GAME().vaughn;
if (vaughn.flags.Met >= VaughnFlags.Met.CompletedPoisoning) { return false; }
return true;
}
export function OnTask() {
const vaughn: Vaughn = GAME().vaughn;
return vaughn.flags.Met === VaughnFlags.Met.OnTaskPoisoning;
}
export function Completed() {
const vaughn: Vaughn = GAME().vaughn;
return vaughn.flags.Met >= VaughnFlags.Met.CompletedPoisoning;
}
export function Start() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
playername : player.name,
};
Text.Clear();
Text.Add("<i>“This one’s a little more dangerous than your previous assignment,”</i> Vaughn tells you after a moment’s contemplation. <i>“You’d be in considerable personal risk - we’re looking at an extended stay inside of a cell if you’re nicked, at least. I wouldn’t blame you if you wanted to back out and leave it to our more experienced operatives.”</i>", parse);
Text.NL();
Text.Add("Well, what’s the big deal? Or is he telling you this to lure you in with the temptation of forbidden fruit?", parse);
Text.NL();
Text.Add("Vaughn chuckles. <i>“Please, [playername]. I’m not so devious - Maria or the boss-man might be, but I’m as stiff and straight as a stick in the mud. No, here you’ll actually be committing quite the serious crime, so I’d rather you know what you’re getting yourself into before I send you out to do it.”</i>", parse);
Text.NL();
Text.Add("For the last time, you wouldn’t have said yes if you didn’t mean it. What’s he plotting, anyway? Assassination? Grand robbery? High treason?", parse);
Text.NL();
Text.Add("The easygoing smile vanishes from Vaughn’s face at those words. <i>“I’ve got that last one covered well enough, so please don’t joke around like that. No, I’d simply like you to poison someone. Want to hear the details?”</i>", parse);
Text.NL();
Text.Add("Oh. Uh… yeah, sure…", parse);
Text.NL();
Text.Add("Snorting, Vaughn leads you over to the opposite side of the watchtower and clear his throat. <i>“Right, let’s begin. Are you familiar with a certain Lady Katara Heydrich?”</i>", parse);
Text.NL();
Text.Add("Can’t say you’ve heard of her before, no. Should you?", parse);
Text.NL();
Text.Add("<i>“Probably not. Very minor personage in court, according to what Elodie’s passed along to us. Still, we need her out of the way. See, thing is that our good friend the King’s Vizier has drafted a number of rather… disturbing laws regarding morphs and those marked as traitors to the crown, allowing Preston and his little posse to circumvent the usual warrants and due process accorded all of the king’s subjects. As you can imagine, we don’t like this one bit.”</i>", parse);
Text.NL();
Text.Add("Right. How does the good Lady Heydrich come into play?", parse);
Text.NL();
Text.Add("<i>“She’s set to present the arguments for those laws at the next court session, when the nobs intend to debate their merits and see if they’re to be passed,”</i> Vaughn replies. <i>“It’s supposed to be the big break Majid’s giving to her, allowing her to speak for him.</i>", parse);
Text.NL();
Text.Add("<i>“I want you to make sure that she never turns up.”</i>", parse);
Text.NL();
Text.Add("That sounds… sinister.", parse);
Text.NL();
Text.Add("Vaughn’s muzzle twists into a sneer. <i>“As it should be. Don’t worry, I’m not going to ask you to kill anyone. That’d put far too much heat on us, and too soon at that. No, I just want you to cause her to be… indisposed, and to that effect, our good surgeon has prepared a couple of options for you.”</i>", parse);
Text.NL();
Text.Add("As you watch, Vaughn digs about in his pants pockets and draws out a couple of slender vials, one marked with a blue label, the other with a red one. Looking closely at them, their contents may as well have been water, for all you can tell - thin and runny, colorless and likely odorless, too. Vaughn makes a show of waving them in your face and smiles.", parse);
Text.NL();
Text.Add("<i>“The blue vial, or the red vial? Blue one’s going to give anyone unfortunate to taste a few drops a terrible case of the runs. The good lady won’t die, but she’ll wish she were dead for a couple of days. Red one’s… ah… let’s just say that she’ll jump the bones of the next living, breathing thing and fuck the poor sop silly, then move on to the next until she’s tired out… <b>then</b> continue like that for a day or two.</i>", parse);
Text.NL();
Text.Add("<i>“Care to pick your poison?”</i>", parse);
Text.Flush();
// [Poison][Aphrodisiac]
const options: IChoice[] = [];
options.push({ nameStr : "Poison",
tooltip : "The poison sounds cruel enough, thank you very much.",
func() {
Text.Clear();
Text.Add("Vaughn nods and hands you the vial. <i>“I’m not going to envy the poor bitch when this gets into her system, but she really ought to have chosen a better bastard to throw her weight behind. I mean, I’ve never seen Majid in the flesh, but what I’ve heard of him makes me glad I’ve never had the chance for such. Well, since she enjoys spending so much time with dirty characters, I’m sure a case of the squealing shits won’t raise any eyebrows. The poison will take effect the following morning, so you’ll have plenty of time to make a getaway without raising too much suspicion.</i>", parse);
Text.NL();
Text.Add("<i>“Now, be careful with that thing. The glass shouldn’t shatter easily, but you don’t want to tempt fate any more than you need to. If you want to open it, just pull hard on the cork and it’ll pop free.</i>", parse);
vaughn.flags.T3 |= VaughnFlags.Poisoning.Poison;
party.Inv().AddItem(QuestItems.OutlawPoison);
Gui.PrintDefaultOptions();
}, enabled : true,
});
options.push({ nameStr : "Aphrodisiac",
tooltip : "Why not? It might be fun to watch.",
func() {
Text.Clear();
parse.gen = player.mfFem("fellow", "girl");
Text.Add("Vaughn grins at you and hands you the vial. <i>“Oh, looking to create a roof-raising scene, are we? That should be fun… as well as bring down a whole lot of disrepute upon our good lady. She certainly won’t be doing any speaking at court, then. Maybe some moaning… ha. Seriously, though, you’re quite the naughty [gen], [playername].”</i>", parse);
Text.NL();
Text.Add("This stuff is strong, isn’t it?", parse);
Text.NL();
Text.Add("<i>“The base recipe’s illegal, so I hear. Our good surgeon’s made a few additions of his own, some changes here and there, which should make it all the more amusing. When you’re ready to open this, just pull and twist hard on the cork, although I’d recommend holding your breath when you do so. Don’t want to accidentally sniff any of the fumes. This stuff will take effect almost immediately, but it need a couple of hours for the full effects to kick in. That should give you enough time to make a getaway before people start asking inconvenient questions.</i>", parse);
vaughn.flags.T3 |= VaughnFlags.Poisoning.Aphrodisiac;
party.Inv().AddItem(QuestItems.OutlawAphrodisiac);
Gui.PrintDefaultOptions();
}, enabled : true,
});
Gui.Callstack.push(() => {
Text.NL();
Text.Add("<i>“Now, as for how much you want to use - just a thimbleful will do, really, but there’s enough in here to spike a full-course meal for a whole bunch of folks, which is what it’ll probably come to.”</i>", parse);
Text.NL();
Text.Add("Ah, right. Now he’s getting to the details - should you be taking notes?", parse);
Text.NL();
Text.Add("Vaughn shrugs and tucks away the vial you didn’t pick into his pocket. <i>“Well, if you want to. Fact is, our eyes and ears have learned that Heydrich’s going to be entertaining some of her fellow nobs in one of the suites at the Lady’s Blessing tomorrow evening; it’ll be quite the event, starting at five in the evening up till midnight. Supposedly, it’s for some kind of business deal or the other, but I personally think that they just want an excuse to stuff their faces. Whatever, it’s all the better for us. Suite number’s thirty-three, keep that in mind.</i>", parse);
Text.NL();
Text.Add("<i>“The entire staff of the Lady’s Blessing is going to be busy with catering to them <b>and</b> their usual clientele, so they’re bound to be overworked and understaffed. Mistakes happen, that sort of thing… there’s your chance. Again, you’ll be on your own for this, but an opportunity should show its face. And if one doesn’t… well, you’ll just have to make things happen, if you get what I mean.”</i>", parse);
Text.NL();
Text.Add("All right.", parse);
Text.NL();
Text.Add("<b>To recap - tomorrow from five to midnight at the Lady’s Blessing. Lady Heydrich, suite thirty-three, spike the food and make sure she doesn’t turn up at court.</b>", parse);
Text.NL();
Text.Add("<i>“That’s the long and short of it,”</i> Vaughn says with a nod. <i>“Remember, we’re counting on you. Don’t. Be. Fucking. Late. The clock’s a-ticking, and as I’m sure you know by now, the world doesn’t stop to wait for you to be ready.</i>", parse);
Text.NL();
Text.Add("<i>“All right then, [playername]. You’ve your orders - good luck and all that other lovely stuff. Success or failure, I’ll be here when you’re ready to report in.”</i>", parse);
Text.Flush();
TimeStep({hour: 1});
vaughn.flags.Met = VaughnFlags.Met.OnTaskPoisoning;
const step = WorldTime().TimeToHour(0);
vaughn.taskTimer = new Time(0, 0, 1, step.hour, step.minute);
Gui.NextPrompt();
});
Gui.SetButtonsFromList(options, false, undefined);
}
export function InnAvailable() {
const vaughn: Vaughn = GAME().vaughn;
// Trigger this upon stepping into the Lady’s Blessing with this task active (Allotted time, 17-24 the next day, ie timer not expired, and <= 7 hours).
if (!VaughnTasksScenes.Poisoning.OnTask()) { return false; }
if (vaughn.taskTimer.Expired()) { return false; }
if (vaughn.taskTimer.ToHours() > 7) { return false; }
return true;
}
export function ArrivalAtInn(onWait: any, oldLocation?: any) {
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
};
Text.Clear();
if (onWait) {
Text.Add("There's a sudden influx of activity as you overhear a conversation between [Orvin] and his staff. Apparently, the Lady Heydrich and her entourage are about to arrive any minute. As if summoned, small groups of chattering nobles wearing fancy clothes start filtering in through the front doors, quickly greeted by the waiters and ushered into a back room. Meanwhile, the rest of the staff busy themselves with their tasks, working with feverish determination.", parse);
} else {
parse.start = (oldLocation === WORLD().loc.Rigard.Plaza) ? "Pushing open the door of the Lady’s Blessing" : "Walking down the stairs";
Text.Add("[start], you find the the common room a whirl of activity. Not with patrons - the evening crowd is thin today - but with numerous staff, almost all of them darting between the kitchen and the stairs leading up to the rooms. The few patrons who are present are almost exclusively gathered about the gambling tables, keeping themselves out of the way of the busy waiters darting to and fro.", parse);
}
Text.NL();
Text.Add("An organized scene indeed… but teetering on the edge of confusion, an insidious current of chaos under the rushing surface. All it’d take is a push in the right direction to create a situation you could take advantage of… ", parse);
Text.NL();
if (!GAME().lei.Recruited()) {
Text.Add("Lei is sitting in his usual corner, ever faithful to his charge. You meet the mercenary’s eyes, and he gives you a silent nod before turning his gaze away from you. He’s a small circle of calm in the whirlwind of activity, but he wouldn’t be Lei otherwise, you guess.", parse);
Text.NL();
}
Text.Add("Even [Orvin] is working overtime today, helping out with the serving and cooking - just how many people is this Lady Heydrich entertaining today? The weight of the glass vial makes itself known in your pocket, and you focus your thoughts. You’re here on a task, after all… ", parse);
Text.NL();
Text.Add("Now, how will you go about doing this?", parse);
Text.Flush();
VaughnTasksScenes.Poisoning.InnPrompt({});
}
export function InnPrompt(opts: any) {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const lei: Lei = GAME().lei;
const twins: Twins = GAME().twins;
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
playername : player.name,
};
// [Orvin][Kitchen][Waiters][Lei][Twins]
const options: IChoice[] = [];
if (RigardFlags.LB.KnowsOrvin() && !opts.Orvin) {
options.push({ nameStr : "Orvin",
tooltip : "Chat with Orvin and try to find out more about the situation.",
func() {
Text.Clear();
Text.Add("You wait for an opening when Orvin doesn’t look <i>too</i> busy, then step in and greet the innkeeper. He hesitates a moment, then returns your greeting with a smile, looking perhaps a little too happy to have an excuse to set down the empty dishes he’s carrying and take a breather.", parse);
Text.NL();
Text.Add("<i>“Oh, hello, [playername]. I’m afraid that we’re quite busy today - if you’re intending to eat here today, you’ll have to wait a little while for your order. Not too long, of course, since the busy spot’s about to clear up, but we were quite harried for most of the morning and afternoon.”</i>", parse);
Text.NL();
Text.Add("You put on your most innocent face and contrive to look surprised. Busy? What with?", parse);
Text.NL();
Text.Add("<i>“We’re quite honored to have one of the city’s fine ladies host her events here - the Lady Heydrich is entertaining some business contacts from the farther reaches of the kingdom, and has paid us quite the sum to put on our best face for them. As you can imagine, it’s been quite the endeavor getting ready for fifty-odd people in all of the four suites she’s booked for the occasion. All of my people and I, we’ve been preparing since last night for the big event, even if we’ve tried to not let it affect our usual business any.”</i>", parse);
Text.NL();
Text.Add("Looking at Orvin, he seems so proud and happy to be doing the catering - it’s almost a pity what you’re going to have to do here. Keeping a straight face, you look towards the kitchen. What was that he said about the busy spot being about to clear up? Does that mean he’s about finished, and you could place an order soon?", parse);
Text.NL();
Text.Add("<i>“Almost there. Almost there. It’s why I’m letting myself take a quick break, talking to you.”</i> Orvin replies. <i>“It’s just one more round of food and drinks to be sent up to their suites, and our part is done. I’ve served up only the best, and they can enjoy themselves all night long in peace.”</i>", parse);
Text.NL();
Text.Add("Judging by the wonderful smells coming out of the kitchen’s open door… yeah. You thank Orvin, then suggest that perhaps you’ll order something once the kitchens are less harried. In the meantime, maybe you’ll watch the cavalcade game or something… sorry about troubling him with your questions.", parse);
Text.NL();
Text.Add("<i>“Oh no, it was my pleasure.”</i> Orvin picks up his burden once more with a grunt, rolling his clearly aching shoulders. <i>“I needed to take a breather, anyway.”</i>", parse);
Text.NL();
Text.Add("You nod and give Orvin a little wave as the innkeeper disappears. Last round of food and drinks to be brought up, eh? Seems like you’ve arrived in the nick of time, then - you don’t have time to dither around, and will have to act quickly. What do you intend?", parse);
Text.Flush();
opts.Orvin = true;
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}, enabled : true,
});
}
options.push({ nameStr : "Kitchen",
tooltip : "Sneak into the kitchen and get up to some mischief.",
func() {
VaughnTasksScenes.Poisoning.Kitchen(opts);
}, enabled : true,
});
if (!opts.Waiters) {
options.push({ nameStr : "Waiters",
tooltip : "Waylay one of the waiters with your charm and try to create an opening.",
func() {
Text.Clear();
Text.Add("Hmm. If the kitchen’s a no-go, then that leaves you with the only option of waylaying the food en route to its destination. <i>That</i> in turn means having to deal with one of the many waiters plying up and down the staircase leading to the inn’s upper stories, and you get the distinct feeling that whatever shenanigans you’re going to cook up to distract the waiters with, they’re going to have to be good. Really good.", parse);
Text.NL();
Text.Add("Although heading over to the stairwell and trying your best to get their attention, not a single one stops to give you so much as a moment. ", parse);
if (player.Cha() > 45) {
Text.Add("Some of them do glance in your direction for a bit, but quickly snap back to the task at hand. ", parse);
}
Text.Add("Is Lady Heydrich’s little get-together that important? Sure seems like it, for so many of the staff to be dedicated to serving her. Or maybe there’s something more to it, judging from how nervous they look…", parse);
Text.NL();
Text.Add("There’s no time to sit around and ponder the issue at length, though. If this isn’t going to work, then you need to find another way to get at the food… maybe someone you know could help? Two minds are better than one, after all.", parse);
Text.Flush();
opts.Waiters = true;
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}, enabled : true,
});
}
if (!opts.Lei) {
options.push({ nameStr : "Lei",
tooltip : "Ask Lei and see if you can learn more about the situation.",
func() {
opts.Lei = true;
Text.Clear();
Text.Add("You settle down across the table from Lei, and he inclines his head at you ever so slightly in acknowledgement.", parse);
Text.NL();
Text.Add("That gives you an idea. Lei is quite the skilled mercenary, isn’t he? Perhaps you could hire him to do a small side job, since his current one isn’t that demanding? Subcontract your work out, in a manner of speaking? It <i>is</i> an option, one that you needn’t automatically quash out of hand… nothing ventured, nothing gained, right?", parse);
Text.NL();
Text.Add("Well, will you ask, or not?", parse);
Text.Flush();
// [Yes][No]
const options: IChoice[] = [];
options.push({ nameStr : "Yes",
tooltip : "Ask Lei if he’s willing to moonlight for you.",
func() {
Text.Clear();
Text.Add("<i>“Yes, [playername]? What is it?”</i>", parse);
Text.NL();
Text.Add("You quickly explain the situation to him, leaving out the obviously illicit bits regarding your information about the outlaws - he’s a mercenary, surely he’ll understand the whole ‘discretion’ thing. Lei doesn’t so much as move a muscle, but you can tell he’s listening intently to each and every one of your words.", parse);
Text.NL();
Text.Add("When you finish, there’s what seems like a long silence, and Lei finally speaks again. <i>“So, you wish to subcontract out the job to me.”</i>", parse);
Text.NL();
Text.Add("That’s the idea, yes. Will he do it?", parse);
Text.NL();
if (lei.Relation() >= LeiFlags.Rel.L3) {
Text.Add("Lei closes his eyes and thinks a moment. <i>“An interesting proposal. As luck would have it, I am certain that my employers will not be in need of my services for the next couple of hours. It appears a suitable opportunity to practice some of my more subtle skills.</i>", parse);
Text.NL();
Text.Add("<i>“Show me this vial of yours.”</i>", parse);
Text.NL();
Text.Add("You do so, palming it as you pull it out of your possessions and carefully hand it over to Lei. He turns it over in his fingers for a couple of moments, studying the flow of the liquid within, then nods at you.", parse);
Text.NL();
Text.Add("<i>“A most appropriate choice. I haven’t seen this for some time. Very well, I will do it - for a price.”</i>", parse);
Text.NL();
Text.Add("And what’s his asking fee?", parse);
Text.NL();
Text.Add("<i>“First, that you sit here in my stead until I return, lest someone attempt to take advantage of my absence. I should not be long, but vigilance is demanded. Secondly, a small fee of two hundred and fifty coins.”</i>", parse);
Text.NL();
Text.Add("Huh.", parse);
Text.NL();
Text.Add("Lei shows you a small smile. <i>“I can’t let word get out that I work for free, can I? There would be no end to the line of those seeking favors from me. I assure you, [playername], two hundred and fifty coins is a very reasonable price for a few minutes of my time.”</i>", parse);
Text.NL();
Text.Add("Well, it’s come to this. He’s a mercenary, what did you expect? Will you pay Lei or not?", parse);
Text.Flush();
// [Yes][No]
const options: IChoice[] = [];
options.push({ nameStr : "Yes",
tooltip : "Pay his asking price.",
func() {
Text.Clear();
Text.Add("<i>“Delightful.”</i> Lei’s expression doesn’t change as he counts your money, then without warning, he stands from his seat.", parse);
Text.NL();
Text.Add("He’s got all the details, right?", parse);
Text.NL();
Text.Add("<i>“I have. Don’t worry. Keep watch over the approach to my wards’ suite for me, and I will return shortly.”</i> He passes a few coins back to you. <i>“Purchase a drink for yourself, such that you do not appear obtrusive.”</i>", parse);
Text.NL();
Text.Add("With that, Lei vanishes into the milling crowd of busy inn staff, leaving you all alone at his table. You do as he says, quickly ordering a drink from one of the few less busy-looking waiters, then sit down to savor it and look alert. True to his word, perhaps fifteen minutes have passed before Lei returns to your table and takes his seat once more.", parse);
Text.NL();
Text.Add("<i>“It is done.”</i>", parse);
Text.NL();
Text.Add("Wow. He must be really good at his job.", parse);
Text.NL();
Text.Add("<i>“A small matter of sleight of hand, nothing more,”</i> Lei replies matter-of-factly. <i>“When another’s attention is on your face, he or she scarcely notices what the hands are doing. Similarly, drawing attention to one hand means the other is often overlooked. My only concern is that my wards’ sleep will be disturbed tonight with the effects of your clever concoction.”</i>", parse);
Text.NL();
Text.Add("Well, that seems to be that. Thanking Lei one last time, you make to take your leave. Best to head back to Vaughn and report your success.", parse);
Text.Flush();
party.coin -= 250;
vaughn.flags.T3 |= VaughnFlags.Poisoning.LeftItToLei;
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
vaughn.flags.Met = VaughnFlags.Met.PoisoningSucceed;
vaughn.flags.T3 |= VaughnFlags.Poisoning.Success;
TimeStep({hour: 1});
if (vaughn.flags.T3 & VaughnFlags.Poisoning.Aphrodisiac) {
Gui.NextPrompt(VaughnTasksScenes.Poisoning.AphrodisiacEntry);
} else {
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}
}, enabled : party.coin >= 250,
});
options.push({ nameStr : "No",
tooltip : "You can’t or won’t pay.",
func() {
Text.Clear();
Text.Add("You shake your head and say that on second thought, maybe you’ll do it yourself. Lei shows no displeasure at your words, but simply nods.", parse);
Text.NL();
Text.Add("<i>“I wish you the best of luck, [playername]. If there is nothing else, I must return to my duties.”</i>", parse);
Text.NL();
Text.Add("You push out your chair, stand, and survey the room as you consider your remaining options. What now? The clock’s a-ticking if you want to have any chance at success here.", parse);
Text.Flush();
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
} else {
Text.Add("Lei shakes his head slowly. <i>As you know full well, my services are currently engaged. I will wish you the best of luck, for the cause your task is serving seems to be a worthy one - I am full aware of the disturbing nature of some of the laws passed of late - but I’m sure you understand that I cannot simply abandon my post to aid you. That would be highly remiss of me.”</i>", parse);
Text.NL();
Text.Add("Oh well. You thought you’d ask, anyway.", parse);
Text.NL();
Text.Add("<i>“Asking is all well and good. I’ve witnessed many an agreement which could be reached had one party thought to simply open his or her mouth and put forward the proposal. Of course, one must consider the current circumstances in which the question is framed - something which you neglected to attend to.</i>", parse);
Text.NL();
Text.Add("<i>“Now, if that is all, I must return to my vigil.”</i>", parse);
Text.NL();
Text.Add("You nod, and rise from the seat. Seems like enlisting Lei’s help didn’t work out - you’ll have to find another avenue to achieve your goals here.", parse);
Text.Flush();
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}
}, enabled : true,
});
options.push({ nameStr : "No",
tooltip : "Nah, you’ll pass.",
func() {
Text.Clear();
Text.Add("Lei glances at you as you make yourself comfortable in the seat. <i>“[playername]. What brings you to me today?”</i>", parse);
Text.NL();
Text.Add("The inn seems busy today, doesn’t it?", parse);
Text.NL();
Text.Add("<i>“Some event or the other, hosted by someone small trying to make herself look bigger,”</i> Lei replies drolly. <i>“A common enough strategy amongst both animals and people, but wholly ineffective against someone who easily sees through the illusion. It is of little consequence, since it does not interfere in my ability to carry out my charge, although I will admit that the extended delay in getting a drink once ordered is turning quite intolerable.”</i>", parse);
Text.NL();
Text.Add("Quite the situation indeed. What did he say about not interfering, though? Wouldn’t the crowd of harried staff provide cover for anyone trying to sneak upstairs, or something on those lines?", parse);
Text.NL();
Text.Add("<i>“With those uniforms? No, anyone not dressed as the staff would stand out, and I daresay the good innkeeper’s people all know each other. All I need to do is watch.”</i>", parse);
Text.NL();
Text.Add("Hmm…", parse);
Text.NL();
Text.Add("<i>“I’m not in the mood to make small talk today, [playername]. If there’s no particular reason for you to seek me out, I request that you please leave me be for now.”</i>", parse);
Text.NL();
Text.Add("Lei’s voice distinctly implies that this isn’t open to negotiation, and you decide that it’s probably best not to pester him any further, lest he take it as provocation. You rise from your seat, nod, and start weighing your remaining options.", parse);
Text.Flush();
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
}, enabled : true,
});
}
if (!opts.Twins) {
options.push({ nameStr : "Twins",
tooltip : "Could the Twins possibly lend a hand here?",
func() {
Text.Clear();
opts.Twins = true;
Text.Add("A thought strikes you: sure, the task set before you may not be the easiest one, but it’s not as if you’re completely on your own here. You <i>do</i> have friends in high places close by, and you might as well bring all the resources you have to bear, right?", parse);
Text.NL();
Text.Add("With that thought in mind, you start off towards the stairs leading up. Some of the waiters cast suspicious looks at you when you pass by them, but soon settle down when it becomes clear you’re not heading for the suites, but rather the penthouse up top. The suspicion is a bit off - it’s not as if you’ve done anything just yet, right? - but you nevertheless emerge up into the Twins’ penthouse. Rumi - or at least, this is how the twin that greets you introduced herself - ushers you in, and by the looks of it they were sharing a bottle of wine and a moment of relaxation when you so thoughtlessly barged in on them. Both of them have donned gowns, but there’s no time for cute mind games this evening; there’s work to be done.", parse);
Text.NL();
Text.Add("<i>“Welcome, [playername].”</i> Rani - or at least, you’re taking Rumi’s word that she’s who she is - says, raising his glass in a small salute. <i>“Decided to drop by? You look quite pale - why don’t you have a little merlot? It’ll do wonders for your complexion.”</i>", parse);
Text.NL();
Text.Add("No, not right at the moment. You’re busy, and was wondering if the two of them could lend a little assistance.", parse);
Text.NL();
Text.Add("Rumi glides over behind her brother and places her hands on the chair’s backrest. <i>“Oh? This I must hear.”</i>", parse);
Text.NL();
Text.Add("Quickly, you summarize the salient details of your mission here, conveniently forgetting to include anything and everything about the outlaws, of course. The twins listen intently as you speak, and when you finish, Rani grins from ear to ear.", parse);
Text.NL();
Text.Add("<i>“Ah, so that’s what all that fuss was all about, and why it took so long for the wine to arrive. A full half-hour late, if I remember correctly.”</i>", parse);
Text.NL();
Text.Add("<i>“Shame,”</i> his sister agrees with a vigorous nod of her head. <i>“Someone of noble blood throws a big party for ‘business ends’, and no one thought to invite the prince and princess?”</i>", parse);
Text.NL();
Text.Add("What? Haven’t they bothered to look outside their door since afternoon?", parse);
Text.NL();
Text.Add("<i>“No,”</i> Rumi replies flatly. <i>“We were… preoccupied.”</i>", parse);
Text.NL();
Text.Add("<i>“Quite so.”</i> Rani runs his tongue over his lips.", parse);
Text.NL();
Text.Add("Right. Whatever floats their boat, but now that they’re appraised of the situation, could their royal personages possibly consider lending a hand in your venture? Any ideas would be welcome.", parse);
Text.NL();
Text.Add("The twins glance at each other, their expressions suddenly serious, and you can practically see the gears turning in their heads. Rumi drums her fingers on the table as she thinks, chewing her lip in the process. <i>“Lady Heydrich, Lady Heydrich… name rings a bell, but can’t quite remember why…”</i>", parse);
Text.NL();
Text.Add("<i>“She was the one who went up against us on the proposal to start work on expanding the sewage system last week, remember?”</i>", parse);
Text.NL();
Text.Add("<i>“Ah, that’s it. Come to think of it, she’s been throwing her weight around a little too much of late - having Majid’s patronage would certainly drive someone petty like her into a bout of preening. Give power to the undeserving, and that’s what happens. I wonder just what Majid can get out of a small-timer like Heydrich.”</i> Rumi takes a sip of her drink and thinks for a little longer, eyes staring into empty space.", parse);
Text.NL();
if (twins.Relation() >= 80) {
Text.Add("<i>“Another layer of obfuscation between him and his goals, of course. Lady Heydrich <b>has</b> been a thorn in our side for a while, wouldn’t you say, Sister?”</i>", parse);
Text.NL();
Text.Add("<i>“Yes. Yes, she has. I haven’t forgotten that last time she made a whole fuss about that bill. Quite desperate, if I remember.”</i> A smile breaks out on the princess’ face. <i>“I suppose we could lend a hand, grant a royal favor… within reason, of course. We do have reputations to maintain, and couldn’t be caught dealing with all sorts of shady characters.”</i>", parse);
Text.NL();
Text.Add("Like you, of course. Right. All you really need to do is to get at the feast before it’s served, so anything they could do to let you get close to the grub before it’s brought into suite thirty-three would be a great help. Or if they’d rather handle the vial themselves…?", parse);
Text.NL();
Text.Add("Rumi extends her hand. <i>“May I see this potion your friend has prepared?”</i>", parse);
Text.NL();
Text.Add("Why not, if it means a better chance they’ll help out? Digging through your possessions, you draw out Vaughn’s vial and pass it over to the princess. She turns it over in the light of a lamp, examining it from every angle, but the frown on her face remains where it is.", parse);
Text.NL();
Text.Add("<i>“I don’t recognize this,”</i> she murmurs, her face serious.", parse);
Text.NL();
Text.Add("<i>“Let me try, please.”</i> Rani receives the vial from his sister and pulls out the stopper with a flourish before using one hand to waft over the vapors to his nose. Nothing happens for a moment or two, and then he turns his head and sucks in a deep breath of fresh air, coughing to clear his airways.", parse);
Text.NL();
parse.hisher = player.mfFem("his", "her");
Text.Add("<i>“Whoo, that’s strong! There’s no smell, as I expected, but… phew. You can <b>feel</b> it. You certainly have quite the talented friend, [playername]. I wouldn’t mind if you introduced me to him sometime.”</i> He turns to Rumi. <i>“It’s all right, sister. I think I know what this is - it’s just been strengthened considerably. No one’s going to die or even hurt really badly, but I think we’re going to see quite some fun if we help [playername] with [hisher] little prank. And if it’ll get Heydrich out of our hair at court… ”</i>", parse);
Text.NL();
Text.Add("<i>“All right, I’m in. What do we do?”</i>", parse);
Text.NL();
Text.Add("Actually, you were hoping that since they do open up more options, they’d have an idea of what those options were. Or at least, better options than the one you had.", parse);
Text.NL();
Text.Add("Rumi arches an eyebrow. <i>“What <b>were</b> you going to ask us to do, then?”</i>", parse);
Text.NL();
Text.Add("Ideally? Distract one of the waiters with their stunning personalities while you get up to mischief. But…", parse);
Text.NL();
Text.Add("<i>“But what?”</i> The princess smiles sweetly. <i>“It’s a simple plan, and these things should be no more complicated than they need to be. As for holding someone’s attention, don’t worry about that. We were born to it.”</i>", parse);
Text.NL();
Text.Add("Rani nods as he hands the vial back to you. <i>“And of course, Father’s education was not completely useless. On top of that, Orvin’s people may not know exactly who we are, but they’ve gathered that we’re people of some import over the course of our extended stay here. After all, with these rates only someone with plenty of money could afford to rent out our penthouse for as long as we have.”</i>", parse);
Text.NL();
Text.Add("<i>“Agreed. They may not want to blow this event Heydrich’s had them cater, but there’s no guarantee that she’ll come back to them the next time she throws a party. We, on the other hand… we’re quite the steady source of income. They’ll give us the time of day. Leave it to my brother and I.”</i>", parse);
Text.NL();
Text.Add("Good, good. That’s all you needed. How long will they need to be ready?", parse);
Text.NL();
Text.Add("Rumi smiles sweetly. <i>“Just let us get changed. If you’d wait outside, we’ll be with you in a minute or two.”</i>", parse);
Text.NL();
Text.Add("The twins are good to their word. Scarcely have a few minutes passed before they emerge into the hallway in their usual clothes, head for the opposite wall, and signal for you to wait in the recently vacated doorway. It doesn’t take too long before another handful of waiters appear in the stairwell with their carts, and the twins quickly round on the last in line, the playful air about them vanishing like mist with the dawn. It’s not too unlike the movements of predators dragging a straggler away from the safety of the herd, and despite the waiter’s fine uniform and prim dress, you can see it’s having much the same effect on the poor sop.", parse);
Text.NL();
Text.Add("<i>“You. Yes, you!”</i> Rani shouts, beckoning the waiter over with an outstretched finger. He obeys with a bowed head and downcast eyes, and no sooner has he come to a stop in front of the twins that they lay into him with savage abandon. <i>“We want to complain about the quality of service here of late!”</i>", parse);
Text.NL();
Text.Add("You can’t help but feel a twinge of pity for the poor waiter as the twins maneuver him right in front of the open doorway - right, the placard on the cart denotes that it’s for suite thirty-three. No problems there, then. Still, you wait for the angry barrage of insults to reach its zenith, completely absorbing the waiter’s attention before daring to make a move.", parse);
Text.NL();
Text.Add("The stony expression on Rumi’s face could stop a charging Rakh - her eyes hard and unflinching, her lips set into a thin, straight line. <i>“Face us when we’re speaking - or have you forgotten your manners? Tell Orvin that we won’t stand for this horrible quality of service here! Half an hour to get up to us - who knows how long it’s been sitting around for? The taste, it’s completely ruined, and…”</i>", parse);
Text.NL();
Text.Add("You quickly realize what they’re doing - diverting the waiter’s attention further away from the cart in front of him. This is your chance, then - while your mark’s back is turned to you, you quickly creep forward and introduce the vial’s contents into both the pitcher and dessert bowl. The watery fluid rushes in without a sound, mingling with dew and condensation as it creeps down the glassware’s sides.", parse);
Text.NL();
Text.Add("<i>“And remember, we want the wine properly chilled this time,”</i> Rumi huffs, looking every bit the spoiled princess, right down to the indignant air that’s practically palpable about her. <i>“I mean, half an hour! I know that you folk are busy today, but seriously, half an hour to bring up a bottle and ice bucket? What is this, Rirvale? I’ve half a mind to find better accommodations elsewhere - I hear there’s a new place near the castle grounds. Well, off with you! And don’t be tardy this time!”</i>", parse);
Text.NL();
Text.Add("Finally released, the poor waiter takes off at a run, his little food cart trundling along at an impressive pace, and both twins give you a wink as you emerge from the doorway to their penthouse.", parse);
Text.NL();
Text.Add("<i>“So, how were my sister and I?”</i>", parse);
Text.NL();
Text.Add("Oh, very convincing, you assure Rani. Very indignant indeed.", parse);
Text.NL();
Text.Add("Rumi smiles and shrugs, hooking an arm about her brother’s waist. <i>“Father did tell us that being overly open with one’s feelings is dangerous for a monarch, and I have to agree with him on that. In any case, should I be expecting lots of noise from downstairs tomorrow morning?”</i>", parse);
Text.NL();
Text.Add("Perhaps even earlier. Well, you ought to scoot before things get a little too heated up.", parse);
Text.NL();
Text.Add("<i>“We’ll see you around, then.”</i> With that, the Twins disappear into their room, and the door shuts with a good, solid thump. Time to make like a tree and leave.", parse);
Text.Flush();
vaughn.flags.T3 |= VaughnFlags.Poisoning.LeftItToTwins;
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
vaughn.flags.Met = VaughnFlags.Met.PoisoningSucceed;
vaughn.flags.T3 |= VaughnFlags.Poisoning.Success;
TimeStep({hour: 1});
if (vaughn.flags.T3 & VaughnFlags.Poisoning.Aphrodisiac) {
Gui.NextPrompt(VaughnTasksScenes.Poisoning.AphrodisiacEntry);
} else {
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}
} else {
parse.himher = player.mfFem("him", "her");
Text.Add("<i>“[playername] <b>has</b> been of quite some help to us of late,”</i> Rani pipes up. <i>“We should really repay [himher] with a favor or two sometime. Money only goes so far, and getting rid of Lady Heydrich’s influence for some time would certainly be a breath of fresh air for once.”</i>", parse);
Text.NL();
Text.Add("<i>“True, but we’ve been extending ourselves quite dangerously of late. Father is beginning to notice something’s up.”</i> Rumi turns away from her brother and to you. <i>“I’m sorry, [playername], but you’ve come at a bad time. If she does show up in court, we’ll fight her to the utmost for you - not as if it wasn’t in our interests to do as much anyway, if she really is fronting for Majid - but asking us to play a direct hand in your rather illegal escapades would bring more scrutiny down upon us than we’d care for at the moment.”</i>", parse);
Text.NL();
Text.Add("<i>“Royal rank doesn’t matter much when it’s Father doing the hectoring,”</i> Rani adds. <i>“Sorry, [playername].”</i>", parse);
Text.NL();
Text.Add("Aah, that’s all right. It’s perfectly understandable - you’ll just have to find a way to deal with Lady Heydrich on your own, and they did say that they’d help you fight her during court if you fail here. Bidding farewell to the twins, you leave their penthouse and wind up back in the common room of the Lady’s Blessing.", parse);
Text.Flush();
VaughnTasksScenes.Poisoning.InnPrompt(opts);
}
}, enabled : true,
});
}
Gui.SetButtonsFromList(options, false, undefined);
}
export function Kitchen(opts: any) {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const terry: Terry = GAME().terry;
let parse: IParse = {
playername: player.name,
};
Text.Clear();
Text.Add("The wonderful aroma of the fare to be had in the Lady’s Blessing hits you once more, and your thoughts drift towards the busy kitchens. Getting into the suites is out of the question, so your best bet is to spike the food either after it’s been cooked or when it’s en route to its final destination. Of the two approaches, you decide that the former offers the best chance of success. Sneaking in, spiking the food and then hightailing it out of there - much easier said than done…", parse);
Text.NL();
if (party.InParty(terry)) {
parse = terry.ParserPronouns(parse);
Text.Add("…Of course, you do have with you someone who’s uniquely suited to the job of sneaking around, and if Terry can take things from where they belong, then putting things where they <i>don’t</i> belong should be just as easy. Right? Right?", parse);
Text.NL();
Text.Add("Seriously, though, are you going to ask Terry to do the job for you, or get up to mischief yourself?", parse);
Text.Flush();
// [Terry][Yourself]
const options: IChoice[] = [];
options.push({ nameStr : "Terry",
tooltip : Text.Parse("The thief's experience should really pay off here; you doubt [heshe]'ll have any trouble getting it done.", parse),
func() {
Text.Clear();
parse.boygirl = terry.mfPronoun("boy", "girl");
parse.foxvixen = terry.mfPronoun("fox", "vixen");
vaughn.flags.T3 |= VaughnFlags.Poisoning.LeftItToTerry;
parse.rel = terry.Relation() >= 60 ? ", although you can tell it’s more teasing than indignant" : "";
Text.Add("<i>“What?”</i> Terry exclaims[rel]. <i>“I’m to do your dirty work?”</i>", parse);
Text.NL();
Text.Add("Well, of course. That’s why you keep [himher] around, to do the things that you can’t manage alone. ", parse);
if (terry.Sexed()) {
Text.Add("Why, did [heshe] think you just kept [himher] around for the petting and fucking?", parse);
Text.NL();
parse.rel = terry.Relation() >= 60 ? Text.Parse(" before sticking [hisher] tongue out at you", parse) : "";
Text.Add("<i>“Sometimes it seems that way,”</i> Terry replies[rel].", parse);
} else {
Text.Add("Why, did [heshe] think you just kept [himher] around for [hisher] charming personality?", parse);
Text.NL();
Text.Add("<i>“Don’t you try flattery on me,”</i> Terry replies, looking suspicious.", parse);
}
Text.NL();
Text.Add("Hmph. In any case, you’re in need of someone who can do some sneaking, [heshe]’s really good at sneaking, and that should be enough reason. Besides, it’s not like [heshe]’s unfamiliar with the Lady’s Blessing - you have to admit, [heshe] really did look quite fetching in that waitress’ outfit… come to think of it, perhaps you could get your hands on a similar one for [himher] sometime…", parse);
Text.NL();
Text.Add("Resigned to [hisher] fate, Terry throws [hisher] hands in the air and sighs. <i>“All right, all right. I’ll see what I can do. No promises, though.”</i>", parse);
Text.NL();
Text.Add("That’s a good [boygirl]. Of course you know that [heshe] will do [hisher] best, right?", parse);
Text.NL();
Text.Add("Terry just skulks. You give the [foxvixen] an amused pat, and hand over Vaughn’s vial to [himher]. Come on now, it can’t be that hard, right? [HeShe] should be familiar with the kitchens’ layout and how things are run in there… who knows, [heshe] might even bump into an old friend or two. There’s no need to feel guilty - it’s all for a higher cause, yeah?", parse);
Text.NL();
Text.Add("<i>“All right, all right, all right,”</i> Terry groans. <i>“Let’s just get it over with.”</i>", parse);
Text.NL();
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
Text.Add("Without another word, Terry slinks out the front door, leaving you alone to bide your time in the barroom while the [foxvixen] works [hisher] magic. You find an empty table to relax at, order a couple of drinks from a harried-looking waiter, and settle down to nurse it as moments tick by.", parse);
Text.NL();
Text.Add("At length, Terry reappears at your side, looking positively exhausted and drained. How long has it been? No more than twenty minutes or half an hour, but you’d have thought it’d be more by how hard the [foxvixen]’s breathing. You pull out the chair across you, and Terry gladly slumps into it, eagerly digging into the spare drink on the table.", parse);
Text.NL();
Text.Add("How’d it go?", parse);
Text.NL();
Text.Add("<i>“Done,”</i> Terry replies, then wipes [hisher] muzzle with the back of [hisher] hand. <i>“It was very rough, but the job’s done.”</i>", parse);
Text.NL();
Text.Add("Really? For a master thief like [himher]?", parse);
Text.NL();
Text.Add("<i>“C’mon, cut me some slack here,”</i> Terry replies in a low hiss. <i>“They were looking out for trouble in the kitchen - I’m not guessing, I <b>know</b> it. Someone tipped them off. The constant looking over shoulders, second-guessing themselves, checking the dishes over and over again… I know Orvin and his people, and they don’t do this unless they’ve good reason to think someone’s going to mess with the food.”</i>", parse);
Text.NL();
Text.Add("Huh. Now that’s an interesting way of looking at things, and you’re doubly glad you asked Terry to go in your stead, but [heshe]’s absolutely sure?", parse);
Text.NL();
Text.Add("Terry nods. <i>“You get a feel for these things, and then have to decide whether you want to go through with the heist anyways. Still, it may have taken most of what I had, but hey, I still got the job done. I don’t think they were looking for someone like me, though, so that helped, even if there were so many eyes in the kitchen…”</i>", parse);
if (terry.PregHandler().IsPregnant()) {
Text.Add(" The [foxvixen] pats [hisher] rounded tummy. <i>“Didn’t help that I had to lug around this little one too, although I think they enjoyed it.”</i>", parse);
}
Text.NL();
Text.Add("The two of you sit around for a few more minutes, then Terry sighs. <i>“We ought to get out of here before the show begins. I don’t want to see the inside of a cell again, and especially not with you beside me.”</i>", parse);
Text.NL();
Text.Add("You’ve to agree with that - perhaps it’d be best if you reported back to Vaughn and told him about your presence being expected at the inn. Standing, you quickly pay for your drinks and make to leave.", parse);
Text.Flush();
vaughn.flags.Met = VaughnFlags.Met.PoisoningSucceed;
vaughn.flags.T3 |= VaughnFlags.Poisoning.Success;
TimeStep({hour: 1});
if (vaughn.flags.T3 & VaughnFlags.Poisoning.Aphrodisiac) {
Gui.NextPrompt(VaughnTasksScenes.Poisoning.AphrodisiacEntry);
} else {
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}
}, enabled : true,
});
options.push({ nameStr : "Yourself",
tooltip : "If you want something done properly, you’ll have to do it yourself.",
func() {
Text.Clear();
VaughnTasksScenes.Poisoning.KitchenYourself();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
} else {
VaughnTasksScenes.Poisoning.KitchenYourself();
}
}
export function KitchenYourself() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
};
parse.comp = party.Num() === 2 ? party.Get(1).name : "your companions";
parse.c = party.Num() > 1 ? Text.Parse(" ask [comp] to wait for you in the barroom, and", parse) : "";
Text.Add("Right. No time like the present, then. With the constant stream of staff heading in and out of the kitchen’s main door, just waltzing on in probably isn’t the best of ideas. There doesn’t seem to be any other way of getting into the kitchen from the common room, so you[c] leave the Lady’s Blessing proper and nip around to the back of the building. There ought to be someplace where deliveries are made and the staff enter the inn by, at the very least… it’s too much to imagine that you’d find a pie set out on the windowsill to cool or something of the likes, but at least you might find an alternative approach here.", parse);
Text.NL();
Text.Add("Indeed, there’s a back door, and a pretty large one at that, clearly made to accept the large quantities of food and drink the Lady’s Blessing must receive every day. It’s locked, but the window beside it isn’t, and you push it open and climb into a back room of sorts. As your eyes adjust to the dim light, you take in the scene that lies before you: silvered trays with cutlery and dishes already laid out on them, pitchers waiting to be filled, small casks of brandy lined up against a wall. Beyond a door set into the far wall, the sounds of the kitchen at work, and it certainly <i>sounds</i> crowded enough that you’d rather not risk entering it at all if possible.", parse);
Text.NL();
Text.Add("It seems like [Orvin]’s had his people prepare as far ahead as possible for the event - it’s clear that once the food’s cooked, it’ll be ready to go with the minimum of fuss. They’ve even marked out the carts bearing the dishes with small placards numbering thirty-one to thirty five… these must be the suites which Heydrich’s rented for the occasion.", parse);
Text.NL();
Text.Add("The casks seem like the only reasonable avenue available to you, but try as you might, you can’t see a way of undoing the wax seals without giving away that they’ve been tampered with. Then it strikes you: if you can’t spike the food, then maybe the dishes will do just as well. Vaughn did mention that a few drops would be more than enough for the vial’s contents to take effect, so hopefully that’ll work.", parse);
Text.NL();
Text.Add("Wasting no time, you uncork the vial and begin tainting the bowls, pitchers and serving dishes slated for suite thirty-three, smearing a few drops on each one in turn.", parse);
Text.NL();
const check = (player.Dex() + player.Int()) / 2 + Math.random() * 20;
const goal = 50;
if (GetDEBUG()) {
Text.Add(`Dex+Int check: ${check} vs ${goal}`, undefined, "bold");
Text.NL();
}
if (check >= goal) {
Text.Add("It’s a tiring job, ensuring that everything is as unnoticeable as possible, but the liquid does dry quickly - hopefully that doesn’t reduce its efficacy any. If the cooks or waiters spot it, hopefully they’ll just mistake it for dampness or something and won’t wipe it off… or worse.", parse);
Text.NL();
Text.Add("It seems like forever, but you finish off the last of the vial’s contents and pop the stopper back in place. And just in time, too - you can hear voices coming to you from beyond the far wall, amidst the din of the kitchen’s activity. Even with the speakers shouting, you can’t quite make out what’s being said, but you know you don’t want to be here when they come in. Sprinting on tiptoe, you vault over the windowsill with a sudden burst of panic-fuelled energy and land in the street outside, just managing to shut the window before the door creaks open and light spills into the back room.", parse);
Text.NL();
Text.Add("Once you’re sure no alarm has been raised, you cautiously risk sneaking a peek into the back room. Waiters busy themselves amongst the carts, filling soup tureens from a huge pot, loading the casks onto the serving carts, pouring sweet nectar into the pitchers, and arranging chilled cut fruits on small toothpicks upon the platters.", parse);
Text.NL();
parse.p = vaughn.flags.T3 & VaughnFlags.Poisoning.Poison ? "poison" : "aphrodisiac";
parse.c = party.Num() > 1 ? Text.Parse("rejoin [comp] in", parse) : "re-enter";
Text.Add("The last course’s coming up, and it promises to be a good one. Hopefully, the [p] takes - with one last glance at the waiters pushing the carts back out through the kitchen’s steamy confines, you slip back to the front entrance and [c] the inn, although you don’t intend to stay long. Best to head back to Vaughn and report your success.", parse);
Text.Flush();
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
vaughn.flags.Met = VaughnFlags.Met.PoisoningSucceed;
vaughn.flags.T3 |= VaughnFlags.Poisoning.Success;
TimeStep({hour: 1});
if (vaughn.flags.T3 & VaughnFlags.Poisoning.Aphrodisiac) {
Gui.NextPrompt(VaughnTasksScenes.Poisoning.AphrodisiacEntry);
} else {
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}
} else {
Text.Add("You work as fast as you can, but it clearly isn’t quick enough. About halfway through the process, numerous footsteps ring out from amidst the din and clatter of the kitchens, clearly heading for the door on the far end of the room.", parse);
Text.NL();
Text.Add("Your breath catches in your throat, and you quickly stuff the vial and its contents into your pocket as you make a mad dash for the window. You’ve one hand on the windowsill and are about to vault over when the click of the handle turning sounds out from behind you, followed by shouts of surprise and anger - but more the latter than the former.", parse);
Text.NL();
Text.Add("No time to look back - and they might see your face if you did. With one hand on the windowsill, you vault through the window and hit the street outside running. While you don’t think whoever it was behind you managed to get a good look at your back before you took off, it’s probably for the best that you don’t show your face about the Lady’s Blessing for a little bit.", parse);
Text.NL();
Text.Add("Thankfully, whoever it was who discovered your intrusion doesn’t seem too interested in pursuing you, and you slow your pace a little as you circle around to the inn’s front, keeping a wide berth from the actual entrance.", parse);
if (party.Num() > 1) {
parse.s = party.Num() > 2 ? "" : "s";
Text.Add(" Presently, [comp] emerge[s] from the inn’s front and rejoins you, having figured out what the sudden hullabaloo was all about.", parse);
}
Text.NL();
Text.Add("It’s not very likely that they’re going to use those dishes which you tainted, so there’s nothing you can do but head back to Vaughn and report your failure.", parse);
Text.Flush();
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
vaughn.flags.Met = VaughnFlags.Met.PoisoningFail;
TimeStep({hour: 1});
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}
}
export function AphrodisiacEntry() {
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
};
Text.Clear();
Text.Add("Mission accomplished, time to leave before the fireworks - uh oh. Passing the stairway leading up to the rooms on your way out, you catch the faint sounds of laughter from suite thirty-three, and more - there’s a clear sexual undertone to it all. Yes, it’s faint, but you’re pretty sure you heard a moan there. At least all the food seems to have been served and you’re sure that the staff are taking a well-deserved break, but it probably isn’t going to be too long before [Orvin] or someone else notices what’s up?", parse);
Text.NL();
Text.Add("The aphrodisiac wasn’t supposed to take effect this quickly, was it? Or did you add more than you ought to have? Well, what’s done is done. You <i>should</i> leave soon, yes, but then again, there’s the temptation to take in your handiwork and see just what you’ve wrought…", parse);
Text.Flush();
// [Peek][Leave]
const options: IChoice[] = [];
options.push({ nameStr : "Peek",
tooltip : "Face it, you just want to know what’s going on inside.",
func() {
VaughnTasksScenes.Poisoning.AphrodisiacPeek();
}, enabled : true,
});
options.push({ nameStr : "Leave",
tooltip : "You don’t want to linger here any more than necessary.",
func() {
VaughnTasksScenes.Poisoning.AphrodisiacLeave();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
}
export function AphrodisiacLeave() {
const parse: IParse = {};
Text.Clear();
Text.Add("Shaking your head, you turn your back and hurry down and out of the Lady’s Blessing. Things should be getting heated up soon, if Vaughn’s description of the aphrodisiac’s effects were accurate, and since you know for sure that the job’s taken care of, you don’t want to be here any longer than necessary. There’s nothing left for you now but to report back to Vaughn and hear what he has to say.", parse);
Text.Flush();
Gui.NextPrompt();
}
export function AphrodisiacPeek() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const vaughn: Vaughn = GAME().vaughn;
const room69: Room69 = GAME().room69;
let parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
};
parse = player.ParserTags(parse);
parse = Text.ParserPlural(parse, player.NumCocks() > 1);
parse = Text.ParserPlural(parse, player.NumCocks() > 2, "", "2");
const p1cock = player.BiggestCock();
Text.Clear();
Text.Add("Curiosity gets the better of you, and you can’t help but crack open the suite door and take a little peek. The scene that greets your eyes isn’t quite the roof-roaring orgy yet, but it’s certainly getting more than a little steamy for the occupants of suite thirty-three, numbering about twelve to fifteen in total. While the aphrodisiac hasn’t had enough time to kick in fully, undone clothes and rumpled fabrics are the order of the day, and there’s plenty of making out going on between the various people within.", parse);
Text.NL();
Text.Add("Of course, some are more enthusiastic than others - in particular, a rather striking woman with the telltale red hair of the nobility lies on her back upon the suite’s plush carpeted floor, her hair making a halo about her head. There’s a huge, throbbing cock in her mouth and one in each of her hands as men in various states of undress cluster about her, eagerly awaiting their turn, and another finely-dressed lady grinds at her mound through her dress in a fit of unbridled lust.", parse);
Text.NL();
Text.Add("Lady Heydrich, you assume. Well, if this keeps up for as long as the aphrodisiac lasts, she’ll definitely be in no shape to turn up in court anytime soon, let alone debate. You turn your eye to the exquisite dishes arrayed out in the buffet, all in various states of consumption, and shake your head. The only regret, perhaps, is how [Orvin]’s going to take a pretty bad fall for this, what with it happening at his establishment and all.", parse);
Text.NL();
Text.Add("Even in this short moment, the air’s begun to heat up noticeably - more and more garments are falling discarded to the ground, while whimpers and soft moans turn to grunts and cries of passion, the rustle of addled fingers pawing desperately at fabric clear in the air. Is there more you need to get done here, or should you just get out while you can?", parse);
Text.Flush();
// [Join][69][Leave]
const options: IChoice[] = [];
options.push({ nameStr : "Join",
tooltip : "Why let a good orgy go to waste? Join in the fun!",
func() {
Text.Clear();
parse.ar = player.Armor() ? Text.Parse("[armor] and ", parse) : "";
Text.Add("Screw this, you could never resist a good orgy, and the fact that it’s an impromptu one comprised of the upper crust makes it all the more dangerous and appealing. Wading through the mess of fabric and bodies, skin rubbing against skin and hands grasping at your calves and thighs, you allow yourself to embrace the increasingly cloying atmosphere of sweet sex growing in the inn suite, hurriedly stripping off your [ar]clothes as you approach the epicenter of the fuck-pile - Lady Heydrich.", parse);
Text.NL();
Text.Add("The other merchants and traders can do themselves; you’re going straight for the prize! Without hesitation, you shove the young man currently occupying her face off; his cock emerges with an audible pop, trailing a small string of seed, and you send him on his way with a good slap on his rump. Hazy and unfocused, Heydrich’s eyes roll this way and that, perhaps wondering who you are or where that delicious cock went. What a greedy little slut, considering that she’s still got one rod of man-meat in each hand.", parse);
Text.NL();
if (p1cock) {
parse.mc = player.NumCocks() > 1 ? "whole lot of replacements" : "replacement";
Text.Add("Well, you’ve got a [mc] right here, so no need to worry about that. Straddling the lusty noblewoman’s chest, you prodigiously apply your elbow to make a little space for yourself and make yourself comfortable.", parse);
Text.NL();
if (p1cock.Len() > 25) {
Text.Add("With how heavy your [cocks] [isAre], you need plenty of space, and waste no time in literally cock-slapping the nearby orgy-goers into clearing a path for your ponderous rod. Heydrich’s eyes widen as she takes in the impressive length and girth of your man-meat[s], but apprehension soon turns to delight as the aphrodisiac’s hold strengthens. With a renewed urgency, she gobbles up[oneof] your [cocks] without hesitation, trying to cram all she can fit into that mouth of hers and leaving barely enough space to breathe.", parse);
} else {
parse.a = player.NumCocks() > 1 ? "a" : "your";
Text.Add("While your [cocks] might not be as endowed as it might have been, it doesn’t faze Heydrich any. With all of her other extremities quite occupied, all it takes is an open mouth for you to ram [a] member into it with great gusto. The addled noblewoman’s eyes widen in surprise at first, then resume their usual glazed-over look as the aphrodisiac’s hold strengthens.", parse);
}
Text.NL();
parse.b = player.HasBalls() ? " balls slapping at her chin and" : "";
Text.Add("Without further ado, you buck your hips forward and start pounding away in a steady, instinctive rhythm,[b] rutting away without a care in the world. Now you’re just another warm body in the midst of the glorious orgy that’s taking place here, flushed and steadily getting slick with sweat as you give in to your desires even without the need of an alchemical aid.", parse);
if (player.NumCocks() > 1) {
Text.NL();
Text.Add("Your other shaft[s2] flop[notS2] and bat[notS2] this way and that, sometimes bumping against Lady Heydrich’s chin, sometimes against other warm things which identity you’re not exactly sure of. At length, you become vaguely aware of other fingers grasping for [itThem2], pumping along [itsTheir2] length with hungry, desperate strokes. It could be any number of the writhing bodies which‘ve drawn closer to the massive pile of copulation since you arrived, but hey, it’s not polite to look a gift horse in the mouth. That mouth’s much better used elsewhere, after all.", parse);
Text.NL();
Text.Add("Groaning, you lean back and savor the delightful sensations from being sucked and stroked at the same time, the subtle contrast only making the whole that much more pleasurable.", parse);
}
} else { // Vag
Text.Add("While you might not have a shaft, you’ve something even better than that for Heydrich to busy her tongue with. Smirking, you blatantly shove your [vag] into the addled noblewoman’s face, letting her get a good scent of your muff. It takes a few urgent grinds before she finally gets the message and starts licking away, that dainty little tongue of hers darting in and out from between her full lips. It soon becomes clear that Heydrich’s no stranger to eating out another woman, and you briefly wonder where and how she learned as much before the first wave of pleasure hits you and you arch backwards, wrapping your fingers around someone’s - it’s hard to tell exactly whose - shoulders to keep balance.", parse);
Text.NL();
Text.Add("Aww. It’s so cute, the sight of her lapping at your cunt like a kitten at a saucer of milk, and the way her tongue-tip reaches for your button and runs along it sends tingles arcing down your spine, triggering a fresh flow of feminine nectar to ooze upon her face. Straightening yourself, you reach for your [breasts] and work away, fingers teasing your [nips] while Heydrich works away beneath you and the others in the room jostle against your bodies. Instinctively drawn by the heat and tension in the air that’s the result of sweet, sweet sex, it’s not long before you have a moaning, wriggling mass of limbs all about you, all sorts of things hard at work stuffing various holes.", parse);
Text.NL();
Text.Add("You’re vaguely aware of a few details about you - a fat, balding merchant being spit roasted by two younger men while his ass is stuffed by a particularly thick and oily sausage, a once stately lady barking like a dog as she’s mounted and reamed on all fours like one - but your attention is always drawn back to slut supreme Heydrich. The more the noblewoman gives into her lusts, the more predatory and urgent her licking becomes, the deeper her tongue thrusts - so vigorous and enthusiastic she is, that she’s moved her hands to your hips, grabbing you as an anchor while she bucks and undulates beneath you.", parse);
}
Text.NL();
Text.Add("While it’d have been nice for this to see the orgy to its end, hurried words reach your ears from downstairs, followed by shouts and footsteps pounding on the staircase leading up. Seems like the inn staff’s caught onto your shenanigans - as upsetting as it is to pull out before due time, you hurriedly stand on shaky legs and do up your clothing as best as you can while dashing for the window.", parse);
Text.NL();
Text.Add("The plush carpet is already soaking up plenty of sexual fluids, and as you vault over the windowsill and onto the roof tiles outside, you can’t help but pity whoever’s going to have to clean this up afterwards. Shouts erupt from behind you as the door’s flung open, and there’s more than one scream at the sight of glistening, rutting orgy-goers, but you don’t dare look back for fear of risking someone getting a glimpse of your face.", parse);
Text.NL();
parse.comp = party.Num() === 2 ? party.Get(1).name : "your companions";
parse.c = party.Num() > 1 ? Text.Parse(" where [comp] rejoin you", parse) : "";
Text.Add("Yeah… maybe staying to partake wasn’t the best of ideas, but it sure <i>felt</i> good while it lasted. Down the roof and round the back[c] - there’s no way you’re heading into the Lady’s Blessing for a while now, not while [Orvin] and his people sort out this mess and are still casting suspicious eyes on everyone and everything. Your nethers still tingling from your rudely interrupted repast, you do your best to clear your head and gather your thoughts. Since there’s nothing left for you to do here, perhaps it’d be best if you headed back to Vaughn and reported in.", parse);
Text.Flush();
vaughn.flags.T3 |= VaughnFlags.Poisoning.JoinedOrgy;
player.slut.IncreaseStat(100, 5);
TimeStep({hour: 1});
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}, enabled : player.FirstCock() !== undefined || player.FirstVag() !== undefined,
});
if (room69.flags.Rel >= Room69Flags.RelFlags.GoodTerms) {
options.push({ nameStr : "69",
tooltip : "Come to think of it, you know someone who might keep them occupied for a while…",
func() {
Text.Clear();
Text.Add("An idea comes to your mind, and a very nasty grin spreads out on your face as it takes form. Yes… you may need to get out of here soon, but there’s someone else who might do a better job of keeping an eye on these fine people, and you know just who it is.", parse);
Text.NL();
Text.Add("Quickly, you take a glance down the corridor; now that the buffet’s been served up, the staff are taking a break, and there aren’t any other guests wandering the halls at the moment. Great, this is the opening you need. Quickly throwing open the door of suite thirty-three, you grab the closest sucker - a young man with his undershirt unbuttoned down to his navel and stiff cock hanging out of his trousers - and begin manhandling him in the direction of room 369. Glassy-eyed and in quite the sex-filled pink haze, he’s quite compliant, especially when you give his rod a few encouraging tugs to get him going. Seeing one of their number depart - and with a newcomer at that - the other members of the nascent orgy begin stumbling out after the two of you, perhaps seeking more exhilarating delights.", parse);
Text.NL();
Text.Add("Well, they’re going to get some soon enough. Slowly, gingerly, your fingers close upon the know of 69’s door, giving it a little stroke with your fingertips as if it were a knob of an entirely different sort.", parse);
Text.NL();
Text.Add("<i>“Ooh, who is it?”</i> a muffled voice calls out from behind the door. <i>“You’re certainly daring to be visiting a lady-gentleman at this hour, and with such forward behavior, too! I can’t entirely say I dislike it, though. Perhaps you should come inside and let us get to know each other a little better?”</i>", parse);
Text.NL();
Text.Add("Well, here goes nothing. Throwing open the door, you usher the young man into Sixtynine; the rest of the parade trailing out behind him, smelling perfume and the promise of sating their lusts, quickly follow him in. Lady Heydrich is the last one in, tottering a little from both lust and the rough dogpiling she took, but lets out a more than enthusiastic squeal as you shove her in with a slap on her pert rump. The moment everyone’s in, the door slams of its own accord, and the squeals - first of fear, then of delight - resound through the walls as the room sets to entertaining the delightful playmates you’ve sent along.", parse);
Text.NL();
Text.Add("It won’t be long before someone <i>does</i> come up to investigate, though. Much as you’d like to stay and savor the fruits of your hard work, you don’t want to be here when inconvenient questions are asked. Ignoring the cries of ecstasy ringing through the walls, you slip out of the Lady’s Blessing and are out the door. Time to head back to Vaughn and get his debrief, then.", parse);
Text.Flush();
player.subDom.IncreaseStat(100, 2);
vaughn.flags.T3 |= VaughnFlags.Poisoning.Used69;
TimeStep({hour: 1});
Gui.NextPrompt(() => {
MoveToLocation(WORLD().loc.Rigard.Plaza);
});
}, enabled : true,
});
}
options.push({ nameStr : "Leave",
tooltip : "All right, you know the the job is done. Get out!",
func() {
VaughnTasksScenes.Poisoning.AphrodisiacLeave();
}, enabled : true,
});
Gui.SetButtonsFromList(options, false, undefined);
}
export function OutOfTime() {
const vaughn: Vaughn = GAME().vaughn;
return VaughnTasksScenes.Poisoning.OnTask() && vaughn.taskTimer.Expired();
}
export function DebriefSuccess() {
const player: Player = GAME().player;
const party: Party = GAME().party;
const outlaws: Outlaws = GAME().outlaws;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
playername : player.name,
};
Text.Clear();
Text.Add("<i>“Ah, you’re back,”</i> Vaughn says as he notices you approach. The fox-morph is taking a small break with a couple of his men, passing a small hip flask amongst the three of them; he dismisses his men and takes a final swig from the flask before pocketing it and turning to you. <i>“How was it? I was quite worried.”</i>", parse);
Text.NL();
Text.Add("You managed to get it done, yes, and pass the now-empty vial to Vaughn. But worried? You’re flattered, but why was it that he was worried about you?", parse);
Text.NL();
Text.Add("<i>“Well, you notice anything out of shape while you were there? People extra vigilant, on the edge, that sort of thing?”</i>", parse);
Text.NL();
Text.Add("Hmm, not really. The waiters did seem rather harried, as did [Orvin] himself, but that was only to be expected with all the catering they had to do. Was there supposed to be something amiss?”</i>", parse);
Text.NL();
Text.Add("Vaughn shakes his head. <i>“I’ve had word from our eyes and ears that the staff were told to expect someone to try and mess with the food. That they were to be right by their food carts at all times, that no one was allowed to be in the kitchens, and that sort of good stuff. Someone told them we were coming, [playername], and I don’t like that one bit.”</i>", parse);
Text.NL();
Text.Add("That… yes, it would explain why the waiters wouldn’t stop for anyone, but he’s sure?", parse);
Text.NL();
Text.Add("<i>“Positive. I don’t like the thought any more than you do, but even the boss-man agrees that there’s got to be a traitor somewhere in our camp.”</i> Vaughn rubs his face. <i>“I suppose it had to happen sooner or later, with some of the shadier folks who nevertheless manage to get in here, but…”</i>", parse);
Text.NL();
Text.Add("The fox-morph falls silent, and the two of you stare at each other for a few moments until he collects himself once more. <i>“You just ought to keep this in mind. Get your stuff done, and we’ll handle the mole in our midst. In the meantime, we should probably get back to the problem at hand.”</i>", parse);
Text.NL();
if (vaughn.flags.T3 & VaughnFlags.Poisoning.Poison) {
Text.Add("Well, you got the poison into the food. You didn’t stop to check if the stuff had actually been eaten, though, and by the Lady herself…", parse);
Text.NL();
Text.Add("<i>“You did what you could,”</i> Vaughn says with a sigh. <i>“It’s the best we can hope for - if everyone around Heydrich but her comes down with the squealing shits, then it’s just our bad luck. You can’t win them all, as Maria says.”</i>", parse);
Text.NL();
Text.Add("Right. So, what now?", parse);
Text.NL();
Text.Add("<i>“What happens now is that you take a good breather and rest up for the inevitable next task the boss-man’s going to hand down sooner or later. Or heck, I might even take up some initiative like he’s been pushing us to do and ask you of my own accord.</i>", parse);
Text.NL();
Text.Add("<i>“Seriously, though. Just take a break, do whatever you do when you’re not with us; I’m sure that you’ve got plenty to be done. You’ll be busy again soon enough.”</i>", parse);
} else { // (Success via aphrodisiac)
Text.Add("Right. About that - when you left the party, the orgy was still going on in full force, and you doubt that anything less than the direct intervention of a great spirit would bring it to a halt. Well, maybe not that much, but he knows what you mean.", parse);
Text.NL();
Text.Add("<i>“Hah,”</i> Vaughn replies, a corner of his mouth curling upwards in utter contempt. <i>“I can imagine, all right. Bird-brains there assured me that a reasonable dose’ll last all day, and won’t wear off even after a nap. Worst thing that could happen is that someone finds the orgy and forcibly breaks it up, but it’s not as if Heydrich will be in any shape to attend court for quite some time.”</i>", parse);
Text.NL();
Text.Add("Great! So… mission accomplished, then?", parse);
Text.NL();
Text.Add("<i>“That would be it, yes. Go and get some rest, take a breather, do whatever you do when you’re not with us. The boss-man has plenty of ideas in that head of his, and I’m sure it won’t be too long before he thinks another one of them’s good enough to put into action. Or perhaps I might even take initiative like the boss-man’s always pushing us to do and ask something of you myself.</i>", parse);
Text.NL();
Text.Add("<i>“That’s it for now, [playername]. Good work. Wish I could’ve been there to see it for myself, those nobs rutting up and down like a bunch of beasts, but them’s the breaks.”</i>", parse);
}
Text.NL();
Text.Add("If he says so, then. You half-turn to go, but Vaughn gently catches you by the shoulder and clears his throat. <i>“Ahem. There’s still something I have to give you for your time.”</i>", parse);
Text.NL();
Text.Add("Why, a reward?", parse);
Text.NL();
Text.Add("Vaughn nods. <i>“You stuck your neck out for us, so I think it’s fitting. Let me go in and get it.”</i>", parse);
Text.NL();
Text.Add("Without another word, Vaughn spins on his heel and enters the watchtower, reappearing shortly with a case in his hands. <i>“Here, for you. Came in from upriver. Meant for the boss-man, but he doesn’t hold truck with such things. Maybe you’ll make better use out of it.”</i>", parse);
Text.NL();
Text.Add("What’s inside, though?", parse);
Text.NL();
Text.Add("A wink and tip of Vaughn’s hat. <i>“Open it up in a bit and find out, that’s all I’ll say. All right, then - if there’s nothing else, I’ve got to get back on duty. Have a good one, [playername].”</i>", parse);
Text.NL();
Text.Add("You unwrap the package. It contains a razor sharp but very fragile looking glass sword.", parse, "bold");
Text.Flush();
TimeStep({hour: 1});
vaughn.flags.Met = VaughnFlags.Met.CompletedPoisoning;
outlaws.relation.IncreaseStat(100, 3);
party.Inv().AddItem(CombatItems.GlassSword);
Gui.NextPrompt();
}
export function DebriefFailure() {
const player: Player = GAME().player;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
Orvin : RigardFlags.LB.KnowsOrvin() ? "Orvin" : "the innkeeper",
playername : player.name,
};
Text.Clear();
Text.Add("<i>“You’re back,”</i> Vaughn says as he notices you approach. The fox-morph is sharing a small break with a couple of his men, passing a hip flask between the three of them, and he dismisses them with a wave of a hand-paw as you draw close. <i>“I was worried you wouldn’t turn up - our eyes and ears reported of quite the commotion at the Lady’s Blessing a little while ago.”</i>", parse);
Text.NL();
Text.Add("Yes, yes. Didn’t take him too long to put two and two together, did he?", parse);
Text.NL();
Text.Add("Vaughn shakes his head and spits on the ground. <i>“Nope, and neither was the news of the good kind. After you set off, I got word that Orvin and his people down at the Lady’s Blessing were particularly on edge. Somehow, someone managed to get across the message that someone would be trying to mess with the catering for Heydrich’s little party, and that they ought to be extra careful.</i>", parse);
Text.NL();
Text.Add("<i>“You look like shit. Tell me what kind of trouble you ran into.”</i>", parse);
Text.NL();
Text.Add("Hey, you didn’t think you looked <i>that</i> bedraggled. Still, you do your best to adjust your clothing while you recount to Vaughn what happened in the back room of Lady’s Blessing. The ex-soldier listens intently, his ears twitching under his hat, then eyes you.", parse);
Text.NL();
Text.Add("<i>“Hah. They made sure that no one could get at the food proper, but failed to consider someone might try to mess with the glassware instead. Linear thinking, as the boss-man would say. Still, seems like they realized their mistake halfway through.”</i>", parse);
Text.NL();
Text.Add("Come to think of it, you can’t help but feel a little bad for [Orvin]. He was just trying to preserve the good name of his inn, that’s all.", parse);
Text.NL();
Text.Add("Vaughn looks at you askance. <i>“I’m not going to lie, [playername]. Most peoples’ lives aren’t sticking closely to the straight and narrow already… but what we do is even less peachy keen than that. Orvin’s got a good business going, he’s got a reputation and history, and he’ll recover in time. This isn’t so bad. Who knows what’ll come down the line, though?</i>", parse);
Text.NL();
Text.Add("<i>“I’ve had to make choices which I’m not exactly proud of, but were necessary back then. You gotta keep that in mind and know what you can do and sleep at night.”</i>", parse);
Text.NL();
Text.Add("All right, you will.", parse);
Text.NL();
Text.Add("<i>“Good. If I were you, I’d get some rest. From your tale, you’ve had quite the close shave, and it’s only due to the spirits’ providence that you weren’t recognized.”</i> He claps you on the shoulder. <i>“Watch your back from here on out; there’s a snitch in our midst and it may take some time to root the bastard out just yet. Get a move along, soldier. There’ll be work to be done soon enough, so hold your horses.”</i>", parse);
Text.Flush();
TimeStep({hour: 1});
vaughn.flags.Met = VaughnFlags.Met.CompletedPoisoning;
Gui.NextPrompt();
}
export function DebriefOutOfTime() {
const party: Party = GAME().party;
const outlaws: Outlaws = GAME().outlaws;
const vaughn: Vaughn = GAME().vaughn;
const parse: IParse = {
};
Text.Clear();
Text.Add("<i>“You’re back,”</i> Vaughn states dryly as you draw close. <i>“Finally decided to show your face, or did you forget the meaning of the word ‘punctual’? No, I don’t want to hear your excuses. Or did you know to stay away from the Lady’s Blessing?”</i>", parse);
Text.NL();
Text.Add("What? What’s that about staying away from the Lady’s Blessing?", parse);
Text.NL();
Text.Add("<i>“Oh, so you were just being tardy. I get it, I get it. And here I was, thinking that you might’ve been a no-show because you know it somehow got leaked that someone was going to try and mess with the food that evening. At least that would’ve been understandable; I would’ve come back and said ‘hey, something unexpected happened, maybe we should call it off’. Well, guess I was wrong.</i>", parse);
Text.NL();
Text.Add("<i>“Give me back the vial. Not as if you’re going to be using it anyway. Guess there’s a small ray of light in all of this - at least you aren’t the bloody traitor. I think.”</i>", parse);
Text.NL();
Text.Add("Wordlessly, you hand over the vial to Vaughn, who storms away. Best not to talk to him again for a little while, or at least until he’s stopped fuming…", parse);
Text.Flush();
party.Inv().RemoveItem(QuestItems.OutlawPoison);
party.Inv().RemoveItem(QuestItems.OutlawAphrodisiac);
outlaws.relation.DecreaseStat(0, 5);
vaughn.flags.Met = VaughnFlags.Met.CompletedPoisoning;
TimeStep({hour: 1});
Gui.NextPrompt();
}
}
}
| 412 | 0.72557 | 1 | 0.72557 | game-dev | MEDIA | 0.92939 | game-dev | 0.951535 | 1 | 0.951535 |
espanso/espanso | 3,979 | espanso-engine/src/process/middleware/undo.rs | /*
* This file is part of espanso.
*
* Copyright (C) 2019-2021 Federico Terzi
*
* espanso 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.
*
* espanso 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 espanso. If not, see <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use super::super::Middleware;
use crate::event::{
input::{Key, Status},
internal::{TextFormat, UndoEvent},
Event, EventType,
};
pub trait UndoEnabledProvider {
fn is_undo_enabled(&self) -> bool;
}
pub struct UndoMiddleware<'a> {
undo_enabled_provider: &'a dyn UndoEnabledProvider,
record: RefCell<Option<InjectionRecord>>,
}
impl<'a> UndoMiddleware<'a> {
pub fn new(undo_enabled_provider: &'a dyn UndoEnabledProvider) -> Self {
Self {
undo_enabled_provider,
record: RefCell::new(None),
}
}
}
impl Middleware for UndoMiddleware<'_> {
fn name(&self) -> &'static str {
"undo"
}
fn next(&self, event: Event, _: &mut dyn FnMut(Event)) -> Event {
let mut record = self.record.borrow_mut();
if let EventType::TriggerCompensation(m_event) = &event.etype {
*record = Some(InjectionRecord {
id: Some(event.source_id),
trigger: Some(m_event.trigger.clone()),
..Default::default()
});
} else if let EventType::Rendered(m_event) = &event.etype {
if m_event.format == TextFormat::Plain {
if let Some(record) = &mut *record {
if record.id == Some(event.source_id) {
record.injected_text = Some(m_event.body.clone());
record.match_id = Some(m_event.match_id);
}
}
}
} else if let EventType::Keyboard(m_event) = &event.etype {
if m_event.status == Status::Pressed {
if m_event.key == Key::Backspace {
if let Some(record) = (*record).take() {
if let (Some(trigger), Some(injected_text), Some(match_id)) =
(record.trigger, record.injected_text, record.match_id)
{
if self.undo_enabled_provider.is_undo_enabled() {
return Event::caused_by(
event.source_id,
EventType::Undo(UndoEvent {
match_id,
trigger,
replace: injected_text,
}),
);
}
}
}
}
*record = None;
}
} else if let EventType::Mouse(_) | EventType::CursorHintCompensation(_) = &event.etype {
// Explanation:
// * Any mouse event invalidates the undo feature, as it could
// represent a change in application
// * Cursor hints invalidate the undo feature, as it would be pretty
// complex to determine which delete operations should be performed.
// This might change in the future.
*record = None;
}
event
}
}
#[derive(Default)]
struct InjectionRecord {
id: Option<u32>,
match_id: Option<i32>,
trigger: Option<String>,
injected_text: Option<String>,
}
| 412 | 0.924148 | 1 | 0.924148 | game-dev | MEDIA | 0.369675 | game-dev | 0.92227 | 1 | 0.92227 |
UJS-Cyber-Lab/TSO-HAstar-Net | 2,479 | src/hybrid_astar_searcher/include/hybrid_astar_searcher/collisiondetection.h | #pragma once
#ifndef COLLISIONDETECTION_H
#define COLLISIONDETECTION_H
#include <nav_msgs/OccupancyGrid.h>
#include "constants.h"
#include "lookup.h"
// #include "node2d.h"
#include "node3d.h"
#include "hybrid_astar_searcher/type_defs.h"
namespace planning {
/*
\brief The CollisionDetection class determines whether a given configuration q of the robot will result in a collision with the environment.
It is supposed to return a boolean value that returns true for collisions and false in the case of a safe node.
*/
class CollisionDetection {
public:
CollisionDetection();
/*!
\brief evaluates whether the configuration is safe
\return true if it is traversable, else false
*/
bool isTraversable(Vec3d pose) {
/* Depending on the used collision checking mechanism this needs to be adjusted
standard: collision checking using the spatial occupancy enumeration
other: collision checking using the 2d costmap and the navigation stack
*/
float cost = configurationTest(pose(0), pose(1), pose(2)) ? 0 : 1;
return cost <= 0;
}
bool isTraversable(int X, int Y, float Theta) {
float cost = configurationTest_(X, Y, Theta) ? 0 : 1;
return cost <= 0;
}
/*!
\brief updates the grid with the world map
*/
void updateGrid(const nav_msgs::OccupancyGridConstPtr& map) {grid = map;}
private:
/*!
\brief Calculates the cost of the robot taking a specific configuration q int the World W
\param x the x position
\param y the y position
\param t the theta angle
\return the cost of the configuration q of W(q)
\todo needs to be implemented correctly
*/
// float configurationCost(float x, float y, float t) {return 0;}
/*!
\brief Tests whether the configuration q of the robot is in C_free
\param x the x position
\param y the y position
\param t the theta angle
\return true if it is in C_free, else false
*/
bool configurationTest(float x, float y, float t);
bool configurationTest_(int X, int Y, float Theta);
private:
nav_msgs::OccupancyGridConstPtr grid;
// The collision lookup table
Constants::config collisionLookup[Constants::headings * Constants::positions];
};
}
#endif // COLLISIONDETECTION_H
| 412 | 0.74992 | 1 | 0.74992 | game-dev | MEDIA | 0.974733 | game-dev | 0.695518 | 1 | 0.695518 |
rhomobile/rhodes | 24,044 | neon/R2D1/Build/Config/RegEx.xml | <?xml version = "1.0"?>
<!-- Regular expressions configuration file -->
<RegularEx>
<Equivs>
<!-- Key Capture HTTP-Equiv -->
<Expression patternEx="^OnKey0x(..)" replaceEx="OnKey-keyvalue0x\1" />
<Expression patternEx="^OnKeyDispatch0x(..)" replaceEx="OnKey-Dispatch0x\1" />
<Expression patternEx="^OnAllKeys$" replaceEx="OnKey-AllKeys" />
<Expression patternEx="^OnAllKeysDispatch$" replaceEx="OnKey-AllKeysDispatch" />
<Expression patternEx="^acceleratekey$" replaceEx="KeyCapture-AccelerateKey" />
<Expression patternEx="^HomeKey$" replaceEx="KeyCapture-HomeKeyValue" />
<Expression patternEx="^OnTrigger$" replaceEx="KeyCapture-TriggerEvent" />
<!-- Scanner (RSM) HTTP-Equiv -->
<Expression patternEx="^RSMGetNavigate$" replaceEx="RSM-RSMGetEvent" />
<Expression patternEx="^RSMGetParam$" replaceEx="RSM" />
<Expression patternEx="^RSMSetParam$" replaceEx="RSM" />
<!-- Scanner (Decoders) HTTP-Equiv -->
<Expression patternEx="^all_decoders$" replaceEx="scanner-all_decoders" />
<Expression patternEx="^auspostal$" replaceEx="scanner-auspostal" />
<Expression patternEx="^Canpostal$" replaceEx="scanner-canpostal" />
<Expression patternEx="^Codabar$" replaceEx="scanner-codabar" />
<Expression patternEx="^Codabar-CLSiEditing$" replaceEx="scanner-codabarclsiediting" />
<Expression patternEx="^Codabar-maxlength$" replaceEx="scanner-codabarmaxlength" />
<Expression patternEx="^Codabar-minlength$" replaceEx="scanner-codabarminlength" />
<Expression patternEx="^Codabar-NotisEditing$" replaceEx="scanner-notisediting" />
<Expression patternEx="^Codabar-Redundancy$" replaceEx="scanner-codabarredundancy" />
<Expression patternEx="^code11$" replaceEx="scanner-code11" />
<Expression patternEx="^Code11-CheckDigitCount$" replaceEx="scanner-code11checkdigitcount" />
<Expression patternEx="^Code11-Redundancy$" replaceEx="scanner-code11redundancy" />
<Expression patternEx="^code11-reportcheckdiget$" replaceEx="scanner-code11reportcheckdigit" />
<Expression patternEx="^code128$" replaceEx="scanner-code128" />
<Expression patternEx="^code128-ean128$" replaceEx="scanner-code128ean128" />
<Expression patternEx="^code128-isbt128$" replaceEx="scanner-code128isbt128" />
<Expression patternEx="^Code128-maxlength$" replaceEx="scanner-Code128maxlength" />
<Expression patternEx="^Code128-minlength$" replaceEx="scanner-Code128minlength" />
<Expression patternEx="^code128-other128$" replaceEx="scanner-code128other128" />
<Expression patternEx="^Code128-Redundancy$" replaceEx="scanner-Code128Redundancy" />
<Expression patternEx="^Code39$" replaceEx="scanner-Code39" />
<Expression patternEx="^Code39-code32prefix$" replaceEx="scanner-Code39code32prefix" />
<Expression patternEx="^Code39-concatenation$" replaceEx="scanner-Code39concatenation" />
<Expression patternEx="^Code39-ConvertToCode32$" replaceEx="scanner-Code39ConvertToCode32" />
<Expression patternEx="^Code39-fullascii$" replaceEx="scanner-Code39fullascii" />
<Expression patternEx="^Code39-maxlength$" replaceEx="scanner-Code39maxlength" />
<Expression patternEx="^Code39-minlength$" replaceEx="scanner-Code39minlength" />
<Expression patternEx="^Code39-Redundancy$" replaceEx="scanner-Code39Redundancy" />
<Expression patternEx="^Code39-ReportCheckDigit$" replaceEx="scanner-Code39ReportCheckDigit" />
<Expression patternEx="^Code39-VerifyCheckDigit$" replaceEx="scanner-Code39VerifyCheckDigit" />
<Expression patternEx="^Code93$" replaceEx="scanner-Code93" />
<Expression patternEx="^Code93-maxlength$" replaceEx="scanner-Code93maxlength" />
<Expression patternEx="^Code93-minlength$" replaceEx="scanner-Code93minlength" />
<Expression patternEx="^Code93-Redundancy$" replaceEx="scanner-Code93Redundancy" />
<Expression patternEx="^Composit_ab$" replaceEx="scanner-Composit_ab" />
<Expression patternEx="^Composit_c$" replaceEx="scanner-Composit_c" />
<Expression patternEx="^d2of5$" replaceEx="scanner-d2of5" />
<Expression patternEx="^d2of5-maxlength$" replaceEx="scanner-d2of5maxlength" />
<Expression patternEx="^d2of5-minlength$" replaceEx="scanner-d2of5minlength" />
<Expression patternEx="^d2of5-Redundancy$" replaceEx="scanner-d2of5Redundancy" />
<Expression patternEx="^DataMatrix$" replaceEx="scanner-DataMatrix" />
<Expression patternEx="^DutchPostal$" replaceEx="scanner-DutchPostal" />
<Expression patternEx="^Ean13$" replaceEx="scanner-Ean13" />
<Expression patternEx="^ean8$" replaceEx="scanner-ean8" />
<Expression patternEx="^ean8-ConvertToEAN13$" replaceEx="scanner-ean8ConvertToEAN13" />
<Expression patternEx="^i2of5$" replaceEx="scanner-i2of5" />
<Expression patternEx="^i2of5-ConvertToEAN13$" replaceEx="scanner-i2of5ConvertToEAN13" />
<Expression patternEx="^i2of5-maxlength$" replaceEx="scanner-i2of5maxlength" />
<Expression patternEx="^i2of5-minlength$" replaceEx="scanner-i2of5minlength" />
<Expression patternEx="^i2of5-Redundancy$" replaceEx="scanner-i2of5Redundancy" />
<Expression patternEx="^12of5-ReportCheckDigit$" replaceEx="scanner-12of5ReportCheckDigit" />
<Expression patternEx="^i2of5-VerifyCheckDigit$" replaceEx="scanner-i2of5VerifyCheckDigit" />
<Expression patternEx="^JapPostal$" replaceEx="scanner-JapPostal" />
<Expression patternEx="^MacroMicroPDF$" replaceEx="scanner-MacroMicroPDF" />
<Expression patternEx="^MacroPDF$" replaceEx="scanner-MacroPDF" />
<Expression patternEx="^MaxiCode$" replaceEx="scanner-MaxiCode" />
<Expression patternEx="^MicroPDF$" replaceEx="scanner-MicroPDF" />
<Expression patternEx="^Msi$" replaceEx="scanner-Msi" />
<Expression patternEx="^Msi-checkdigits$" replaceEx="scanner-Msicheckdigits" />
<Expression patternEx="^Msi-CheckDigitScheme$" replaceEx="scanner-MsiCheckDigitScheme" />
<Expression patternEx="^Msi-maxlength$" replaceEx="scanner-Msimaxlength" />
<Expression patternEx="^Msi-minlength$" replaceEx="scanner-Msiminlength" />
<Expression patternEx="^Msi-Redundancy$" replaceEx="scanner-MsiRedundancy" />
<Expression patternEx="^Msi-ReportCheckDigit$" replaceEx="scanner-MsiReportCheckDigit" />
<Expression patternEx="^Qrcode$" replaceEx="scanner-Qrcode" />
<Expression patternEx="^rss14$" replaceEx="scanner-rss14" />
<Expression patternEx="^Rssexp$" replaceEx="scanner-Rssexp" />
<Expression patternEx="^Rsslim$" replaceEx="scanner-Rsslim" />
<Expression patternEx="^Signature$" replaceEx="scanner-Signature" />
<Expression patternEx="^tlc39$" replaceEx="scanner-tlc39" />
<Expression patternEx="^Trioptic39$" replaceEx="scanner-Trioptic39" />
<Expression patternEx="^trioptic39-Redundancy$" replaceEx="scanner-trioptic39Redundancy" />
<Expression patternEx="^UKPostal$" replaceEx="scanner-UKPostal" />
<Expression patternEx="^upc_ean-bookland$" replaceEx="scanner-upc_eanbookland" />
<Expression patternEx="^upc_ean-coupon$" replaceEx="scanner-upc_eancoupon" />
<Expression patternEx="^upc_ean-lineardecode$" replaceEx="scanner-upc_eanlineardecode" />
<Expression patternEx="^upc_ean-randomweightcheckdigit$" replaceEx="scanner-upc_eanrandomweightcheckdigit" />
<Expression patternEx="^upc_ean-securitylevel$" replaceEx="scanner-upc_eansecuritylevel" />
<Expression patternEx="^Upc_ean-supplemental2$" replaceEx="scanner-Upc_eansupplemental2" />
<Expression patternEx="^Upc_ean-supplemental5$" replaceEx="scanner-Upc_eansupplemental5" />
<Expression patternEx="^upc_ean-supplementalmode$" replaceEx="scanner-upc_eansupplementalmode" />
<Expression patternEx="^Upca$" replaceEx="scanner-Upca" />
<Expression patternEx="^upca-preamble$" replaceEx="scanner-upcapreamble" />
<Expression patternEx="^upca-ReportCheckDigit$" replaceEx="scanner-upcaReportCheckDigit" />
<Expression patternEx="^upce0$" replaceEx="scanner-upce0" />
<Expression patternEx="^upce0-ConvertToupca$" replaceEx="scanner-upce0ConvertToupca" />
<Expression patternEx="^upce0-preamble$" replaceEx="scanner-upce0preamble" />
<Expression patternEx="^upce0-ReportCheckDigit$" replaceEx="scanner-upce0ReportCheckDigit" />
<Expression patternEx="^upce1$" replaceEx="scanner-upce1" />
<Expression patternEx="^upce1-ConvertToupca$" replaceEx="scanner-upce1ConvertToupca" />
<Expression patternEx="^upce1-preamble$" replaceEx="scanner-upce1preamble" />
<Expression patternEx="^upce1-ReportCheckDigit$" replaceEx="scanner-upce1ReportCheckDigit" />
<Expression patternEx="^Usplanet$" replaceEx="scanner-Usplanet" />
<Expression patternEx="^Uspostnet$" replaceEx="scanner-Uspostnet" />
<Expression patternEx="^Webcode$" replaceEx="scanner-Webcode" />
<Expression patternEx="^scannernavigate$" replaceEx="scanner-decodeevent" />
<Expression patternEx="^enumscannernavigate$" replaceEx="scanner-enumscannerevent" />
<!-- Imager HTTP-Equiv -->
<Expression patternEx="^imagernavigate$" replaceEx="imager-imagerevent" />
<!-- Indicators HTTP-Equiv -->
<Expression patternEx="^batterynavigate$" replaceEx="battery-batteryevent" />
<Expression patternEx="^signalnavigate$" replaceEx="signal-signalevent" />
<!-- Signature Capture HTTP-Equiv -->
<Expression patternEx="^signaturenavigate$" replaceEx="signaturecapture-SignatureSaveEvent" />
<!-- Telemetry HTTP-Equiv -->
<Expression patternEx="^TelemetryNavigate$" replaceEx="Telemetry-TelemetryDataEvent" />
<!-- IO HTTP-Equiv -->
<Expression patternEx="^IONavigate$" replaceEx="IO-PortEvent" />
<Expression patternEx="^IOAnalog$" replaceEx="IO" />
<Expression patternEx="^IOSystem$" replaceEx="IO" />
<Expression patternEx="^IODigital$" replaceEx="IO" />
<!-- Device & Application HTTP-Equiv -->
<Expression patternEx="^TimerNavigate$" replaceEx="Timer-Start" />
<Expression patternEx="^TimerInterval$" replaceEx="Timer-Interval" />
<Expression patternEx="^MoveSIP$" replaceEx="SIP" />
<Expression patternEx="^SIPControl$" replaceEx="SIP" />
<Expression patternEx="^CursorPos$" replaceEx="Hourglass" />
<Expression patternEx="^Volume$" replaceEx="Volume-SetVolume" />
<Expression patternEx="^Reboot$" replaceEx="Reboot-BootType" />
<Expression patternEx="^PowerOn$" replaceEx="PowerOn-PowerOnEventLegacy" />
<!-- Card Reader HTTP-Equiv -->
<Expression patternEx="^msrnavigate$" replaceEx="cardreader-readevent" />
<Expression patternEx="^dcrnavigate$" replaceEx="cardreader-readevent" />
<Expression patternEx="^dcr$" replaceEx="cardreader" />
<!-- Push HTTP-Equiv -->
<Expression patternEx="^PushNavigate$" replaceEx="Push-Detected" />
<Expression patternEx="^Unattended$" replaceEx="Push-Unattended" />
<!-- File Management HTTP-Equiv -->
<Expression patternEx="^FileTransferNavigate$" replaceEx="FileTransfer-TransferEvent" />
<!-- Controls (Buttons) HTTP-Equiv -->
<Expression patternEx="^TextButton$" replaceEx="ZoomTextButton" />
</Equivs>
<Contents>
<!-- Common Contents -->
<Expression patternEx="^$" replaceEx="url('')" />
<Expression patternEx="^Javascript:(.*)" replaceEx="url('Javascript:\1');" />
<Expression patternEx="^(x)=(-?[0-9]+)" replaceEx="left:\2" />
<Expression patternEx="^(y)=(-?[0-9]+)" replaceEx="top:\2" />
<Expression patternEx="^(w)=(-?[0-9]+)" replaceEx="width:\2" />
<Expression patternEx="^(h)=(-?[0-9]+)" replaceEx="height:\2" />
<Expression patternEx="^show$" replaceEx="visibility:visible" />
<Expression patternEx="^hide$" replaceEx="visibility:hidden" />
<Expression patternEx="^enabled$" replaceEx="enable" />
<Expression patternEx="^disabled$" replaceEx="disable" />
<!-- Colour -->
<Expression patternEx="(.*):([a-f0-9]+),([a-f0-9]+),([a-f0-9]+)" replaceEx="\1:#\2\3\4;" />
<Expression patternEx="(.*)=([a-f0-9]+),([a-f0-9]+),([a-f0-9]+)" replaceEx="\1:#\2\3\4;" />
<Expression patternEx="^RGB:(.*)" replaceEx="color:\1" />
<!-- File Management Contents -->
<Expression patternEx="^source=(http://.*)" replaceEx="source:url('\1')" />
<Expression patternEx="^dest=(http://.*)" replaceEx="destination:url('\1')" />
<Expression patternEx="^source=(ftp://.*)" replaceEx="source:url('\1')" />
<Expression patternEx="^dest=(ftp://.*)" replaceEx="destination:url('\1')" />
<Expression patternEx="^filename:(ftp://.*)" replaceEx="filename:url('\1')" />
<Expression patternEx="^filename:(http://.*)" replaceEx="filename:url('\1')" />
<Expression patternEx="^filename:(file://.*)" replaceEx="filename:url('\1')" />
<Expression patternEx="^http://(.*)" replaceEx="url('http://\1');" />
<Expression patternEx="^https://(.*)" replaceEx="url('https://\1');" />
<Expression patternEx="^file://(.*)" replaceEx="url('file://\1');" />
<Expression patternEx="^ftp://(.*)" replaceEx="url('ftp://\1');" />
<Expression patternEx="^http:$" replaceEx="protocol:http" />
<Expression patternEx="^ftp:$" replaceEx="protocol:ftp" />
<Expression patternEx="^http$" replaceEx="protocol:http" />
<Expression patternEx="^http:([0-9]+)" replaceEx="protocol:http; port:\1" />
<Expression patternEx="^ftp$" replaceEx="protocol:ftp" />
<Expression patternEx="^ftp:([0-9]+)" replaceEx="protocol:ftp; port:\1" />
<Expression patternEx="^file$" replaceEx="protocol:file" />
<Expression patternEx="^source=(.*)" replaceEx="source:\1" />
<Expression patternEx="^dest=(.*)" replaceEx="destination:\1" />
<Expression patternEx="^user=(.*)" replaceEx="username:\1" />
<Expression patternEx="^pass=(.*)" replaceEx="password:\1" />
<Expression patternEx="^username=(.*)" replaceEx="username:\1" />
<Expression patternEx="^password=(.*)" replaceEx="password:\1" />
<Expression patternEx="^send$" replaceEx="transfer;SetFileDestination:FALSE" />
<Expression patternEx="^receive$" replaceEx="transfer;SetFileDestination:TRUE" />
<Expression patternEx="^createfolders=(.*)" replaceEx="createfolders:\1" />
<Expression patternEx="^overwrite=(.*)" replaceEx="overwrite:\1" />
<!-- Signature Capture Contents -->
<Expression patternEx="^noborder$" replaceEx="border:hidden" />
<Expression patternEx="^border$" replaceEx="border:visible" />
<Expression patternEx="^penwidth=(.*)" replaceEx="penwidth:\1" />
<Expression patternEx="^pencolor=(.*)" replaceEx="pencolor:\1" />
<Expression patternEx="^bgcolor=(.*)" replaceEx="bgcolor:\1" />
<Expression patternEx="^url=(.*)" replaceEx="destination:url('\1');" />
<Expression patternEx="^user=(.*)" replaceEx="username:\1" />
<Expression patternEx="^pass=(.*)" replaceEx="password:\1" />
<Expression patternEx="^name=(.*)" replaceEx="name:\1" />
<Expression patternEx="^aim=(on|off)" replaceEx="aim:\1" />
<Expression patternEx="^lamp=(on|off)" replaceEx="lamp:\1" />
<!-- Scanner (Decoders) Contents -->
<Expression patternEx="^autoenter$" replaceEx="autoenter:enabled" />
<Expression patternEx="^autotab$" replaceEx="autotab:enabled" />
<Expression patternEx="^RASTER_MODE_NONE$" replaceEx="rastermode:none" />
<Expression patternEx="^RASTER_MODE_OPEN_ALWAYS$" replaceEx="rastermode:open_always" />
<Expression patternEx="^RASTER_MODE_SMART$" replaceEx="rastermode:smart" />
<Expression patternEx="^RASTER_MODE_CYCLONE$" replaceEx="rastermode:cyclone" />
<Expression patternEx="^AIM_TYPE_TRIGGER$" replaceEx="aimtype:trigger" />
<Expression patternEx="^AIM_TYPE_TIMED_HOLD$" replaceEx="aimtype:timed_hold" />
<Expression patternEx="^AIM_TYPE_TIMED_RELEASE$" replaceEx="aimtype:timed_release" />
<Expression patternEx="^AIM_TYPE_CONTINUOUS_TRIGGER$" replaceEx="aimtype:continuous_trigger" />
<Expression patternEx="^AIM_TYPE_PRESENTATION$" replaceEx="aimtype:presentation" />
<Expression patternEx="^I2OF5_NO_CHECK_DIGIT$" replaceEx="none" />
<Expression patternEx="^I2OF5_USS_CHECK_DIGIT$" replaceEx="uss" />
<Expression patternEx="^I2OF5_OPCC_CHECK_DIGIT$" replaceEx="opcc" />
<Expression patternEx="^msi_chkdgt_mod_11_10$" replaceEx="mod_11_10" />
<Expression patternEx="^msi_chkdgt_mod_10_10$" replaceEx="mod_10_10" />
<Expression patternEx="^security_none$" replaceEx="none" />
<Expression patternEx="^security_ambiguous$" replaceEx="ambiguous" />
<Expression patternEx="^security_all$" replaceEx="all" />
<Expression patternEx="^supplementals_none$" replaceEx="none" />
<Expression patternEx="^supplementals_always$" replaceEx="always" />
<Expression patternEx="^supplementals_auto$" replaceEx="auto" />
<Expression patternEx="^PREAMBLE_NONE$" replaceEx="none" />
<Expression patternEx="^PREAMBLE_SYSTEM_CHAR$" replaceEx="system_char" />
<Expression patternEx="^PREAMBLE_COUNTRY_AND_SYSTEM_CHARS$" replaceEx="country_and_system_chars" />
<!-- Indicators Contents -->
<Expression patternEx="^Left_GrowFromTop$" replaceEx="IconPosition:Left;GraphPosition:Top" />
<Expression patternEx="^Right_GrowFromTop$" replaceEx="IconPosition:Right;GraphPosition:Top" />
<Expression patternEx="^Bottom_GrowFromRight$" replaceEx="IconPosition:Bottom;GraphPosition:Right" />
<Expression patternEx="^Top_GrowFromRight$" replaceEx="IconPosition:Top;GraphPosition:Right" />
<Expression patternEx="^Left_GrowFromBottom$" replaceEx="IconPosition:Left;GraphPosition:Bottom" />
<Expression patternEx="^Right_GrowFromBottom$" replaceEx="IconPosition:Right;GraphPosition:Bottom" />
<Expression patternEx="^Bottom_GrowFromLeft$" replaceEx="IconPosition:bottom;GraphPosition:left" />
<Expression patternEx="^Top_GrowFromLeft$" replaceEx="IconPosition:top;GraphPosition:left" />
<!-- Card Reader Contents -->
<Expression patternEx="^pintimeout=([0-9]+)" replaceEx="pintimeout:\1" />
<Expression patternEx="^pinentry=(on|off)" replaceEx="pinentry:\1" />
<Expression patternEx="^pandata=(.*)" replaceEx="pandata:\1" />
<!-- Key Capture Contents -->
<Expression patternEx="^remapto:(.*)" replaceEx="remapto=\1" />
<!-- Device & Application Contents -->
<Expression patternEx="^Interval=([0-9][0-9]):([0-9][0-9]):([0-9][0-9])" replaceEx="Interval:\1-\2-\3" />
<Expression patternEx="^Repeat=(true|false)" replaceEx="Repeat:\1" />
<Expression patternEx="^ServerIP:(.*)" replaceEx="SntpServerIP:\1" />
<!-- Alarm Time Parameter -->
<Expression patternEx="^Time=([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])t([0-9][0-9]):([0-9][0-9]):([0-9][0-9])([+-][0-9][0-9]):([0-9][0-9])" replaceEx="Time:\1-\2-\3t\4-\5-\6\7-\8" />
<!-- Push Contents -->
<Expression patternEx="^Port=([0-9]+)" replaceEx="Port:\1" />
<Expression patternEx="^Passkey=(.+)" replaceEx="Passkey:\1" />
<Expression patternEx="^Passkey=$" replaceEx="Passkey:url('')" />
<!-- EMML Profile Contents -->
<Expression patternEx="^Import:(.*)$" replaceEx="ImportProfile:\1" />
<!-- Telemetry Parameters -->
<Expression patternEx="^Enable(ABSControlStatus)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(ThrottlePosition)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(ServiceBrakeSwitch)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(IgnitionStatus)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(ParkingBrakeSwitch)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(RoadSpeed)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(CruiseControlSwitch)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(BrakesSwitch)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(ClutchStatus)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(CruiseControlSetSpeed)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(AcceleratorPedalPos)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineLoad)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineOilPressure)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(BoostPressure)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineCoolantTemperature)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineRetarderStatus)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(ATC_ASR_Status)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TransmissionRangeSelected)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TransmissionRangeAttained)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(BatteryVoltage)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineOilTemperature)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TransmissionOilTemperature)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(FuelRate)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(InstantaneousFuelEconomy)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(AverageFuelEconomy)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(EngineRPM)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TransmitterDiagnosticCode)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TransmitterDiagnosticTable)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(VehicleIDNumber)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(VehicleGlobalPosition)$" replaceEx="Enable:\1" />
<Expression patternEx="^Enable(TotalDistance)$" replaceEx="Enable:\1" />
<!-- Disable Parameters -->
<Expression patternEx="^Disable(ABSControlStatus)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(ThrottlePosition)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(ServiceBrakeSwitch)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(IgnitionStatus)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(ParkingBrakeSwitch)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(RoadSpeed)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(CruiseControlSwitch)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(BrakesSwitch)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(ClutchStatus)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(CruiseControlSetSpeed)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(AcceleratorPedalPos)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineLoad)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineOilPressure)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(BoostPressure)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineCoolantTemperature)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineRetarderStatus)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(ATC_ASR_Status)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TransmissionRangeSelected)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TransmissionRangeAttained)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(BatteryVoltage)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineOilTemperature)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TransmissionOilTemperature)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(FuelRate)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(InstantaneousFuelEconomy)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(AverageFuelEconomy)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(EngineRPM)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TransmitterDiagnosticCode)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TransmitterDiagnosticTable)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(VehicleIDNumber)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(VehicleGlobalPosition)$" replaceEx="Disable:\1" />
<Expression patternEx="^Disable(TotalDistance)$" replaceEx="Disable:\1" />
</Contents>
</RegularEx> | 412 | 0.777952 | 1 | 0.777952 | game-dev | MEDIA | 0.272343 | game-dev | 0.525963 | 1 | 0.525963 |
tqjxlm/Atlas | 6,967 | libs/CrowdSim/libpedsim/ped_tree.cpp | //
// pedsim - A microscopic pedestrian simulation system.
// Copyright (c) by Christian Gloor
//
#include "ped_agent.h"
#include "ped_scene.h"
#include "ped_tree.h"
#include <cassert>
#include <cstddef>
using namespace std;
/// Description: set intial values
/// \author chgloor
/// \date 2012-01-28
Ped::Ttree::Ttree(Ped::Tscene *pscene, int pdepth, double px, double py, double pw, double ph) : scene(pscene) {
// more initializations here. not really necessary to put them into the initializator list, too.
isleaf = true;
x = px;
y = py;
w = pw;
h = ph;
depth = pdepth;
tree1 = NULL;
tree2 = NULL;
tree3 = NULL;
tree4 = NULL;
};
/// Destructor. Deleted this node and all its children. If there are any agents left, they are removed first (not deleted).
/// \author chgloor
/// \date 2012-01-28
Ped::Ttree::~Ttree() {
clear();
}
void Ped::Ttree::clear() {
if(isleaf) {
agents.clear();
}
else {
tree1->clear();
delete tree1;
tree2->clear();
delete tree2;
tree3->clear();
delete tree3;
tree4->clear();
delete tree4;
isleaf = true;
}
}
/// Adds an agent to the tree. Searches the right node and adds the agent there.
/// If there are too many agents at that node allready, a new child is created.
/// \author chgloor
/// \date 2012-01-28
/// \param *a The agent to add
void Ped::Ttree::addAgent(const Ped::Tagent *a) {
if (isleaf) {
agents.insert(a);
scene->treehash[a] = this;
}
else {
const Tvector pos = a->getPosition();
if ((pos.x >= x+w/2) && (pos.y >= y+h/2)) tree3->addAgent(a); // 3
if ((pos.x <= x+w/2) && (pos.y <= y+h/2)) tree1->addAgent(a); // 1
if ((pos.x >= x+w/2) && (pos.y <= y+h/2)) tree2->addAgent(a); // 2
if ((pos.x <= x+w/2) && (pos.y >= y+h/2)) tree4->addAgent(a); // 4
}
if (agents.size() > 8) {
isleaf = false;
addChildren();
while (!agents.empty()) {
const Ped::Tagent *a = (*agents.begin());
const Tvector pos = a->getPosition();
if ((pos.x >= x+w/2) && (pos.y >= y+h/2)) tree3->addAgent(a); // 3
if ((pos.x <= x+w/2) && (pos.y <= y+h/2)) tree1->addAgent(a); // 1
if ((pos.x >= x+w/2) && (pos.y <= y+h/2)) tree2->addAgent(a); // 2
if ((pos.x <= x+w/2) && (pos.y >= y+h/2)) tree4->addAgent(a); // 4
agents.erase(a);
}
}
}
/// A little helper that adds child nodes to this node
/// \author chgloor
/// \date 2012-01-28
void Ped::Ttree::addChildren() {
tree1 = new Ped::Ttree(scene, depth+1, x, y, w/2, h/2);
tree2 = new Ped::Ttree(scene, depth+1, x+w/2, y, w/2, h/2);
tree3 = new Ped::Ttree(scene, depth+1, x+w/2, y+h/2, w/2, h/2);
tree4 = new Ped::Ttree(scene, depth+1, x, y+h/2, w/2, h/2);
}
Ped::Ttree* Ped::Ttree::getChildByPosition(double xIn, double yIn) {
if((xIn <= x+w/2) && (yIn <= y+h/2))
return tree1;
if((xIn >= x+w/2) && (yIn <= y+h/2))
return tree2;
if((xIn >= x+w/2) && (yIn >= y+h/2))
return tree3;
if((xIn <= x+w/2) && (yIn >= y+h/2))
return tree4;
// this should never happen
return NULL;
}
/// Updates the tree structure if an agent moves. Removes the agent and places it again, if outside boundary.
/// If an this happens, this is O(log n), but O(1) otherwise.
/// \author chgloor
/// \date 2012-01-28
/// \param *a the agent to update
void Ped::Ttree::moveAgent(const Ped::Tagent *a) {
const Tvector pos = a->getPosition();
if ((pos.x < x) || (pos.x > (x+w)) || (pos.y < y) || (pos.y > (y+h))) {
scene->placeAgent(a);
agents.erase(a);
}
}
bool Ped::Ttree::removeAgent(const Ped::Tagent *a) {
if(isleaf) {
size_t removedCount = agents.erase(a);
return (removedCount > 0);
}
else {
const Tvector pos = a->getPosition();
return getChildByPosition(pos.x, pos.y)->removeAgent(a);
}
}
/// Checks if this tree node has not enough agents in it to justify more child nodes. It does this by checking all
/// child nodes, too, recursively. If there are not enough children, it moves all the agents into this node, and deletes the child nodes.
/// \author chgloor
/// \date 2012-01-28
/// \return the number of agents in this and all child nodes.
int Ped::Ttree::cut() {
if (isleaf)
return agents.size();
int count = 0;
count += tree1->cut();
count += tree2->cut();
count += tree3->cut();
count += tree4->cut();
if (count < 5) {
assert(tree1->isleaf == true);
assert(tree2->isleaf == true);
assert(tree3->isleaf == true);
assert(tree4->isleaf == true);
agents.insert(tree1->agents.begin(), tree1->agents.end());
agents.insert(tree2->agents.begin(), tree2->agents.end());
agents.insert(tree3->agents.begin(), tree3->agents.end());
agents.insert(tree4->agents.begin(), tree4->agents.end());
isleaf = true;
for (set<const Ped::Tagent*>::iterator it = agents.begin(); it != agents.end(); ++it) {
const Tagent *a = (*it);
scene->treehash[a] = this;
}
delete tree1;
delete tree2;
delete tree3;
delete tree4;
}
return count;
}
/// Returns the set of agents that is stored within this tree node
/// \author chgloor
/// \date 2012-01-28
/// \return The set of agents
/// \todo This might be not very efficient, since all childs are checked, too. And then the set (set of pointer, but still) is being copied around.
set<const Ped::Tagent*> Ped::Ttree::getAgents() const {
if (isleaf)
return agents;
set<const Ped::Tagent*> ta;
set<const Ped::Tagent*> t1 = tree1->getAgents();
set<const Ped::Tagent*> t2 = tree2->getAgents();
set<const Ped::Tagent*> t3 = tree3->getAgents();
set<const Ped::Tagent*> t4 = tree4->getAgents();
ta.insert(t1.begin(), t1.end());
ta.insert(t2.begin(), t2.end());
ta.insert(t3.begin(), t3.end());
ta.insert(t4.begin(), t4.end());
return ta;
}
void Ped::Ttree::getAgents(list<const Ped::Tagent*>& outputList) const {
if(isleaf) {
for(const Ped::Tagent* currentAgent : agents)
outputList.push_back(currentAgent);
}
else {
tree1->getAgents(outputList);
tree2->getAgents(outputList);
tree3->getAgents(outputList);
tree4->getAgents(outputList);
}
}
/// Checks if a point x/y is within the space handled by the tree node, or within a given radius r
/// \author chgloor
/// \date 2012-01-29
/// \return true if the point is within the space
/// \param px The x co-ordinate of the point
/// \param py The y co-ordinate of the point
/// \param pr The radius
bool Ped::Ttree::intersects(double px, double py, double pr) const {
if (((px+pr) > x) && ((px-pr) < (x+w)) && ((py+pr) > y) && ((py-pr) < (y+h)))
return true; // x+-r/y+-r is inside
else
return false;
}
| 412 | 0.919839 | 1 | 0.919839 | game-dev | MEDIA | 0.245478 | game-dev | 0.974505 | 1 | 0.974505 |
hlrs-vis/covise | 5,157 | src/OpenCOVER/DrivingSim/VehicleUtil/VehicleUtil.cpp | /* This file is part of COVISE.
You can use it under the terms of the GNU Lesser General Public License
version 2.1 or later, see lgpl-2.1.txt.
* License: LGPL 2+ */
#include "VehicleUtil.h"
#include <unistd.h>
using namespace vehicleUtil;
// VehicleUtil ///////////////////////////////////////////////////////
// set protected static pointer for singleton to NULL
VehicleUtil *VehicleUtil::p_vutil = NULL;
// constructor, destructor, instance ---------------------------------
VehicleUtil::VehicleUtil()
{
p_DeviceList = new std::list<HMIDeviceIface *>;
//opencover::coShutDownHandlerList::instance()->addHandler(this);
p_CANProv = CANProvider::instance();
m_vehiclestate = KEYOUT;
}
VehicleUtil::~VehicleUtil()
{
// free list
delete p_DeviceList;
}
// singleton
VehicleUtil *VehicleUtil::instance()
{
if (p_vutil == NULL)
{
p_vutil = new VehicleUtil();
}
return p_vutil;
}
//--------------------------------------------------------------------
// public methods ----------------------------------------------------
/**
* HMI devices use this method to add themselves to a list which is
* applied to set a consolidated vehicle state and to shutdown the
* devices
*
* @param HMIDeviceIface* a HMI device
* @return none
*/
void VehicleUtil::addDevice(HMIDeviceIface *device)
{
std::list<HMIDeviceIface *>::iterator i = p_DeviceList->begin();
// check if the device is not already in list - if yes, return
while (i != p_DeviceList->end())
{
if ((*i) == device)
{
return;
}
i++;
}
// add device to device list
p_DeviceList->push_back(device);
}
/**
* With this method the state of the vehicle can be controlled. It
* provides for a consolidated state of all ecus / HMI devices. The
* state is also controlled by comparing m_vehiclestate with the
* newly demanded state
*
* @param int a state, see enum in header file
* @return none
*/
void VehicleUtil::setVehicleState(int demandedstate)
{
std::list<HMIDeviceIface *>::iterator i = p_DeviceList->begin();
// key is out of ignition lock
if (demandedstate == KEYOUT && m_vehiclestate == KEYIN)
{
p_CANProv->keyIsOut();
i = p_DeviceList->begin(); // get position of first list entry
while (i != p_DeviceList->end())
{
(*i)->shutDownDevice();
i++;
}
m_vehiclestate = KEYOUT;
}
// key is in ignition lock
else if (demandedstate == KEYIN && m_vehiclestate == KEYOUT)
{
p_CANProv->keyIsIn();
i = p_DeviceList->begin();
while (i != p_DeviceList->end())
{
(*i)->keyInLock(0); // keynumber should be added in the future
i++;
}
m_vehiclestate = KEYIN;
}
// key was turned to "Ignite" position
else if (demandedstate == KEYIN_IGNITED && m_vehiclestate == KEYIN)
{
p_CANProv->ignitionIsOn();
i = p_DeviceList->begin();
while (i != p_DeviceList->end())
{
(*i)->ignitionOn();
i++;
}
m_vehiclestate = KEYIN_IGNITED;
}
// key is in "Start engine" position / engine is started
else if (demandedstate == KEYIN_ESTART && m_vehiclestate == KEYIN_IGNITED)
{
p_CANProv->engineIsStarted();
i = p_DeviceList->begin();
while (i != p_DeviceList->end())
{
(*i)->initDevice();
i++;
}
m_vehiclestate = KEYIN_ESTART;
}
// engine was started
else if (demandedstate == KEYIN_ERUNNING && m_vehiclestate == KEYIN_ESTART)
{
p_CANProv->engineIsRunning();
i = p_DeviceList->begin();
while (i != p_DeviceList->end())
{
(*i)->startDevice();
i++;
}
m_vehiclestate = KEYIN_ERUNNING;
}
// key was turned to "Stop engine" position
else if (demandedstate == KEYIN_ESTOP && (m_vehiclestate == KEYIN_ERUNNING || m_vehiclestate == KEYIN_IGNITED || m_vehiclestate == KEYIN_ESTART))
{
p_CANProv->keyIsIn();
i = p_DeviceList->begin();
while (i != p_DeviceList->end())
{
(*i)->stopDevice();
i++;
}
m_vehiclestate = KEYIN;
}
}
/**
* With this method the HMI devices and the CANProvider are stopped,
* shutdown and the CANProvider singleton and the HMI device classses
* singletons are deleted subsequently!
*
* @param none
* @return none
*/
void VehicleUtil::shutDown()
{
std::list<HMIDeviceIface *>::iterator i;
// stop all HMIDeviceIfaces in list
setVehicleState(KEYIN_ESTOP);
sleep(1);
// shutDown all HMIDeviceIfaces in list
setVehicleState(KEYOUT);
sleep(1);
// shut down CANProvider
p_CANProv->shutdown();
// call destructor of all HMIDeviceIfaces in list
for (i = p_DeviceList->begin(); i != p_DeviceList->end(); ++i)
{
delete (*i);
}
// call destructor of CANProvider
delete p_CANProv;
}
//--------------------------------------------------------------------
| 412 | 0.966774 | 1 | 0.966774 | game-dev | MEDIA | 0.58617 | game-dev | 0.957578 | 1 | 0.957578 |
soot-oss/SootUp | 8,233 | sootup.apk.frontend/src/main/java/sootup/apk/frontend/dexpler/DexFileProvider.java | package sootup.apk.frontend.dexpler;
/*-
* #%L
* SootUp
* %%
* Copyright (C) 2022 - 2024 Kadiray Karakaya, Markus Schmidt, Jonas Klauke, Stefan Schott, Palaniappan Muthuraman, Marcus Hüwe and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.DexFile;
import org.jf.dexlib2.iface.MultiDexContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DexFileProvider {
private final Logger logger = LoggerFactory.getLogger(DexFileProvider.class);
private int api_version;
private static DexFileProvider instance;
public static DexFileProvider getInstance() {
if (instance == null) {
instance = new DexFileProvider();
}
return instance;
}
public static final class DexContainer<T extends DexFile> {
private final MultiDexContainer.DexEntry<T> base;
private final String name;
private final File filePath;
public DexContainer(MultiDexContainer.DexEntry<T> base, String name, File filePath) {
this.base = base;
this.name = name;
this.filePath = filePath;
}
public MultiDexContainer.DexEntry<T> getBase() {
return base;
}
public String getDexName() {
return name;
}
}
/** Mapping of filesystem file (apk, dex, etc.) to mapping of dex name to dex file */
private final Map<String, Map<String, DexContainer<? extends DexFile>>> dexMap = new HashMap<>();
/**
* Returns all dex files found in dex source
*
* @param dexSource Path to a jar, apk, dex, odex or a directory containing multiple dex files
* @param api_version the version of the currently instrumenting APK
* @return List of dex files derived from source
* @throws IOException if the dex source is not parsed properly
*/
public List<DexContainer<? extends DexFile>> getDexFromSource(File dexSource, int api_version)
throws IOException {
this.api_version = api_version;
return getDexFromSource(dexSource, DEFAULT_PRIORITIZER);
}
public List<DexContainer<? extends DexFile>> getDexFromSource(
File dexSource, Comparator<DexContainer<? extends DexFile>> prioritizer) throws IOException {
ArrayList<DexContainer<? extends DexFile>> resultList = new ArrayList<>();
List<File> allSources = allSourcesFromFile(dexSource);
updateIndex(allSources);
for (File theSource : allSources) {
resultList.addAll(dexMap.get(theSource.getCanonicalPath()).values());
}
if (resultList.size() > 1) {
resultList.sort(Collections.reverseOrder(prioritizer));
}
return resultList;
}
private void updateIndex(List<File> dexSources) throws IOException {
for (File theSource : dexSources) {
String key = theSource.getCanonicalPath();
Map<String, DexContainer<? extends DexFile>> dexFiles = dexMap.get(key);
if (dexFiles == null) {
try {
dexFiles = mappingForFile(theSource);
dexMap.put(key, dexFiles);
} catch (IOException e) {
throw new IllegalStateException("Error parsing dex source", e);
}
}
}
}
/**
* @param dexSourceFile A file containing either one or multiple dex files (apk, zip, etc.) but no
* directory!
* @return
* @throws IOException
*/
private Map<String, DexContainer<? extends DexFile>> mappingForFile(File dexSourceFile)
throws IOException {
// load dex files from apk/folder/file
boolean multiple_dex = true;
MultiDexContainer<? extends DexBackedDexFile> dexContainer =
DexFileFactory.loadDexContainer(dexSourceFile, Opcodes.forApi(api_version));
List<String> dexEntryNameList = dexContainer.getDexEntryNames();
int dexFileCount = dexEntryNameList.size();
if (dexFileCount < 1) {
return Collections.emptyMap();
}
Map<String, DexContainer<? extends DexFile>> dexMap = new HashMap<>(dexFileCount);
// report found dex files and add to list.
// We do this in reverse order to make sure that we add the first entry if there is no
// classes.dex file in single dex
// mode
ListIterator<String> entryNameIterator = dexEntryNameList.listIterator(dexFileCount);
while (entryNameIterator.hasPrevious()) {
String entryName = entryNameIterator.previous();
MultiDexContainer.DexEntry<? extends DexFile> entry = dexContainer.getEntry(entryName);
entryName = deriveDexName(entryName);
logger.debug(
String.format(
"Found dex file '%s' with %d classes in '%s'",
entryName, entry.getDexFile().getClasses().size(), dexSourceFile.getCanonicalPath()));
if (multiple_dex) {
dexMap.put(entryName, new DexContainer<>(entry, entryName, dexSourceFile));
} else if (dexMap.isEmpty()
&& (entryName.equals("classes.dex") || !entryNameIterator.hasPrevious())) {
// We prefer to have classes.dex in single dex mode.
// If we haven't found a classes.dex until the last element, take the last!
dexMap =
Collections.singletonMap(
entryName, new DexContainer<>(entry, entryName, dexSourceFile));
if (dexFileCount > 1) {
logger.warn(
"Multiple dex files detected, only processing '"
+ entryName
+ "'. Use '-process-multiple-dex' option to process them all.");
}
}
}
return Collections.unmodifiableMap(dexMap);
}
public List<File> allSourcesFromFile(File dexSource) {
if (dexSource.isDirectory()) {
List<File> dexFiles = getAllDexFilesInDirectory(dexSource);
return dexFiles;
} else {
String ext = com.google.common.io.Files.getFileExtension(dexSource.getName()).toLowerCase();
if ((ext.equals("jar") || ext.equals("zip"))) {
return Collections.emptyList();
} else {
return Collections.singletonList(dexSource);
}
}
}
private List<File> getAllDexFilesInDirectory(File path) {
Queue<File> toVisit = new ArrayDeque<File>();
Set<File> visited = new HashSet<File>();
List<File> ret = new ArrayList<File>();
toVisit.add(path);
while (!toVisit.isEmpty()) {
File cur = toVisit.poll();
if (visited.contains(cur)) {
continue;
}
visited.add(cur);
if (cur.isDirectory()) {
toVisit.addAll(Arrays.asList(cur.listFiles()));
} else if (cur.isFile() && cur.getName().endsWith(".dex")) {
ret.add(cur);
}
}
return ret;
}
private String deriveDexName(String entryName) {
return new File(entryName).getName();
}
private static final Comparator<DexContainer<? extends DexFile>> DEFAULT_PRIORITIZER =
(o1, o2) -> {
String s1 = o1.getDexName(), s2 = o2.getDexName();
// "classes.dex" has highest priority
if (s1.equals("classes.dex")) {
return 1;
} else if (s2.equals("classes.dex")) {
return -1;
}
// if one of the strings starts with "classes", we give it the edge right here
boolean s1StartsClasses = s1.startsWith("classes");
boolean s2StartsClasses = s2.startsWith("classes");
if (s1StartsClasses && !s2StartsClasses) {
return 1;
} else if (s2StartsClasses && !s1StartsClasses) {
return -1;
}
// otherwise, use natural string ordering
return s1.compareTo(s2);
};
}
| 412 | 0.789903 | 1 | 0.789903 | game-dev | MEDIA | 0.341227 | game-dev | 0.967514 | 1 | 0.967514 |
modernuo/ModernUO | 2,634 | Projects/UOContent/Engines/Khaldun/Mobiles/LysanderGathenwale.cs | using ModernUO.Serialization;
using Server.Items;
namespace Server.Mobiles;
[SerializationGenerator(0, false)]
public partial class LysanderGathenwale : BaseCreature
{
[Constructible]
public LysanderGathenwale() : base(AIType.AI_Mage)
{
Title = "the Cursed";
Hue = 0x8838;
Body = 0x190;
AddItem(new Boots(0x599));
AddItem(new Cloak(0x96F));
var spellbook = new Spellbook();
var gloves = new RingmailGloves();
var chest = new StuddedChest();
var arms = new PlateArms();
spellbook.Hue = 0x599;
gloves.Hue = 0x599;
chest.Hue = 0x96F;
arms.Hue = 0x599;
AddItem(spellbook);
AddItem(gloves);
AddItem(chest);
AddItem(arms);
SetStr(111, 120);
SetDex(71, 80);
SetInt(121, 130);
SetHits(180, 207);
SetMana(227, 265);
SetDamage(5, 13);
SetResistance(ResistanceType.Physical, 35, 45);
SetResistance(ResistanceType.Fire, 25, 30);
SetResistance(ResistanceType.Cold, 50, 60);
SetResistance(ResistanceType.Poison, 25, 35);
SetResistance(ResistanceType.Energy, 25, 35);
SetSkill(SkillName.Wrestling, 80.1, 90.0);
SetSkill(SkillName.Tactics, 90.1, 100.0);
SetSkill(SkillName.MagicResist, 80.1, 90.0);
SetSkill(SkillName.Magery, 90.1, 100.0);
SetSkill(SkillName.EvalInt, 95.1, 100.0);
SetSkill(SkillName.Meditation, 90.1, 100.0);
Fame = 5000;
Karma = -10000;
var reags = Loot.RandomReagent();
reags.Amount = 30;
PackItem(reags);
}
public override bool ClickTitle => false;
public override bool ShowFameTitle => false;
public override bool DeleteCorpseOnDeath => true;
public override string DefaultName => "Lysander Gatherwale";
public override bool AlwaysMurderer => true;
public override int GetIdleSound() => 0x1CE;
public override int GetAngerSound() => 0x1AC;
public override int GetDeathSound() => 0x182;
public override int GetHurtSound() => 0x28D;
public override void GenerateLoot()
{
AddLoot(LootPack.MedScrolls, 2);
}
public override bool OnBeforeDeath()
{
if (!base.OnBeforeDeath())
{
return false;
}
Backpack?.Destroy();
if (Utility.Random(3) == 0)
{
var notebook = Loot.RandomLysanderNotebook();
notebook.MoveToWorld(Location, Map);
}
Effects.SendLocationEffect(Location, Map, 0x376A, 10, 1);
return true;
}
}
| 412 | 0.9231 | 1 | 0.9231 | game-dev | MEDIA | 0.961835 | game-dev | 0.914869 | 1 | 0.914869 |
Rosewood-Development/RoseStacker | 28,621 | NMS/v1_20_R4/src/main/java/dev/rosewood/rosestacker/nms/v1_20_R4/NMSHandlerImpl.java | package dev.rosewood.rosestacker.nms.v1_20_R4;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import dev.rosewood.rosegarden.utils.NMSUtil;
import dev.rosewood.rosestacker.nms.NMSHandler;
import dev.rosewood.rosestacker.nms.hologram.Hologram;
import dev.rosewood.rosestacker.nms.spawner.StackedSpawnerTile;
import dev.rosewood.rosestacker.nms.storage.EntityDataEntry;
import dev.rosewood.rosestacker.nms.storage.StackedEntityDataStorage;
import dev.rosewood.rosestacker.nms.storage.StackedEntityDataStorageType;
import dev.rosewood.rosestacker.nms.storage.StorageMigrationType;
import dev.rosewood.rosestacker.nms.util.ReflectionUtils;
import dev.rosewood.rosestacker.nms.v1_20_R4.entity.SoloEntitySpider;
import dev.rosewood.rosestacker.nms.v1_20_R4.entity.SoloEntityStrider;
import dev.rosewood.rosestacker.nms.v1_20_R4.event.AsyncEntityDeathEventImpl;
import dev.rosewood.rosestacker.nms.v1_20_R4.hologram.HologramImpl;
import dev.rosewood.rosestacker.nms.v1_20_R4.spawner.StackedSpawnerTileImpl;
import dev.rosewood.rosestacker.nms.v1_20_R4.storage.NBTEntityDataEntry;
import dev.rosewood.rosestacker.nms.v1_20_R4.storage.NBTStackedEntityDataStorage;
import dev.rosewood.rosestacker.nms.v1_20_R4.storage.SimpleStackedEntityDataStorage;
import dev.rosewood.rosestacker.stack.StackedSpawner;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.entity.SpawnGroupData;
import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.ai.control.JumpControl;
import net.minecraft.world.entity.ai.control.LookControl;
import net.minecraft.world.entity.ai.control.MoveControl;
import net.minecraft.world.entity.ai.goal.FloatGoal;
import net.minecraft.world.entity.ai.goal.GoalSelector;
import net.minecraft.world.entity.ai.goal.WrappedGoal;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.animal.Rabbit;
import net.minecraft.world.entity.monster.Spider;
import net.minecraft.world.entity.monster.Strider;
import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.entity.raid.Raider;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.trading.MerchantOffers;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.SpawnerBlockEntity;
import net.minecraft.world.level.entity.PersistentEntitySectionManager;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.levelgen.ThreadSafeLegacyRandomSource;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_20_R4.CraftWorld;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftAbstractVillager;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftCreeper;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftItem;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftLivingEntity;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_20_R4.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_20_R4.util.CraftChatMessage;
import org.bukkit.craftbukkit.v1_20_R4.util.CraftNamespacedKey;
import org.bukkit.entity.AbstractVillager;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import sun.misc.Unsafe;
@SuppressWarnings("unchecked")
public class NMSHandlerImpl implements NMSHandler {
private static boolean hijackedAnyRandomSources = false;
private static EntityDataAccessor<Boolean> value_Creeper_DATA_IS_IGNITED; // DataWatcherObject that determines if a creeper is ignited, normally private
private static Field field_GoalSelector_availableGoals; // Field to get the available pathing goals of a mob, normally private
private static Field field_Mob_lookControl; // Field to get the look controller of a mob, normally protected
private static Field field_Mob_moveControl; // Field to get the move controller of a mob, normally protected
private static Field field_Mob_jumpControl; // Field to get the jump controller of a mob, normally protected
private static Field field_LivingEntity_brain; // Field to get the brain of a living entity, normally protected
private static Field field_ServerLevel_entityManager; // Field to get the persistent entity section manager, normally private
private static Field field_ServerLevel_entityLookup; // Field to get the entity lookup which is part of paper's chunk system
private static Method method_EntityLookup_addNewEntity; // Method to add a new entity which is part of paper's chunk system
private static Field field_Entity_spawnReason; // Spawn reason field (only on Paper servers, will be null for Spigot)
private static AtomicInteger entityCounter; // Atomic integer to generate unique entity IDs, normally private
private static Unsafe unsafe;
private static long field_SpawnerBlockEntity_spawner_offset; // Field offset for modifying SpawnerBlockEntity's spawner field
private static long field_Level_random_offset; // Field offset for modifying LevelAccess's random field
private static Field field_LegacyRandomSource_seed; // Field to get the seed of a LegacyRandomSource, normally private
private static Field field_AbstractVillager_offers; // Field to get the offers of an AbstractVillager, normally private
private static Field field_Entity_spawnedViaMobSpawner; // Field to get the spawnedViaMobSpawner of an Entity, added by Paper, normally public
private static Field field_ItemEntity_despawnRate; // Field to get the despawn rate of an ItemEntity
static {
try {
Field field_Creeper_DATA_IS_IGNITED = ReflectionUtils.getFieldByPositionAndType(net.minecraft.world.entity.monster.Creeper.class, 2, EntityDataAccessor.class);
value_Creeper_DATA_IS_IGNITED = (EntityDataAccessor<Boolean>) field_Creeper_DATA_IS_IGNITED.get(null);
field_GoalSelector_availableGoals = ReflectionUtils.getFieldByPositionAndType(GoalSelector.class, 0, Set.class);
field_Mob_lookControl = ReflectionUtils.getFieldByPositionAndType(Mob.class, 0, LookControl.class);
field_Mob_moveControl = ReflectionUtils.getFieldByPositionAndType(Mob.class, 0, MoveControl.class);
field_Mob_jumpControl = ReflectionUtils.getFieldByPositionAndType(Mob.class, 0, JumpControl.class);
field_LivingEntity_brain = ReflectionUtils.getFieldByPositionAndType(net.minecraft.world.entity.LivingEntity.class, 0, Brain.class);
try {
// Handle Paper's chunk system
field_ServerLevel_entityManager = ReflectionUtils.getFieldByPositionAndType(ServerLevel.class, 0, PersistentEntitySectionManager.class);
} catch (IllegalStateException e) {
field_ServerLevel_entityManager = null;
field_ServerLevel_entityLookup = ReflectionUtils.getFieldByName(ServerLevel.class, "entityLookup");
}
if (NMSUtil.isPaper())
field_Entity_spawnReason = ReflectionUtils.getFieldByPositionAndType(Entity.class, 0, SpawnReason.class);
entityCounter = (AtomicInteger) ReflectionUtils.getFieldByPositionAndType(Entity.class, 0, AtomicInteger.class).get(null);
Field field_SpawnerBlockEntity_spawner = ReflectionUtils.getFieldByPositionAndType(SpawnerBlockEntity.class, 0, BaseSpawner.class);
Field field_Level_random = ReflectionUtils.getFieldByPositionAndType(Level.class, 0, RandomSource.class);
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = (Unsafe) unsafeField.get(null);
field_SpawnerBlockEntity_spawner_offset = unsafe.objectFieldOffset(field_SpawnerBlockEntity_spawner);
field_Level_random_offset = unsafe.objectFieldOffset(field_Level_random);
field_LegacyRandomSource_seed = ReflectionUtils.getFieldByPositionAndType(LegacyRandomSource.class, 0, AtomicLong.class);
field_AbstractVillager_offers = ReflectionUtils.getFieldByPositionAndType(net.minecraft.world.entity.npc.AbstractVillager.class, 0, MerchantOffers.class);
if (NMSUtil.isPaper()) {
field_Entity_spawnedViaMobSpawner = ReflectionUtils.getFieldByName(Entity.class, "spawnedViaMobSpawner");
field_ItemEntity_despawnRate = ReflectionUtils.getFieldByName(net.minecraft.world.entity.item.ItemEntity.class, "despawnRate");
}
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
@Override
public LivingEntity createNewEntityUnspawned(EntityType entityType, Location location, SpawnReason spawnReason) {
World world = location.getWorld();
if (world == null)
return null;
Class<? extends org.bukkit.entity.Entity> entityClass = entityType.getEntityClass();
if (entityClass == null || !LivingEntity.class.isAssignableFrom(entityClass))
throw new IllegalArgumentException("EntityType must be of a LivingEntity");
net.minecraft.world.entity.EntityType<? extends Entity> nmsEntityType = BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(entityType.getKey()));
Entity nmsEntity = this.createCreature(
nmsEntityType,
((CraftWorld) world).getHandle(),
new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()),
this.toNmsSpawnReason(spawnReason)
);
return nmsEntity == null ? null : (LivingEntity) nmsEntity.getBukkitEntity();
}
/**
* Duplicate of {@link net.minecraft.world.entity.EntityType#create(ServerLevel, Consumer, BlockPos, MobSpawnType, boolean, boolean)}.
* Contains a patch to prevent chicken jockeys from spawning and to not play the mob sound upon creation.
*/
public <T extends Entity> T createCreature(net.minecraft.world.entity.EntityType<T> entityType, ServerLevel world, BlockPos blockPos, MobSpawnType mobSpawnType) {
T newEntity;
if (entityType == net.minecraft.world.entity.EntityType.SPIDER) {
newEntity = (T) new SoloEntitySpider((net.minecraft.world.entity.EntityType<? extends Spider>) entityType, world);
} else if (entityType == net.minecraft.world.entity.EntityType.STRIDER) {
newEntity = (T) new SoloEntityStrider((net.minecraft.world.entity.EntityType<? extends Strider>) entityType, world);
} else {
newEntity = entityType.create(world);
}
if (newEntity == null)
return null;
if (field_Entity_spawnReason != null) {
try {
field_Entity_spawnReason.set(newEntity, this.toBukkitSpawnReason(mobSpawnType));
} catch (IllegalAccessException ignored) {}
}
newEntity.moveTo(blockPos.getX() + 0.5D, blockPos.getY(), blockPos.getZ() + 0.5D, Mth.wrapDegrees(world.random.nextFloat() * 360.0F), 0.0F);
if (newEntity instanceof Mob mob) {
mob.yHeadRot = mob.getYRot();
mob.yBodyRot = mob.getYRot();
SpawnGroupData groupDataEntity = null;
if (entityType == net.minecraft.world.entity.EntityType.DROWNED
|| entityType == net.minecraft.world.entity.EntityType.HUSK
|| entityType == net.minecraft.world.entity.EntityType.ZOMBIE_VILLAGER
|| entityType == net.minecraft.world.entity.EntityType.ZOMBIFIED_PIGLIN
|| entityType == net.minecraft.world.entity.EntityType.ZOMBIE) {
// Don't allow chicken jockeys to spawn
groupDataEntity = new Zombie.ZombieGroupData(Zombie.getSpawnAsBabyOdds(world.getRandom()), false);
}
mob.finalizeSpawn(world, world.getCurrentDifficultyAt(mob.blockPosition()), mobSpawnType, groupDataEntity);
}
return newEntity;
}
@Override
public void spawnExistingEntity(LivingEntity entity, SpawnReason spawnReason, boolean bypassSpawnEvent) {
Location location = entity.getLocation();
World world = location.getWorld();
if (world == null)
throw new IllegalArgumentException("Entity is not in a loaded world");
if (bypassSpawnEvent) {
try {
this.addEntityToWorld(((CraftWorld) world).getHandle(), ((CraftEntity) entity).getHandle());
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
} else {
((CraftWorld) world).addEntityToWorld(((CraftEntity) entity).getHandle(), spawnReason);
}
}
@Override
public void updateEntityNameTagForPlayer(Player player, org.bukkit.entity.Entity entity, String customName, boolean customNameVisible) {
try {
List<SynchedEntityData.DataValue<?>> dataValues = new ArrayList<>();
Optional<Component> nameComponent = Optional.ofNullable(CraftChatMessage.fromStringOrNull(customName));
dataValues.add(SynchedEntityData.DataValue.create(EntityDataSerializers.OPTIONAL_COMPONENT.createAccessor(2), nameComponent));
dataValues.add(SynchedEntityData.DataValue.create(EntityDataSerializers.BOOLEAN.createAccessor(3), customNameVisible));
ClientboundSetEntityDataPacket entityDataPacket = new ClientboundSetEntityDataPacket(entity.getEntityId(), dataValues);
((CraftPlayer) player).getHandle().connection.send(entityDataPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void updateEntityNameTagVisibilityForPlayer(Player player, org.bukkit.entity.Entity entity, boolean customNameVisible) {
try {
List<SynchedEntityData.DataValue<?>> dataValues = Lists.newArrayList(SynchedEntityData.DataValue.create(EntityDataSerializers.BOOLEAN.createAccessor(3), customNameVisible));
ClientboundSetEntityDataPacket entityDataPacket = new ClientboundSetEntityDataPacket(entity.getEntityId(), dataValues);
((CraftPlayer) player).getHandle().connection.send(entityDataPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void unigniteCreeper(Creeper creeper) {
net.minecraft.world.entity.monster.Creeper nmsCreeper = ((CraftCreeper) creeper).getHandle();
nmsCreeper.getEntityData().set(value_Creeper_DATA_IS_IGNITED, false);
if (!Bukkit.getBukkitVersion().contains("1.17-"))
nmsCreeper.swell = nmsCreeper.maxSwell;
}
@Override
public void removeEntityGoals(LivingEntity livingEntity) {
net.minecraft.world.entity.LivingEntity nmsEntity = ((CraftLivingEntity) livingEntity).getHandle();
if (!(nmsEntity instanceof Mob))
return;
try {
Mob mob = (Mob) nmsEntity;
// Remove all goal AI other than floating in water
Set<WrappedGoal> goals = (Set<WrappedGoal>) field_GoalSelector_availableGoals.get(mob.goalSelector);
Iterator<WrappedGoal> goalsIterator = goals.iterator();
while (goalsIterator.hasNext()) {
WrappedGoal goal = goalsIterator.next();
if (goal.getGoal() instanceof FloatGoal)
continue;
goalsIterator.remove();
}
// Remove all targetting AI
((Set<WrappedGoal>) field_GoalSelector_availableGoals.get(mob.targetSelector)).clear();
// Forget any existing targets
mob.setTarget(null);
// Remove controllers
field_Mob_lookControl.set(mob, new LookControl(mob) {
public void tick() {}
});
field_Mob_moveControl.set(mob, new MoveControl(mob) {
public void tick() {}
});
if (mob instanceof Rabbit) {
field_Mob_jumpControl.set(mob, new Rabbit.RabbitJumpControl((Rabbit) mob) {
public void tick() {}
public boolean canJump() {return false;}
public boolean wantJump() {return false;}
});
} else {
field_Mob_jumpControl.set(mob, new JumpControl(mob) {
public void tick() {}
});
}
field_LivingEntity_brain.set(mob, new Brain(List.of(), List.of(), ImmutableList.of(), () -> Brain.codec(List.of(), List.of())) {
public Optional<?> getMemory(MemoryModuleType var0) {return Optional.empty();}
});
} catch (ReflectiveOperationException ex) {
ex.printStackTrace();
}
}
@Override
public ItemStack setItemStackNBT(ItemStack itemStack, String key, String value) {
net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack);
nmsItem.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, comp -> comp.update(currentNbt -> {
currentNbt.putString(key, value);
}));
return CraftItemStack.asBukkitCopy(nmsItem);
}
@Override
public ItemStack setItemStackNBT(ItemStack itemStack, String key, int value) {
net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack);
nmsItem.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, comp -> comp.update(currentNbt -> {
currentNbt.putInt(key, value);
}));
return CraftItemStack.asBukkitCopy(nmsItem);
}
@Override
public String getItemStackNBTString(ItemStack itemStack, String key) {
net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack);
CompoundTag tagCompound = nmsItem.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
return tagCompound.getString(key);
}
@Override
public int getItemStackNBTInt(ItemStack itemStack, String key) {
net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack);
CompoundTag tagCompound = nmsItem.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
return tagCompound.getInt(key);
}
@Override
public String getItemStackNBTStringFromCompound(ItemStack itemStack, String compoundKey, String valueKey) {
net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(itemStack);
CompoundTag tagCompound = nmsItem.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
CompoundTag targetCompound = tagCompound.getCompound(compoundKey);
if (targetCompound == null)
return "";
return targetCompound.getString(valueKey);
}
@Override
public void setLastHurtBy(LivingEntity livingEntity, Player player) {
if (player != null)
((CraftLivingEntity) livingEntity).getHandle().lastHurtByPlayer = ((CraftPlayer) player).getHandle();
}
@Override
public boolean hasLineOfSight(LivingEntity entity1, Location location) {
net.minecraft.world.entity.LivingEntity nmsEntity1 = ((CraftLivingEntity) entity1).getHandle();
Vec3 vec3d = new Vec3(nmsEntity1.getX(), nmsEntity1.getEyeY(), nmsEntity1.getZ());
Vec3 target = new Vec3(location.getX(), location.getY(), location.getZ());
return nmsEntity1.level().clip(new ClipContext(vec3d, target, ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, nmsEntity1)).getType() == HitResult.Type.MISS;
}
@Override
public boolean isActiveRaider(LivingEntity entity) {
return ((CraftLivingEntity) entity).getHandle() instanceof Raider raider && raider.getCurrentRaid() != null;
}
@Override
public EntityDataEntry createEntityDataEntry(LivingEntity livingEntity) {
return new NBTEntityDataEntry(livingEntity);
}
public StackedEntityDataStorage createEntityDataStorage(LivingEntity livingEntity, StackedEntityDataStorageType storageType) {
return switch (storageType) {
case NBT -> new NBTStackedEntityDataStorage(livingEntity);
case SIMPLE -> new SimpleStackedEntityDataStorage(livingEntity);
};
}
public StackedEntityDataStorage deserializeEntityDataStorage(LivingEntity livingEntity, byte[] data, StackedEntityDataStorageType storageType, Set<StorageMigrationType> migrations) {
return switch (storageType) {
case NBT -> new NBTStackedEntityDataStorage(livingEntity, data);
case SIMPLE -> new SimpleStackedEntityDataStorage(livingEntity, data);
};
}
@Override
public StackedSpawnerTile injectStackedSpawnerTile(Object stackedSpawnerObj) {
StackedSpawner stackedSpawner = (StackedSpawner) stackedSpawnerObj;
Block block = stackedSpawner.getBlock();
ServerLevel level = ((CraftWorld) block.getWorld()).getHandle();
BlockPos blockPos = new BlockPos(block.getX(), block.getY(), block.getZ());
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (!(blockEntity instanceof SpawnerBlockEntity spawnerBlockEntity))
return null;
StackedSpawnerTile stackedSpawnerTile = new StackedSpawnerTileImpl(spawnerBlockEntity.getSpawner(), spawnerBlockEntity, stackedSpawner);
unsafe.putObject(spawnerBlockEntity, field_SpawnerBlockEntity_spawner_offset, stackedSpawnerTile);
return stackedSpawnerTile;
}
@Override
public Hologram createHologram(Location location, List<String> text) {
return new HologramImpl(text, location, entityCounter::incrementAndGet);
}
@Override
public boolean supportsEmptySpawners() {
return true;
}
@Override
public void hijackRandomSource(World world) {
ServerLevel level = ((CraftWorld) world).getHandle();
if (!(level.random instanceof LegacyRandomSource))
return;
if (!hijackedAnyRandomSources)
hijackedAnyRandomSources = true;
try {
LegacyRandomSource originalRandomSource = (LegacyRandomSource) level.random;
AtomicLong seed = (AtomicLong) field_LegacyRandomSource_seed.get(originalRandomSource);
RandomSource hijackedRandomSource = new ThreadSafeLegacyRandomSource(seed.get());
unsafe.putObject(level, field_Level_random_offset, hijackedRandomSource);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
@Override
public void setPaperFromMobSpawner(org.bukkit.entity.Entity entity) {
if (field_Entity_spawnedViaMobSpawner == null)
return;
try {
field_Entity_spawnedViaMobSpawner.set(((CraftEntity) entity).getHandle(), true);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
@Override
public void setCustomNameUncapped(org.bukkit.entity.Entity entity, String customName) {
((CraftEntity) entity).getHandle().setCustomName(CraftChatMessage.fromStringOrNull(customName));
}
@Override
public int getItemDespawnRate(Item item) {
if (field_ItemEntity_despawnRate == null)
return ((CraftWorld) item.getWorld()).getHandle().spigotConfig.itemDespawnRate;
try {
return (int) field_ItemEntity_despawnRate.get(((CraftItem) item).getHandle());
} catch (ReflectiveOperationException e) {
e.printStackTrace();
throw new IllegalStateException("Unable to get item despawn rate");
}
}
@Override
public EntityDeathEvent createAsyncEntityDeathEvent(@NotNull LivingEntity what, @NotNull List<ItemStack> drops, int droppedExp) {
return new AsyncEntityDeathEventImpl(what, drops, droppedExp);
}
@Override
public List<org.bukkit.entity.Entity> getEntities(World world) {
CraftWorld craftWorld = (CraftWorld) world;
List<org.bukkit.entity.Entity> entities = new ArrayList<>();
for (Entity entity : craftWorld.getNMSEntities())
entities.add(entity.getBukkitEntity());
return entities;
}
public void addEntityToWorld(ServerLevel world, Entity entity) throws ReflectiveOperationException {
if (field_ServerLevel_entityManager != null) {
PersistentEntitySectionManager<Entity> entityManager = (PersistentEntitySectionManager<Entity>) field_ServerLevel_entityManager.get(world);
entityManager.addNewEntity(entity);
} else if (field_ServerLevel_entityLookup != null) {
Object entityLookup = field_ServerLevel_entityLookup.get(world);
if (method_EntityLookup_addNewEntity == null)
method_EntityLookup_addNewEntity = ReflectionUtils.getMethodByName(entityLookup.getClass(), "addNewEntity", Entity.class);
method_EntityLookup_addNewEntity.invoke(entityLookup, entity);
} else {
throw new IllegalStateException("Unable to spawn entities due to missing methods");
}
}
private SpawnReason toBukkitSpawnReason(MobSpawnType mobSpawnType) {
return switch (mobSpawnType) {
case SPAWN_EGG -> SpawnReason.SPAWNER_EGG;
case SPAWNER -> SpawnReason.SPAWNER;
default -> SpawnReason.CUSTOM;
};
}
private MobSpawnType toNmsSpawnReason(SpawnReason spawnReason) {
return switch (spawnReason) {
case SPAWNER_EGG -> MobSpawnType.SPAWN_EGG;
case SPAWNER -> MobSpawnType.SPAWNER;
default -> MobSpawnType.COMMAND;
};
}
public void saveEntityToTag(LivingEntity livingEntity, CompoundTag compoundTag) {
// Async villager "fix", if the trades aren't loaded yet force them to save as empty, they will get loaded later
if (livingEntity instanceof AbstractVillager) {
try {
net.minecraft.world.entity.npc.AbstractVillager villager = ((CraftAbstractVillager) livingEntity).getHandle();
// Set the trades to empty if they are null to prevent trades from generating during the saveWithoutId call
boolean bypassTrades = field_AbstractVillager_offers.get(villager) == null;
if (bypassTrades)
field_AbstractVillager_offers.set(villager, new MerchantOffers());
((CraftLivingEntity) livingEntity).getHandle().saveWithoutId(compoundTag);
// Restore the offers back to null and make sure nothing is written to the NBT
if (bypassTrades) {
field_AbstractVillager_offers.set(villager, null);
compoundTag.remove("Offers");
}
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
} else {
((CraftLivingEntity) livingEntity).getHandle().saveWithoutId(compoundTag);
}
}
}
| 412 | 0.889747 | 1 | 0.889747 | game-dev | MEDIA | 0.997616 | game-dev | 0.669255 | 1 | 0.669255 |
Coffee-Client/Coffee | 2,742 | src/main/java/coffee/client/feature/module/impl/world/Annihilator.java | /*
* Copyright (c) 2022 Coffee Client, 0x150 and contributors.
* Some rights reserved, refer to LICENSE file.
*/
package coffee.client.feature.module.impl.world;
import coffee.client.CoffeeMain;
import coffee.client.feature.config.DoubleSetting;
import coffee.client.feature.config.StringSetting;
import coffee.client.feature.module.Module;
import coffee.client.feature.module.ModuleType;
import coffee.client.helper.event.impl.MouseEvent;
import me.x150.jmessenger.MessageSubscription;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import java.util.Objects;
public class Annihilator extends Module {
final DoubleSetting range = this.config.create(new DoubleSetting.Builder(5).name("Range").description("Range of the nuke").min(1).max(14).precision(0).get());
final StringSetting block = this.config.create(new StringSetting.Builder("air").name("Block").description("The block to fill with").get());
public Annihilator() {
super("Annihilator", "Nukes whatever you click at, requires /fill permissions", ModuleType.WORLD);
}
@MessageSubscription
void on(MouseEvent event1) {
if (event1.getButton() == 0 && event1.getType() == MouseEvent.Type.CLICK) {
mousePressed();
}
}
void mousePressed() {
if (client.currentScreen != null) {
return;
}
HitResult hr = Objects.requireNonNull(client.player).raycast(200d, 0f, true);
Vec3d pos1 = hr.getPos();
BlockPos pos = BlockPos.ofFloored(pos1);
int startY = MathHelper.clamp(r(pos.getY() - range.getValue()), Objects.requireNonNull(CoffeeMain.client.world).getBottomY(), CoffeeMain.client.world.getTopY());
int endY = MathHelper.clamp(r(pos.getY() + range.getValue()), CoffeeMain.client.world.getBottomY(), CoffeeMain.client.world.getTopY());
String cmd = "fill " + r(pos.getX() - range.getValue()) + " " + startY + " " + r(pos.getZ() - range.getValue()) + " " + r(pos.getX() + range.getValue()) + " " + endY + " " + r(
pos.getZ() + range.getValue()) + " " + "minecraft:" + block.getValue();
client.getNetworkHandler().sendCommand(cmd);
}
int r(double v) {
return (int) Math.round(v);
}
@Override
public void tick() {
}
@Override
public void enable() {
}
@Override
public void disable() {
}
@Override
public String getContext() {
return null;
}
@Override
public void onWorldRender(MatrixStack matrices) {
}
@Override
public void onHudRender() {
}
}
| 412 | 0.827443 | 1 | 0.827443 | game-dev | MEDIA | 0.45584 | game-dev | 0.856975 | 1 | 0.856975 |
MegaMek/megamek | 21,799 | megamek/src/megamek/common/weapons/handlers/capitalMissile/CapitalMissileHandler.java | /*
* Copyright (c) 2005 - Ben Mazur (bmazur@sev.org)
* Copyright (C) 2008-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common.weapons.handlers.capitalMissile;
import java.io.Serial;
import java.util.Vector;
import megamek.common.RangeType;
import megamek.common.Report;
import megamek.common.ToHitData;
import megamek.common.actions.WeaponAttackAction;
import megamek.common.enums.GamePhase;
import megamek.common.equipment.AmmoType;
import megamek.common.equipment.WeaponMounted;
import megamek.common.equipment.WeaponType;
import megamek.common.game.Game;
import megamek.common.loaders.EntityLoadingException;
import megamek.common.options.OptionsConstants;
import megamek.common.rolls.TargetRoll;
import megamek.common.units.Building;
import megamek.common.units.Entity;
import megamek.common.units.Targetable;
import megamek.common.weapons.handlers.AmmoWeaponHandler;
import megamek.common.weapons.handlers.WeaponHandler;
import megamek.server.totalWarfare.TWGameManager;
/**
* @author Jay Lawson
*/
public class CapitalMissileHandler extends AmmoWeaponHandler {
@Serial
private static final long serialVersionUID = -1618484541772117621L;
boolean advancedPD;
/**
*
*/
public CapitalMissileHandler(ToHitData t, WeaponAttackAction w, Game g, TWGameManager m)
throws EntityLoadingException {
super(t, w, g, m);
advancedPD = g.getOptions().booleanOption(OptionsConstants.ADVANCED_AERO_RULES_STRATOPS_ADV_POINT_DEFENSE);
}
/*
* (non-Javadoc)
*
* @see megamek.common.weapons.handlers.AttackHandler#handle(int, java.util.Vector)
*/
@Override
public boolean handle(GamePhase phase, Vector<Report> vPhaseReport) {
if (!cares(phase)) {
return true;
}
int numAttacks = 1;
Entity entityTarget = (target.getTargetType() == Targetable.TYPE_ENTITY) ? (Entity) target
: null;
if (entityTarget != null) {
attackingEntity.setLastTarget(entityTarget.getId());
attackingEntity.setLastTargetDisplayName(entityTarget.getDisplayName());
}
// Which building takes the damage?
Building bldg = game.getBoard().getBuildingAt(target.getPosition());
String number = numWeapons > 1 ? " (" + numWeapons + ")" : "";
for (int i = numAttacks; i > 0; i--) {
// Report weapon attack and its to-hit value.
Report report = new Report(3115);
report.indent();
report.newlines = 0;
report.subject = subjectId;
report.add(weaponType.getName() + number);
if (entityTarget != null) {
if ((weaponType.getAmmoType() != AmmoType.AmmoTypeEnum.NA)
&& (weapon.getLinked() != null)
&& (weapon.getLinked().getType() instanceof AmmoType ammoType)) {
if (!ammoType.getMunitionType().contains(AmmoType.Munitions.M_STANDARD)) {
report.messageId = 3116;
report.add(ammoType.getSubMunitionName());
}
}
report.addDesc(entityTarget);
} else {
report.messageId = 3120;
report.add(target.getDisplayName(), true);
}
vPhaseReport.addElement(report);
// are we a glancing hit? Check for this here, report it later
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_COMBAT_TAC_OPS_GLANCING_BLOWS)) {
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_AERO_RULES_AERO_SANITY)) {
if (getParentBayHandler() != null) {
//Use the to-hit value for the bay handler, otherwise toHit is set to Automatic Success
WeaponHandler bayHandler = getParentBayHandler();
bGlancing = (roll.getIntValue() == bayHandler.toHit.getValue());
bLowProfileGlancing = isLowProfileGlancingBlow(entityTarget, bayHandler.toHit);
}
} else {
setGlancingBlowFlags(entityTarget);
}
}
// Set Margin of Success/Failure and check for Direct Blows
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_AERO_RULES_AERO_SANITY)
&& getParentBayHandler() != null) {
//Use the to-hit value for the bay handler, otherwise toHit is set to Automatic Success
WeaponHandler bayHandler = getParentBayHandler();
toHit.setMoS(roll.getIntValue() - Math.max(2, bayHandler.toHit.getValue()));
} else {
toHit.setMoS(roll.getIntValue() - Math.max(2, toHit.getValue()));
}
bDirect = game.getOptions().booleanOption(OptionsConstants.ADVANCED_COMBAT_TAC_OPS_DIRECT_BLOW)
&& ((toHit.getMoS() / 3) >= 1) && (entityTarget != null);
// Used when using a grounded DropShip with individual weapons
// or a fighter squadron loaded with ASM or Alamo bombs.
nDamPerHit = calcDamagePerHit();
// Point Defense fire vs Capital Missiles
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_AERO_RULES_AERO_SANITY)
&& getParentBayHandler() != null) {
WeaponHandler bayHandler = getParentBayHandler();
CounterAV = bayHandler.getCounterAV();
} else {
// This gets used if you're shooting at an airborne DropShip. It can defend with PD bays.
attackValue = calcAttackValue();
}
// CalcAttackValue triggers counterfire, so now we can safely get this
CapMissileAMSMod = getCapMissileAMSMod();
// Only do this if the missile wasn't destroyed
if (CapMissileAMSMod > 0 && CapMissileArmor > 0) {
toHit.addModifier(CapMissileAMSMod, "Damage from Point Defenses");
if (roll.getIntValue() < toHit.getValue()) {
CapMissileMissed = true;
}
}
// Report any AMS bay action against Capital missiles that doesn't destroy them all.
if (amsBayEngagedCap && CapMissileArmor > 0) {
report = new Report(3358);
report.add(CapMissileAMSMod);
report.subject = subjectId;
vPhaseReport.addElement(report);
// Report any PD bay action against Capital missiles that doesn't destroy them all.
} else if (pdBayEngagedCap && CapMissileArmor > 0) {
report = new Report(3357);
report.add(CapMissileAMSMod);
report.subject = subjectId;
vPhaseReport.addElement(report);
}
if (toHit.getValue() == TargetRoll.IMPOSSIBLE) {
report = new Report(3135);
report.subject = subjectId;
report.add(" " + target.getPosition(), true);
vPhaseReport.addElement(report);
return false;
} else if (toHit.getValue() == TargetRoll.AUTOMATIC_FAIL) {
report = new Report(3140);
report.newlines = 0;
report.subject = subjectId;
report.add(toHit.getDesc());
vPhaseReport.addElement(report);
} else if (toHit.getValue() == TargetRoll.AUTOMATIC_SUCCESS) {
report = new Report(3145);
report.newlines = 0;
report.subject = subjectId;
report.add(toHit.getDesc());
vPhaseReport.addElement(report);
} else {
// roll to hit
report = new Report(3150);
report.newlines = 0;
report.subject = subjectId;
report.add(toHit);
vPhaseReport.addElement(report);
}
// dice have been rolled, thanks
report = new Report(3155);
report.newlines = 0;
report.subject = subjectId;
report.add(roll);
vPhaseReport.addElement(report);
// do we hit?
bMissed = roll.getIntValue() < toHit.getValue();
//Report Glancing/Direct Blow here because of Capital Missile weirdness
if (!(amsBayEngagedCap || pdBayEngagedCap)) {
addGlancingBlowReports(vPhaseReport);
if (bDirect) {
report = new Report(3189);
report.subject = attackingEntity.getId();
report.newlines = 0;
vPhaseReport.addElement(report);
}
}
CounterAV = getCounterAV();
//use this if AMS counterfire destroys all the Capital missiles
if (amsBayEngagedCap && (CapMissileArmor <= 0)) {
report = new Report(3356);
report.indent();
report.subject = subjectId;
vPhaseReport.addElement(report);
nDamPerHit = 0;
}
//use this if PD counterfire destroys all the Capital missiles
if (pdBayEngagedCap && (CapMissileArmor <= 0)) {
report = new Report(3355);
report.indent();
report.subject = subjectId;
vPhaseReport.addElement(report);
nDamPerHit = 0;
}
// Any necessary PSRs, jam checks, etc.
// If this boolean is true, don't report
// the miss later, as we already reported
// it in doChecks
boolean missReported = doChecks(vPhaseReport);
if (missReported) {
bMissed = true;
}
if (bMissed && !missReported) {
reportMiss(vPhaseReport);
}
// Handle damage.
int nCluster = calculateNumCluster();
int id = vPhaseReport.size();
int hits = calcHits(vPhaseReport);
if (target.isAirborne() || game.getBoard().isSpace() || attackingEntity.usesWeaponBays()) {
// if we added a line to the phase report for calc hits, remove
// it now
while (vPhaseReport.size() > id) {
vPhaseReport.removeElementAt(vPhaseReport.size() - 1);
}
int[] aeroResults = calcAeroDamage(entityTarget, vPhaseReport);
hits = aeroResults[0];
// If our capital missile was destroyed, it shouldn't hit
if ((amsBayEngagedCap || pdBayEngagedCap) && (CapMissileArmor <= 0)) {
hits = 0;
}
nCluster = aeroResults[1];
}
//Capital missiles shouldn't be able to target buildings, being space-only weapons
// but if they aren't defined, handleEntityDamage() doesn't work.
int bldgAbsorbs = 0;
// We have to adjust the reports on a miss, so they line up
if (bMissed && id != vPhaseReport.size()) {
vPhaseReport.get(id - 1).newlines--;
vPhaseReport.get(id).indent(2);
vPhaseReport.get(vPhaseReport.size() - 1).newlines++;
}
// Make sure the player knows when his attack causes no damage.
if (nDamPerHit == 0) {
report = new Report(3365);
report.subject = subjectId;
vPhaseReport.addElement(report);
return false;
}
if (!bMissed) {
// for each cluster of hits, do a chunk of damage
while (hits > 0) {
int nDamage;
// targeting a hex for igniting
if ((target.getTargetType() == Targetable.TYPE_HEX_IGNITE)
|| (target.getTargetType() == Targetable.TYPE_BLDG_IGNITE)) {
handleIgnitionDamage(vPhaseReport, bldg, hits);
return false;
}
// targeting a hex for clearing
if (target.getTargetType() == Targetable.TYPE_HEX_CLEAR) {
nDamage = nDamPerHit * hits;
handleClearDamage(vPhaseReport, bldg, nDamage);
return false;
}
// Targeting a building.
if (target.getTargetType() == Targetable.TYPE_BUILDING) {
// The building takes the full brunt of the attack.
nDamage = nDamPerHit * hits;
handleBuildingDamage(vPhaseReport, bldg, nDamage,
target.getPosition());
// And we're done!
return false;
}
if (entityTarget != null) {
handleEntityDamage(entityTarget, vPhaseReport, bldg, hits,
nCluster, bldgAbsorbs);
gameManager.creditKill(entityTarget, attackingEntity);
hits -= nCluster;
firstHit = false;
}
} // Handle the next cluster.
} else { // Hex is targeted, need to report a hit
report = new Report(3390);
report.subject = subjectId;
vPhaseReport.addElement(report);
}
}
Report.addNewline(vPhaseReport);
return false;
}
/**
* Calculate the attack value based on range
*
* @return an <code>int</code> representing the attack value at that range.
*/
@Override
protected int calcAttackValue() {
AmmoType ammoType = ammo.getType();
int av = 0;
double counterAV = calcCounterAV();
int armor = weaponType.getMissileArmor();
//AR10 munitions
if (ammoType != null) {
if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.AR10) {
if (ammoType.hasFlag(AmmoType.F_AR10_KILLER_WHALE)) {
av = 4;
armor = 40;
} else if (ammoType.hasFlag(AmmoType.F_AR10_WHITE_SHARK)) {
av = 3;
armor = 30;
} else if (ammoType.hasFlag(AmmoType.F_PEACEMAKER)) {
av = 1000;
armor = 40;
} else if (ammoType.hasFlag(AmmoType.F_SANTA_ANNA)) {
av = 100;
armor = 30;
} else {
av = 2;
armor = 20;
}
} else {
int range = RangeType.rangeBracket(nRange, weaponType.getATRanges(),
true, false);
if (range == WeaponType.RANGE_SHORT) {
av = weaponType.getRoundShortAV();
} else if (range == WeaponType.RANGE_MED) {
av = weaponType.getRoundMedAV();
} else if (range == WeaponType.RANGE_LONG) {
av = weaponType.getRoundLongAV();
} else if (range == WeaponType.RANGE_EXT) {
av = weaponType.getRoundExtAV();
}
}
//Nuclear Warheads for non-AR10 missiles
if (ammoType.hasFlag(AmmoType.F_SANTA_ANNA)) {
av = 100;
} else if (ammoType.hasFlag(AmmoType.F_PEACEMAKER)) {
av = 1000;
}
nukeS2S = ammoType.hasFlag(AmmoType.F_NUCLEAR);
}
// For squadrons, total the missile armor for the launched volley
if (attackingEntity.isCapitalFighter()) {
armor = armor * numWeapons;
}
CapMissileArmor = armor - (int) counterAV;
CapMissileAMSMod = calcCapMissileAMSMod();
if (bDirect) {
av = Math.min(av + (toHit.getMoS() / 3), av * 2);
}
av = applyGlancingBlowModifier(av, false);
av = (int) Math.floor(getBracketingMultiplier() * av);
return av;
}
/**
* Calculate the damage per hit.
*
* @return an <code>int</code> representing the damage dealt per hit.
*/
@Override
protected int calcDamagePerHit() {
AmmoType ammoType = ammo.getType();
double toReturn = weaponType.getDamage(nRange);
//AR10 munitions
if (ammoType != null) {
if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.AR10) {
if (ammoType.hasFlag(AmmoType.F_AR10_KILLER_WHALE)) {
toReturn = 4;
} else if (ammoType.hasFlag(AmmoType.F_AR10_WHITE_SHARK)) {
toReturn = 3;
} else if (ammoType.hasFlag(AmmoType.F_PEACEMAKER)) {
toReturn = 1000;
} else if (ammoType.hasFlag(AmmoType.F_SANTA_ANNA)) {
toReturn = 100;
} else {
toReturn = 2;
}
}
//Nuclear Warheads for non-AR10 missiles
if (ammoType.hasFlag(AmmoType.F_SANTA_ANNA)) {
toReturn = 100;
} else if (ammoType.hasFlag(AmmoType.F_PEACEMAKER)) {
toReturn = 1000;
}
nukeS2S = ammoType.hasFlag(AmmoType.F_NUCLEAR);
}
// we default to direct fire weapons for anti-infantry damage
if (bDirect) {
toReturn = Math.min(toReturn + (toHit.getMoS() / 3.0), toReturn * 2);
}
toReturn = applyGlancingBlowModifier(toReturn, false);
return (int) toReturn;
}
@Override
protected int calcCapMissileAMSMod() {
CapMissileAMSMod = (int) Math.ceil(CounterAV / 10.0);
return CapMissileAMSMod;
}
@Override
protected int getCapMisMod() {
AmmoType ammoType = ammo.getType();
return getCritMod(ammoType);
}
/*
* get the cap mis mod given a single ammo type
*/
protected int getCritMod(AmmoType ammoType) {
if (ammoType == null || ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.PIRANHA
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.AAA_MISSILE
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.ASEW_MISSILE
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.LAA_MISSILE) {
return 0;
}
if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.WHITE_SHARK
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.WHITE_SHARK_T
|| ammoType.hasFlag(AmmoType.F_AR10_WHITE_SHARK)
// Santa Anna, per IO rules
|| ammoType.hasFlag(AmmoType.F_SANTA_ANNA)) {
return 9;
} else if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.KRAKEN_T
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.KRAKENM
// Peacemaker, per IO rules
|| ammoType.hasFlag(AmmoType.F_PEACEMAKER)) {
return 8;
} else if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.KILLER_WHALE
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.KILLER_WHALE_T
|| ammoType.hasFlag(AmmoType.F_AR10_KILLER_WHALE)
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.MANTA_RAY
|| ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.ALAMO) {
return 10;
} else if (ammoType.getAmmoType() == AmmoType.AmmoTypeEnum.STINGRAY) {
return 12;
} else {
return 11;
}
}
/**
* Checks to see if this point defense/AMS bay can engage a capital missile This should return true. Only when
* handling capital missile attacks can this be false.
*/
@Override
protected boolean canEngageCapitalMissile(WeaponMounted counter) {
return counter.getBayWeapons().size() >= 2;
}
/**
* Sets the appropriate AMS Bay reporting flag depending on what type of missile this is
*/
@Override
protected void setAMSBayReportingFlag() {
amsBayEngagedCap = true;
}
/**
* Sets the appropriate PD Bay reporting flag depending on what type of missile this is
*/
@Override
protected void setPDBayReportingFlag() {
pdBayEngagedCap = true;
}
}
| 412 | 0.963454 | 1 | 0.963454 | game-dev | MEDIA | 0.967944 | game-dev | 0.989858 | 1 | 0.989858 |
GregTechCEu/GregTech-Modern | 9,984 | src/main/java/com/gregtechceu/gtceu/utils/input/SyncedKeyMapping.java | package com.gregtechceu.gtceu.utils.input;
import com.gregtechceu.gtceu.GTCEu;
import com.gregtechceu.gtceu.common.network.GTNetwork;
import com.gregtechceu.gtceu.common.network.packets.CPacketKeyDown;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
import net.minecraftforge.client.settings.IKeyConflictContext;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import com.mojang.blaze3d.platform.InputConstants;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jetbrains.annotations.ApiStatus;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.Supplier;
public final class SyncedKeyMapping {
private static final Int2ObjectMap<SyncedKeyMapping> KEYMAPPINGS = new Int2ObjectOpenHashMap<>();
private static int syncIndex = 0;
@OnlyIn(Dist.CLIENT)
private KeyMapping keyMapping;
@OnlyIn(Dist.CLIENT)
private Supplier<Supplier<KeyMapping>> keyMappingGetter;
private final boolean needsRegister;
@OnlyIn(Dist.CLIENT)
private int keyCode;
@OnlyIn(Dist.CLIENT)
private boolean isKeyDown;
private static final Int2BooleanMap updatingKeyDown = new Int2BooleanOpenHashMap();
private final WeakHashMap<ServerPlayer, Boolean> serverMapping = new WeakHashMap<>();
private final WeakHashMap<ServerPlayer, Set<IKeyPressedListener>> playerListeners = new WeakHashMap<>();
private final Set<IKeyPressedListener> globalListeners = Collections.newSetFromMap(new WeakHashMap<>());
private SyncedKeyMapping(Supplier<Supplier<KeyMapping>> mcKeyMapping) {
if (GTCEu.isClientSide()) {
this.keyMappingGetter = mcKeyMapping;
}
// Does not need to be registered, will be registered by MC
this.needsRegister = false;
KEYMAPPINGS.put(syncIndex++, this);
}
private SyncedKeyMapping(int keyCode) {
if (GTCEu.isClientSide() && !GTCEu.isDataGen()) {
this.keyCode = keyCode;
}
// Does not need to be registered, is not a configurable key mapping
this.needsRegister = false;
KEYMAPPINGS.put(syncIndex++, this);
}
private SyncedKeyMapping(String nameKey, IKeyConflictContext ctx, int keyCode, String category) {
if (GTCEu.isClientSide() && !GTCEu.isDataGen()) {
this.keyMapping = (KeyMapping) createKeyMapping(nameKey, ctx, keyCode, category);
}
this.needsRegister = true;
KEYMAPPINGS.put(syncIndex++, this);
}
/**
* Create a SyncedKeyMapping wrapper around a Minecraft {@link KeyMapping}.
*
* @param mcKeyMapping Doubly-wrapped supplier around a keymapping from
* {@link net.minecraft.client.Options Minecraft.getInstance().options}.
*/
public static SyncedKeyMapping createFromMC(Supplier<Supplier<KeyMapping>> mcKeyMapping) {
return new SyncedKeyMapping(mcKeyMapping);
}
/**
* Create a new SyncedKeyMapping for a specified key code.
*
* @param keyCode The key code.
*/
public static SyncedKeyMapping create(int keyCode) {
return new SyncedKeyMapping(keyCode);
}
/**
* Create a new SyncedKeyMapping with server held and pressed syncing to server.<br>
* Will automatically create a keymapping entry in the MC options page under the GregTechCEu category.
*
* @param nameKey Translation key for the keymapping name.
* @param ctx Conflict context for the keymapping options category.
* @param keyCode The key code, from {@link InputConstants}.
*/
public static SyncedKeyMapping createConfigurable(String nameKey, IKeyConflictContext ctx, int keyCode) {
return createConfigurable(nameKey, ctx, keyCode, GTCEu.NAME);
}
/**
* Create a new SyncedKeyMapping with server held and pressed syncing to server.<br>
* Will automatically create a keymapping entry in the MC options page under the specified category.
*
* @param nameKey Translation key for the keymapping name.
* @param ctx Conflict context for the keymapping options category.
* @param keyCode The key code, from {@link InputConstants}.
* @param category The category in the MC options page.
*/
public static SyncedKeyMapping createConfigurable(String nameKey, IKeyConflictContext ctx, int keyCode,
String category) {
return new SyncedKeyMapping(nameKey, ctx, keyCode, category);
}
@OnlyIn(Dist.CLIENT)
private Object createKeyMapping(String nameKey, IKeyConflictContext ctx, int keyCode, String category) {
return new KeyMapping(nameKey, ctx, InputConstants.Type.KEYSYM, keyCode, category);
}
/**
* Check if a player is currently holding down this key.
*
* @param player The player to check.
*
* @return If the key is held.
*/
public boolean isKeyDown(Player player) {
if (player.level().isClientSide) {
if (keyMapping != null) {
return keyMapping.isDown();
}
long id = Minecraft.getInstance().getWindow().getWindow();
return InputConstants.isKeyDown(id, keyCode);
}
Boolean isKeyDown = serverMapping.get((ServerPlayer) player);
return isKeyDown != null ? isKeyDown : false;
}
/**
* Registers an {@link IKeyPressedListener} to this key, which will have its {@link IKeyPressedListener#onKeyPressed
* onKeyPressed} method called when the provided player presses this key.
*
* @param player The player who owns this listener.
* @param listener The handler for the key clicked event.
*/
public SyncedKeyMapping registerPlayerListener(ServerPlayer player, IKeyPressedListener listener) {
Set<IKeyPressedListener> listenerSet = playerListeners
.computeIfAbsent(player, $ -> Collections.newSetFromMap(new WeakHashMap<>()));
listenerSet.add(listener);
return this;
}
public static void onRegisterKeyBinds(RegisterKeyMappingsEvent event) {
for (SyncedKeyMapping value : KEYMAPPINGS.values()) {
if (value.keyMappingGetter != null) {
value.keyMapping = value.keyMappingGetter.get().get();
value.keyMappingGetter = null;
}
if (value.keyMapping != null && value.needsRegister) {
event.register(value.keyMapping);
}
}
}
/**
* Remove a player's listener on this keymapping for a provided player.
*
* @param player The player who owns this listener.
* @param listener The handler for the key clicked event.
*/
public void removePlayerListener(ServerPlayer player, IKeyPressedListener listener) {
Set<IKeyPressedListener> listenerSet = playerListeners.get(player);
if (listenerSet != null) {
listenerSet.remove(listener);
}
}
/**
* Registers an {@link IKeyPressedListener} to this key, which will have its {@link IKeyPressedListener#onKeyPressed
* onKeyPressed} method called when any player presses this key.
*
* @param listener The handler for the key clicked event.
*/
public SyncedKeyMapping registerGlobalListener(IKeyPressedListener listener) {
globalListeners.add(listener);
return this;
}
/**
* Remove a global listener on this keybinding.
*
* @param listener The handler for the key clicked event.
*/
public void removeGlobalListener(IKeyPressedListener listener) {
globalListeners.remove(listener);
}
@SubscribeEvent
@OnlyIn(Dist.CLIENT)
public static void onClientTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) {
updatingKeyDown.clear();
for (var entry : KEYMAPPINGS.int2ObjectEntrySet()) {
SyncedKeyMapping keyMapping = entry.getValue();
boolean previousKeyDown = keyMapping.isKeyDown;
if (keyMapping.keyMapping != null) {
keyMapping.isKeyDown = keyMapping.keyMapping.isDown();
} else {
long id = Minecraft.getInstance().getWindow().getWindow();
keyMapping.isKeyDown = InputConstants.isKeyDown(id, keyMapping.keyCode);
}
if (previousKeyDown != keyMapping.isKeyDown) {
updatingKeyDown.put(entry.getIntKey(), keyMapping.isKeyDown);
}
}
if (!updatingKeyDown.isEmpty()) {
GTNetwork.sendToServer(new CPacketKeyDown(updatingKeyDown));
}
}
}
@ApiStatus.Internal
public void serverActivate(boolean keyDown, ServerPlayer player) {
this.serverMapping.put(player, keyDown);
// Player listeners
Set<IKeyPressedListener> listenerSet = playerListeners.get(player);
if (listenerSet != null && !listenerSet.isEmpty()) {
for (IKeyPressedListener listener : listenerSet) {
listener.onKeyPressed(player, this, keyDown);
}
}
// Global listeners
for (IKeyPressedListener listener : globalListeners) {
listener.onKeyPressed(player, this, keyDown);
}
}
@ApiStatus.Internal
public static SyncedKeyMapping getFromSyncId(int id) {
return KEYMAPPINGS.get(id);
}
}
| 412 | 0.914906 | 1 | 0.914906 | game-dev | MEDIA | 0.511551 | game-dev | 0.878714 | 1 | 0.878714 |
Ezzz-dev/Nostalrius | 3,126 | data/chatchannels/scripts/help.lua | local CHANNEL_HELP = 7
local muted = Condition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT)
muted:setParameter(CONDITION_PARAM_SUBID, CHANNEL_HELP)
muted:setParameter(CONDITION_PARAM_TICKS, 3600000)
function onSpeak(player, type, message)
local playerAccountType = player:getAccountType()
if player:getLevel() == 1 and playerAccountType == ACCOUNT_TYPE_NORMAL then
player:sendCancelMessage("You may not speak into channels as long as you are on level 1.")
return false
end
if player:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
player:sendCancelMessage("You are muted from the Help channel for using it inappropriately.")
return false
end
if playerAccountType >= ACCOUNT_TYPE_TUTOR then
if string.sub(message, 1, 6) == "!mute " then
local targetName = string.sub(message, 7)
local target = Player(targetName)
if target ~= nil then
if playerAccountType > target:getAccountType() then
if not target:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
target:addCondition(muted)
sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been muted by " .. player:getName() .. " for using Help Channel inappropriately.")
else
player:sendCancelMessage("That player is already muted.")
end
else
player:sendCancelMessage("You are not authorized to mute that player.")
end
else
player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
end
return false
elseif string.sub(message, 1, 8) == "!unmute " then
local targetName = string.sub(message, 9)
local target = Player(targetName)
if target ~= nil then
if playerAccountType > target:getAccountType() then
if target:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then
target:removeCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP)
sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been unmuted by " .. player:getName() .. ".")
else
player:sendCancelMessage("That player is not muted.")
end
else
player:sendCancelMessage("You are not authorized to unmute that player.")
end
else
player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
end
return false
end
end
if type == TALKTYPE_CHANNEL_Y then
if playerAccountType >= ACCOUNT_TYPE_TUTOR or getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_O
end
elseif type == TALKTYPE_CHANNEL_O then
if playerAccountType < ACCOUNT_TYPE_TUTOR and not getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_Y
end
elseif type == TALKTYPE_CHANNEL_R1 then
if playerAccountType < ACCOUNT_TYPE_GAMEMASTER and not getPlayerFlagValue(player, PlayerFlag_CanTalkRedChannel) then
if playerAccountType >= ACCOUNT_TYPE_TUTOR or getPlayerFlagValue(player, PlayerFlag_TalkOrangeHelpChannel) then
type = TALKTYPE_CHANNEL_O
else
type = TALKTYPE_CHANNEL_Y
end
end
end
return type
end
| 412 | 0.789158 | 1 | 0.789158 | game-dev | MEDIA | 0.599155 | game-dev | 0.789446 | 1 | 0.789446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.