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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NebulaSS13/Nebula | 3,698 | code/game/objects/structures/_structure_materials.dm | /obj/structure
var/decl/material/material
var/decl/material/reinf_material
var/material_alteration
var/dismantled
var/name_prefix
/// The base alpha used to calculate material-based alpha in update_material_color().
var/base_alpha = 50
/obj/structure/get_material()
RETURN_TYPE(/decl/material)
return material
/obj/structure/proc/get_material_health_modifier()
. = 1
/obj/structure/proc/update_materials(var/keep_health)
if(material_alteration & MAT_FLAG_ALTERATION_NAME)
update_material_name()
if(material_alteration & MAT_FLAG_ALTERATION_DESC)
update_material_desc()
if(material_alteration & MAT_FLAG_ALTERATION_COLOR)
update_material_color()
if((alpha / 255) < 0.5)
set_opacity(FALSE)
else
set_opacity(initial(opacity))
if(isnull(initial(paint_verb)) && !isnull(material))
paint_verb = material.paint_verb
hitsound = material?.hitsound || initial(hitsound)
if(max_health != -1)
max_health = initial(max_health) + material?.integrity * get_material_health_modifier()
if(reinf_material)
var/bonus_health = reinf_material.integrity * get_material_health_modifier()
max_health += bonus_health
if(!keep_health)
current_health += bonus_health
current_health = keep_health ? min(current_health, max_health) : max_health
update_icon()
/obj/structure/proc/update_material_name(var/override_name)
var/base_name = override_name || initial(name)
var/new_name
if(istype(material) && (material_alteration & MAT_FLAG_ALTERATION_NAME))
new_name = "[material.adjective_name] [base_name]"
else
new_name = base_name
if(name_prefix)
new_name = "[name_prefix] [new_name]"
SetName(new_name)
/obj/structure/proc/update_material_desc(var/override_desc)
var/base_desc = override_desc || initial(desc)
if(istype(material) && (material_alteration & MAT_FLAG_ALTERATION_DESC))
desc = "[base_desc] This one is made of [material.solid_name]."
else
desc = base_desc
/obj/structure/proc/update_material_color()
color = get_color()
if(istype(material))
alpha = clamp((base_alpha + material.opacity * 255), 0, 255)
else
alpha = initial(alpha)
///Spawns a single part_type part, returns the result. Allows overriding spawning the actual part and it's constructor args.
/obj/structure/proc/create_dismantled_part(var/turf/T)
return new parts_type(T, (material && material.type), (reinf_material && reinf_material.type))
/obj/structure/proc/create_dismantled_products(var/turf/T)
SHOULD_CALL_PARENT(TRUE)
if(parts_type && !ispath(parts_type, /obj/item/stack))
for(var/i = 1 to max(parts_amount, 1))
LAZYADD(., create_dismantled_part(T))
return
for(var/mat in matter)
var/decl/material/M = GET_DECL(mat)
var/placing
if(isnull(parts_amount))
placing = (matter[mat] / SHEET_MATERIAL_AMOUNT) * 0.75
if(material == M && parts_type)
placing *= atom_info_repository.get_matter_multiplier_for(parts_type, mat, placing)
placing = floor(placing)
else
placing = parts_amount
if(placing > 0)
if(material == M)
LAZYADD(., M.place_dismantled_product(T, FALSE, placing, parts_type))
else
LAZYADD(., M.place_dismantled_product(T, FALSE, placing))
/obj/structure/proc/clear_materials()
matter = null
material = null
reinf_material = null
/obj/structure/proc/dismantle_structure(mob/user)
SHOULD_CALL_PARENT(TRUE)
if(!dismantled)
dismantled = TRUE
var/list/products = create_dismantled_products(get_turf(src))
if(paint_color && length(products))
for(var/obj/product in products)
if((isitem(product) || istype(product, /obj/structure)) && product.get_material() == material)
product.set_color(paint_color)
clear_materials()
dump_contents()
if(!QDELETED(src))
qdel(src)
. = TRUE
| 0 | 0.867131 | 1 | 0.867131 | game-dev | MEDIA | 0.598737 | game-dev | 0.912889 | 1 | 0.912889 |
TeamChocoQuest/ChocolateQuestRepoured | 1,322 | src/main/java/team/cqr/cqrepoured/network/server/handler/SPacketHandlerOpenMerchantGui.java | package team.cqr.cqrepoured.network.server.handler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import team.cqr.cqrepoured.CQRMain;
import team.cqr.cqrepoured.entity.bases.AbstractEntityCQR;
import team.cqr.cqrepoured.network.client.packet.CPacketOpenMerchantGui;
import team.cqr.cqrepoured.util.GuiHandler;
public class SPacketHandlerOpenMerchantGui implements IMessageHandler<CPacketOpenMerchantGui, IMessage> {
@Override
public IMessage onMessage(CPacketOpenMerchantGui message, MessageContext ctx) {
if (ctx.side.isServer()) {
FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(() -> {
EntityPlayer player = CQRMain.proxy.getPlayer(ctx);
World world = CQRMain.proxy.getWorld(ctx);
Entity entity = world.getEntityByID(message.getEntityId());
if (entity instanceof AbstractEntityCQR) {
player.openGui(CQRMain.INSTANCE, GuiHandler.MERCHANT_GUI_ID, world, message.getEntityId(), 0, 0);
}
});
}
return null;
}
}
| 0 | 0.847534 | 1 | 0.847534 | game-dev | MEDIA | 0.926866 | game-dev | 0.7739 | 1 | 0.7739 |
ishwi/Chuu | 4,079 | src/main/java/core/commands/config/NPModeSetterCommand.java | package core.commands.config;
import core.apis.lyrics.TextSplitter;
import core.commands.Context;
import core.commands.abstracts.ConcurrentCommand;
import core.commands.utils.ChuuEmbedBuilder;
import core.commands.utils.CommandCategory;
import core.commands.utils.CommandUtil;
import core.otherlisteners.util.PaginatorBuilder;
import core.parsers.EnumListParser;
import core.parsers.Parser;
import core.parsers.params.EnumListParameters;
import core.util.ServiceView;
import dao.entities.NPMode;
import net.dv8tion.jda.api.EmbedBuilder;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class NPModeSetterCommand extends ConcurrentCommand<EnumListParameters<NPMode>> {
public static final Function<String, EnumSet<NPMode>> mapper = (String value) -> {
String[] split = value.trim().replaceAll(" +", " ").split("[|,& ]+");
EnumSet<NPMode> modes = EnumSet.noneOf(NPMode.class);
for (String mode : split) {
try {
NPMode npMode = NPMode.valueOf(mode.replace("-", "_").toUpperCase());
modes.add(npMode);
} catch (IllegalArgumentException ignored) {
//Ignore
}
}
return modes;
};
public NPModeSetterCommand(ServiceView dao) {
super(dao);
}
@Override
protected CommandCategory initCategory() {
return CommandCategory.CONFIGURATION;
}
@Override
public Parser<EnumListParameters<NPMode>> initParser() {
return new EnumListParser<>(db, "np-modes", NPMode.class, EnumSet.of(NPMode.UNKNOWN), mapper);
}
@Override
public String getDescription() {
return "Customize your np/fm commands with several extra fields";
}
@Override
public List<String> getAliases() {
return List.of("npmode", "npconfig", "npc", "fmmode", "fmconfig", "fmc");
}
@Override
public String getName() {
return "NP command configuration";
}
@Override
public void onCommand(Context e, @NotNull EnumListParameters<NPMode> params) {
EnumSet<NPMode> modes = params.getEnums();
if (params.isHelp()) {
if (modes.isEmpty()) {
sendMessageQueue(e, getUsageInstructions());
return;
}
String lines = modes.stream().map(x -> "**%s** ➜ %s".formatted(NPMode.getListedName(List.of(x)), x.getHelpMessage())).collect(Collectors.joining("\n"));
List<String> split = TextSplitter.split(lines, 2000);
EmbedBuilder eb = new ChuuEmbedBuilder(e).setTitle("NP Configuration help")
.setDescription(split.get(0));
new PaginatorBuilder<>(e, eb, split).pageSize(1).unnumered().build().queue();
return;
}
if (params.isListing()) {
modes = db.getNPModes(params.getUser().getIdLong());
String strMode = NPMode.getListedName(modes);
sendMessageQueue(e,
"Do `" + CommandUtil.getMessagePrefix(e) + "npc help` for a list of all options.\n" +
"%surrent modes: ".formatted(params.getUser().getIdLong() != e.getAuthor().getIdLong() ? getUserString(e, params.getUser().getIdLong()) + "'s c" : "C") +
strMode);
} else {
if (params.isAdding() || params.isRemoving()) {
EnumSet<NPMode> npModes = db.getNPModes(e.getAuthor().getIdLong());
if (params.isAdding()) {
npModes.addAll(modes);
} else {
npModes.removeAll(modes);
}
modes = npModes;
}
String strMode = NPMode.getListedName(modes);
db.changeNpMode(e.getAuthor().getIdLong(), modes);
sendMessageQueue(e, String.format("Successfully changed to the following %s: %s", CommandUtil.singlePlural(modes.size(), "mode", "modes"), strMode));
}
}
}
| 0 | 0.886028 | 1 | 0.886028 | game-dev | MEDIA | 0.522424 | game-dev | 0.949459 | 1 | 0.949459 |
R2Northstar/NorthstarMods | 10,444 | Northstar.CustomServers/mod/scripts/vscripts/sh_powerup.gnut | global function SH_PowerUp_Init
global function GetPowerUpFromIndex
global function GetPowerUpFromItemRef
//Proto Use Functions
global function PowerUp_Func_GiveEPG
global function PowerUp_Func_GiveHELL
global function PowerUp_Func_GiveLSTAR
global function PowerUp_Func_GiveSHOTGUN
global function PowerUp_Func_GiveArmorSmall
global function PowerUp_Func_GiveArmorMedium
global function PowerUp_Func_GiveArmorLarge
global function PowerUp_Func_TitanBuildTime
global function PowerUp_Func_PilotUpgrade
global function PowerUp_Func_GiveTicks
global struct PowerUp
{
int index
string name
asset icon
asset model
asset baseModel
string itemRef
vector modelOffset
vector modelAngles
float respawnDelay
vector glowColor
bool titanPickup
int maxInWorld
void functionref( entity ) destroyFunc
bool functionref() spawnFunc
}
const bool TITAN_PICKUP = true
const bool PILOT_PICKUP = false
struct
{
array<PowerUp> powerUps
}file
const TEST_MODEL = $"models/communication/terminal_com_station.mdl"
const TEST_ICON = $"vgui/HUD/coop/minimap_coop_nuke_titan"
void function SH_PowerUp_Init()
{
#if SERVER || CLIENT
PrecacheWeapon( "mp_weapon_epg" )
PrecacheWeapon( "mp_weapon_arena1" )
PrecacheWeapon( "mp_weapon_arena2" )
PrecacheWeapon( "mp_weapon_arena3" )
PrecacheWeapon( "mp_weapon_lstar" )
PrecacheWeapon( "mp_weapon_shotgun_doublebarrel" )
PrecacheWeapon( "mp_weapon_frag_drone" )
#endif
file.powerUps.resize( ePowerUps.count )
CreatePowerUp( ePowerUps.weaponEPG, "mp_weapon_epg", "EPG", 60.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveEPG, <255,0,0>, PILOT_PICKUP, $"vgui/HUD/op_ammo_mini", $"models/weapons/auto_rocket_launcher_ARL/w_ARL.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.weaponHELL, "mp_weapon_arena3", "HELL", 90.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveHELL, <255,0,0>, PILOT_PICKUP, $"vgui/HUD/op_ammo_mini", $"models/weapons/defender/w_defender.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.weaponLSTAR, "mp_weapon_lstar", "LSTAR", 45.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveLSTAR, <255,0,0>, PILOT_PICKUP, $"vgui/HUD/op_ammo_mini", $"models/weapons/lstar/w_lstar.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.weaponSHOTGUN, "mp_weapon_shotgun_doublebarrel", "Shrapnel Shotgun", 30.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveSHOTGUN, <255,0,0>, PILOT_PICKUP, $"vgui/HUD/op_ammo_mini", $"models/weapons/mastiff_stgn/w_mastiff.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.armorSmall, "mp_loot_armor_small", "Armor +5", 30.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveArmorSmall, <0,0,255>, PILOT_PICKUP, $"vgui/HUD/op_health_mini", $"models/gameplay/health_pickup_small.mdl", $"models/containers/plastic_pallet_01.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.armorMedium, "mp_loot_armor_medium", "Armor +25", 60.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveArmorMedium, <0,0,255>, PILOT_PICKUP, $"vgui/HUD/op_health_mini", $"models/gameplay/health_pickup_small.mdl", $"models/containers/plastic_pallet_01.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.armorLarge, "mp_loot_armor_large", "Armor +50", 120.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveArmorLarge, <0,0,255>, PILOT_PICKUP, $"vgui/HUD/op_health_mini", $"models/gameplay/health_pickup_large.mdl", $"models/containers/plastic_pallet_01.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.titanTimeReduction, "mp_loot_titan_build_credit", "Titan Build Time", 20.0, 2, FRAShouldSpawnPowerUp, PowerUp_Func_TitanBuildTime, <0,255,0>, PILOT_PICKUP, $"vgui/HUD/op_drone_mini", $"models/titans/medium/titan_medium_battery_static.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.LTS_TitanTimeReduction, "mp_loot_titan_build_credit_lts", "Titan Build Time", 60.0, 0, LTSShouldSpawnPowerUp, PowerUp_Func_TitanBuildTime, <0,255,0>, PILOT_PICKUP, $"vgui/HUD/op_drone_mini", $"models/titans/medium/titan_medium_battery_static.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.pilotUpgrade, "mp_loot_pilot_upgrade", "Can of Spinach", 120.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_PilotUpgrade, <0,255,0>, PILOT_PICKUP, $"vgui/HUD/op_drone_mini", $"models/humans/pilots/pilot_light_ged_m.mdl", $"models/communication/flag_base.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
CreatePowerUp( ePowerUps.ticks, "mp_weapon_frag_drone", "Ticks", 60.0, 0, DefaultShouldSpawnPowerUp, PowerUp_Func_GiveTicks, <255,0,0>, PILOT_PICKUP, $"vgui/HUD/op_ammo_mini", $"models/robots/drone_frag/frag_drone_proj.mdl", $"models/robots/drone_frag/frag_drone_proj.mdl", < 0, 0, 32 >, < 0, 0, 0 > )
}
bool function FRAShouldSpawnPowerUp()
{
return GAMETYPE == FREE_AGENCY
}
bool function LTSShouldSpawnPowerUp()
{
if ( HasIronRules() )
return false
// modified for fw
//return ( GAMETYPE == LAST_TITAN_STANDING || GAMETYPE == LTS_BOMB )
return ( GAMETYPE == LAST_TITAN_STANDING || GAMETYPE == LTS_BOMB || GAMETYPE == FORT_WAR )
}
bool function DefaultShouldSpawnPowerUp()
{
return GetCurrentPlaylistVarInt( "power_ups_enabled", 0 ) == 1
}
void function CreatePowerUp( int enumIndex, string item, string displayName, float respawnTime, int worldLimit, bool functionref() shouldSpawnFunction, void functionref( entity ) destroyFunction, vector color, bool canTitanPickup, asset worldIcon, asset worldModel, asset worldBase, vector worldModelOffset, vector worldModelAngle )
{
PowerUp power
power.index = enumIndex
power.name = displayName
power.icon = worldIcon
power.model = worldModel
power.baseModel = worldBase
power.itemRef = item
power.modelOffset = worldModelOffset
power.modelAngles = worldModelAngle
power.respawnDelay = respawnTime
power.destroyFunc = destroyFunction
power.spawnFunc = shouldSpawnFunction
power.glowColor = color
power.titanPickup = canTitanPickup
power.maxInWorld = worldLimit
file.powerUps[enumIndex] = power
#if CLIENT
PrecacheHUDMaterial( worldIcon )
#else
PrecacheModel( worldModel )
PrecacheModel( worldBase )
#if R1_VGUI_MINIMAP
Minimap_PrecacheMaterial( worldIcon )
#endif
#endif
}
PowerUp function GetPowerUpFromIndex( int index )
{
return file.powerUps[index]
}
PowerUp function GetPowerUpFromItemRef( string ref )
{
foreach( power in file.powerUps )
{
if ( power.itemRef == ref )
return power
}
Assert( false, "Power Up not found")
unreachable
}
//////////////////////////////////////////////
// PROTO USE FUNCTIONS - Maybe should be a bunch of new item_ classes with their own healthkit callbacks?
//////////////////////////////////////////////
void function PowerUp_Func_GiveEPG( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
GiveWeaponPowerUp( player, "mp_weapon_arena2" )
#endif
}
void function PowerUp_Func_GiveHELL( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
GiveWeaponPowerUp( player, "mp_weapon_arena3" )
#endif
}
void function PowerUp_Func_GiveLSTAR( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
GiveWeaponPowerUp( player, "mp_weapon_arena1" )
#endif
}
void function PowerUp_Func_GiveSHOTGUN( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
GiveWeaponPowerUp( player, "mp_weapon_shotgun_doublebarrel" )
#endif
}
void function PowerUp_Func_GiveTicks( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
player.TakeOffhandWeapon( OFFHAND_ORDNANCE )
player.GiveOffhandWeapon( "mp_weapon_frag_drone", OFFHAND_ORDNANCE )
thread RestoreDefaultOffhandWeapon( player )
#endif
}
#if SERVER
void function RestoreDefaultOffhandWeapon( entity player )
{
player.EndSignal( "OnDeath" )
player.EndSignal( "OnDestroy" )
while( true )
{
player.WaitSignal( "ThrowGrenade" )
if ( player.IsTitan() )
continue
entity weapon = player.GetOffhandWeapon( OFFHAND_ORDNANCE )
if ( weapon.GetWeaponPrimaryClipCount() == 0 )
{
player.TakeOffhandWeapon( OFFHAND_ORDNANCE )
int loadoutIndex = GetActivePilotLoadoutIndex( player )
PilotLoadoutDef loadout = GetPilotLoadoutFromPersistentData( player, loadoutIndex )
player.GiveOffhandWeapon( loadout.ordnance, OFFHAND_ORDNANCE )
return
}
}
}
void function GiveWeaponPowerUp( entity player, string newWeapon )
{
array<entity> weapons = player.GetMainWeapons()
string weaponToSwitch = player.GetLatestPrimaryWeapon().GetWeaponClassName()
if ( player.GetActiveWeapon() != player.GetAntiTitanWeapon() )
{
foreach ( weapon in weapons )
{
string weaponClassName = weapon.GetWeaponClassName()
if ( weaponClassName == newWeapon )
{
weaponToSwitch = weaponClassName
break
}
}
}
player.TakeWeaponNow( weaponToSwitch )
player.GiveWeapon( newWeapon )
player.SetActiveWeaponByName( newWeapon )
}
#endif
void function PowerUp_Func_GiveArmorSmall( entity player )
{
GiveArmor( player, 5 )
}
void function PowerUp_Func_GiveArmorMedium( entity player )
{
GiveArmor( player, 25 )
}
void function PowerUp_Func_GiveArmorLarge( entity player )
{
GiveArmor( player, 50 )
}
void function GiveArmor( entity player, int amount )
{
#if SERVER
if ( player.IsTitan() )
return
int currentShieldHealth = player.GetShieldHealth()
int currentMaxShieldHealth = player.GetShieldHealthMax()
player.SetShieldHealth( min( 200, amount + currentShieldHealth ) )
player.SetShieldHealthMax( min( 200, amount + currentMaxShieldHealth ) )
#endif
}
void function PowerUp_Func_TitanBuildTime( entity player )
{
#if SERVER
entity battery = Rodeo_CreateBatteryPack()
battery.SetOrigin( player.GetOrigin() )
#endif
}
void function PowerUp_Func_PilotUpgrade( entity player )
{
#if SERVER
if ( player.IsTitan() )
return
int loadoutIndex = GetPersistentSpawnLoadoutIndex( player, "pilot" )
PilotLoadoutDef loadout = GetPilotLoadoutFromPersistentData( player, loadoutIndex )
loadout.primary = "mp_weapon_arena2"
loadout.secondary = "mp_weapon_mgl"
loadout.ordnance = "mp_weapon_grenade_emp"
UpdateDerivedPilotLoadoutData( loadout )
GivePilotLoadout( player, loadout )
SetActivePilotLoadoutIndex( player, loadoutIndex )
#endif
} | 0 | 0.922907 | 1 | 0.922907 | game-dev | MEDIA | 0.99894 | game-dev | 0.842212 | 1 | 0.842212 |
Virtuoel/Pehkui | 1,579 | src/main/java/virtuoel/pehkui/mixin/compat1204minus/compat119plus/ServerPlayNetworkHandlerMixin.java | package virtuoel.pehkui.mixin.compat1204minus.compat119plus;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@Mixin(ServerPlayNetworkHandler.class)
public class ServerPlayNetworkHandlerMixin
{
@Shadow ServerPlayerEntity player;
@ModifyArg(method = "onPlayerInteractBlock", index = 0, at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/Vec3d;squaredDistanceTo(Lnet/minecraft/util/math/Vec3d;)D"))
private Vec3d pehkui$onPlayerInteractBlock$center(Vec3d center)
{
final BlockPos pos = new BlockPos(MathHelper.floor(center.x), MathHelper.floor(center.y), MathHelper.floor(center.z));
final Vec3d eye = player.getEyePos();
final BlockPos eyePos = new BlockPos(MathHelper.floor(eye.x), MathHelper.floor(eye.y), MathHelper.floor(eye.z));
final double xOffset = eye.getX() - center.getX();
final double yOffset = eye.getY() - center.getY();
final double zOffset = eye.getZ() - center.getZ();
center = center.add(
eyePos.getX() == pos.getX() ? xOffset : xOffset < 0.0D ? -0.5D : 0.5D,
eyePos.getY() == pos.getY() ? yOffset : yOffset < 0.0D ? -0.5D : 0.5D,
eyePos.getZ() == pos.getZ() ? zOffset : zOffset < 0.0D ? -0.5D : 0.5D
);
return center;
}
}
| 0 | 0.741264 | 1 | 0.741264 | game-dev | MEDIA | 0.923588 | game-dev | 0.802937 | 1 | 0.802937 |
jsdf/goose64 | 3,022 | src/modeltype.c |
#include "modeltype.h"
char* ModelTypeStrings[] = {
"NoneModel", //
"GooseModel", //
"BookItemModel", //
"HomeworkItemModel", //
"CakeItemModel", //
"UniBldgModel", //
"UniFloorModel", //
"BushModel", //
"FlagpoleModel", //
"GardenerCharacterModel", //
"WallModel", //
"PlanterModel", //
"GroundModel", //
"WaterModel", //
"RockModel", //
"WatergrassModel", //
"ReedModel", //
"LilypadModel", //
"BenchModel", //
"PathModel", //
"PaverModel", //
"WallTallModel", //
"HedgeModel", //
"CollisionGroundModel", //
"MAX_MODEL_TYPE", //
};
#define DEFAULT_MODEL_PROPERTIES \
{ /* mass */ \
100, /* radius */ 10.0, /* centroidOffset */ {0.0, 0.0, 0.0}, \
/*scale*/ 1.0, GenericModelType \
}
ModelProperties modelTypesProperties[] = {
/* NoneModel */
DEFAULT_MODEL_PROPERTIES,
/* GooseModel */
{/* mass */ 200, /* radius */ 25.0,
/* centroidOffset */ {0.0, 15.0, 0.0}, /*scale*/ 0.7, PlayerModelType},
/* BookItemModel */
{/* mass */ 10, /* radius */ 9.0,
/* centroidOffset */ {0.0, 0.0, 0.0}, /*scale*/ 1.0, ItemModelType},
/* HomeworkItemModel */
{/* mass */ 100, /* radius */ 50.0,
/* centroidOffset */ {0.0, 0.0, 0.0}, /*scale*/ 1.0, ItemModelType},
/* CakeItemModel */
{/* mass */ 100, /* radius */ 50.0,
/* centroidOffset */ {0.0, 0.0, 0.0}, /*scale*/ 1.0, ItemModelType},
/* UniBldgModel */
DEFAULT_MODEL_PROPERTIES,
/* UniFloorModel */
DEFAULT_MODEL_PROPERTIES,
/* BushModel */
{/* mass */ 100, /* radius */ 55.0,
/* centroidOffset */ {0.0, 15.0, 0.0}, /*scale*/ 1.0, GenericModelType},
/* FlagpoleModel */
DEFAULT_MODEL_PROPERTIES,
/* GardenerCharacterModel */
{/* mass */ 2000, /* radius */ 25.0,
/* centroidOffset */ {0.0, 22.0, 0.0}, /*scale*/ 1.0, CharacterModelType},
/* WallModel */
DEFAULT_MODEL_PROPERTIES,
/* PlanterModel */
DEFAULT_MODEL_PROPERTIES,
/* GroundModel */
DEFAULT_MODEL_PROPERTIES,
/* WaterModel */
DEFAULT_MODEL_PROPERTIES,
/* RockModel */
DEFAULT_MODEL_PROPERTIES,
/* WatergrassModel */
DEFAULT_MODEL_PROPERTIES,
/* ReedModel */
DEFAULT_MODEL_PROPERTIES,
/* LilypadModel */
DEFAULT_MODEL_PROPERTIES,
/* BenchModel */
DEFAULT_MODEL_PROPERTIES,
/* PathModel */
DEFAULT_MODEL_PROPERTIES,
/* PaverModel */
DEFAULT_MODEL_PROPERTIES,
/* WallTallModel */
DEFAULT_MODEL_PROPERTIES,
/* HedgeModel */
DEFAULT_MODEL_PROPERTIES,
/* CollisionGroundModel */
DEFAULT_MODEL_PROPERTIES,
};
| 0 | 0.747134 | 1 | 0.747134 | game-dev | MEDIA | 0.239767 | game-dev | 0.677194 | 1 | 0.677194 |
Monkestation/Monkestation2.0 | 5,658 | monkestation/code/modules/bunny_wizard/outfits.dm | /datum/outfit/cursed_bunny //for bunny wizards, don't use these for normal outfits
name = "Cursed Bunny"
uniform = /obj/item/clothing/under/costume/playbunny
suit = /obj/item/clothing/suit/jacket/tailcoat
shoes = /obj/item/clothing/shoes/heels
head = /obj/item/clothing/head/playbunnyears
gloves = /obj/item/clothing/gloves/color/white
neck = /obj/item/clothing/neck/tie/bunnytie/tied
r_pocket = /obj/item/toy/cards/deck
l_pocket = /obj/item/reagent_containers/cup/rag
r_hand = /obj/item/storage/bag/tray
l_hand = /obj/item/reagent_containers/cup/glass/drinkingglass/filled/champagne
/datum/outfit/cursed_bunny/post_equip(mob/living/carbon/human/equipped_on, visualsOnly=FALSE)
if(visualsOnly)
return
var/list/no_drops = list()
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_FEET)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_ICLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_OCLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_HEAD)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_NECK)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_GLOVES)
for(var/obj/item/trait_needed as anything in no_drops)
ADD_TRAIT(trait_needed, TRAIT_NODROP, CURSED_ITEM_TRAIT(trait_needed.type))
trait_needed.name = "cursed " + trait_needed.name
/datum/outfit/cursed_bunny/costume
name = "Cursed Bunny Costume"
uniform = null
suit = /obj/item/clothing/suit/costume/bunnysuit/regular
head = /obj/item/clothing/head/costume/bunnyhead/regular
shoes = /obj/item/clothing/shoes/clown_shoes/clown_jester_shoes
neck = null
r_hand = /obj/item/food/hotcrossbun
l_hand = null
r_pocket = null
l_pocket = /obj/item/food/chocolatebunny
/datum/outfit/cursed_bunny/costume/post_equip(mob/living/carbon/human/equipped_on, visualsOnly=FALSE)
if(visualsOnly)
return
var/list/no_drops = list()
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_FEET)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_OCLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_HEAD)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_GLOVES)
for(var/obj/item/trait_needed as anything in no_drops)
ADD_TRAIT(trait_needed, TRAIT_NODROP, CURSED_ITEM_TRAIT(trait_needed.type))
trait_needed.name = "cursed " + trait_needed.name
/datum/outfit/cursed_bunny/color
name = "Cursed Bunny (Random Color)"
/datum/outfit/cursed_bunny/color/post_equip(mob/living/carbon/human/equipped_on, visualsOnly=FALSE)
if(visualsOnly)
return
var/bunny_color = random_color()
equipped_on.w_uniform?.greyscale_colors = "#[bunny_color]#[bunny_color]#ffffff#87502e"
equipped_on.wear_suit?.greyscale_colors = "#[bunny_color]"
equipped_on.head?.greyscale_colors = "#[bunny_color]"
equipped_on.shoes?.greyscale_colors = "#[bunny_color]"
equipped_on.wear_neck?.greyscale_colors = "#ffffff#[bunny_color]"
equipped_on.w_uniform?.update_greyscale()
equipped_on.wear_suit?.update_greyscale()
equipped_on.head?.update_greyscale()
equipped_on.shoes?.update_greyscale()
equipped_on.wear_neck?.update_greyscale()
equipped_on.update_worn_undersuit()
equipped_on.update_worn_oversuit()
equipped_on.update_worn_shoes()
equipped_on.update_worn_head()
equipped_on.update_worn_neck()
var/list/no_drops = list()
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_FEET)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_ICLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_OCLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_HEAD)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_NECK)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_GLOVES)
for(var/obj/item/trait_needed as anything in no_drops)
ADD_TRAIT(trait_needed, TRAIT_NODROP, CURSED_ITEM_TRAIT(trait_needed.type))
trait_needed.name = "cursed " + trait_needed.name
/datum/outfit/cursed_bunny/magician
name = "Cursed Bunny (Magician)"
uniform = /obj/item/clothing/under/costume/playbunny/magician
suit = /obj/item/clothing/suit/wizrobe/magician
head = /obj/item/clothing/head/wizard/magician
shoes = /obj/item/clothing/shoes/heels/magician
neck = /obj/item/clothing/neck/tie/bunnytie/magician/tied
r_hand = null
l_hand = /obj/item/gun/magic/wand/nothing
r_pocket = null
l_pocket = /obj/item/toy/cards/deck/tarot
/datum/outfit/plasmaman/cursed_bunny
name = "Cursed Bunny (Plasmaman)"
uniform = /obj/item/clothing/under/plasmaman/plasma_bun
suit = /obj/item/clothing/suit/jacket/tailcoat/plasmaman
head = /obj/item/clothing/head/helmet/space/plasmaman/bunny_ears
shoes = /obj/item/clothing/shoes/heels/enviroheels
neck = /obj/item/clothing/neck/tie/bunnytie/tied
belt = /obj/item/tank/internals/plasmaman/belt/full
r_pocket = /obj/item/toy/cards/deck
l_pocket = /obj/item/reagent_containers/cup/rag
r_hand = /obj/item/storage/bag/tray
l_hand = /obj/item/reagent_containers/cup/glass/drinkingglass/filled/champagne
internals_slot = ITEM_SLOT_BELT
/datum/outfit/plasmaman/cursed_bunny/post_equip(mob/living/carbon/human/equipped_on, visualsOnly=FALSE)
var/list/no_drops = list()
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_FEET)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_ICLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_OCLOTHING)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_HEAD)
no_drops += equipped_on.get_item_by_slot(ITEM_SLOT_NECK)
for(var/obj/item/trait_needed as anything in no_drops)
ADD_TRAIT(trait_needed, TRAIT_NODROP, CURSED_ITEM_TRAIT(trait_needed.type))
trait_needed.name = "cursed " + trait_needed.name
/obj/item/reagent_containers/cup/glass/drinkingglass/filled/champagne
name = "Champagne"
list_reagents = list(/datum/reagent/consumable/ethanol/champagne = 50)
| 0 | 0.828327 | 1 | 0.828327 | game-dev | MEDIA | 0.994034 | game-dev | 0.748845 | 1 | 0.748845 |
udacity/ud406 | 3,380 | 2.3.01-Exercise-BasicPlatforms/core/src/com/udacity/gamedev/gigagal/util/Assets.java | package com.udacity.gamedev.gigagal.util;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
public class Assets implements Disposable, AssetErrorListener {
public static final String TAG = Assets.class.getName();
public static final Assets instance = new Assets();
public GigaGalAssets gigaGalAssets;
private AssetManager assetManager;
private Assets() {
}
public void init(AssetManager assetManager) {
this.assetManager = assetManager;
assetManager.setErrorListener(this);
assetManager.load(Constants.TEXTURE_ATLAS, TextureAtlas.class);
assetManager.finishLoading();
TextureAtlas atlas = assetManager.get(Constants.TEXTURE_ATLAS);
gigaGalAssets = new GigaGalAssets(atlas);
}
@Override
public void error(AssetDescriptor asset, Throwable throwable) {
Gdx.app.error(TAG, "Couldn't load asset: " + asset.fileName, throwable);
}
@Override
public void dispose() {
assetManager.dispose();
}
public class GigaGalAssets {
public final AtlasRegion standingLeft;
public final AtlasRegion standingRight;
public final AtlasRegion walkingLeft;
public final AtlasRegion walkingRight;
public final AtlasRegion jumpingLeft;
public final AtlasRegion jumpingRight;
public final Animation walkingLeftAnimation;
public final Animation walkingRightAnimation;
public GigaGalAssets(TextureAtlas atlas) {
standingLeft = atlas.findRegion(Constants.STANDING_LEFT);
standingRight = atlas.findRegion(Constants.STANDING_RIGHT);
walkingLeft = atlas.findRegion(Constants.WALKING_LEFT_2);
walkingRight = atlas.findRegion(Constants.WALKING_RIGHT_2);
jumpingLeft = atlas.findRegion(Constants.JUMPING_LEFT);
jumpingRight = atlas.findRegion(Constants.JUMPING_RIGHT);
Array<AtlasRegion> walkingLeftFrames = new Array<AtlasRegion>();
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_2));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_1));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_2));
walkingLeftFrames.add(atlas.findRegion(Constants.WALKING_LEFT_3));
walkingLeftAnimation = new Animation(Constants.WALK_LOOP_DURATION, walkingLeftFrames, PlayMode.LOOP);
Array<AtlasRegion> walkingRightFrames = new Array<AtlasRegion>();
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_2));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_1));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_2));
walkingRightFrames.add(atlas.findRegion(Constants.WALKING_RIGHT_3));
walkingRightAnimation = new Animation(Constants.WALK_LOOP_DURATION, walkingRightFrames, PlayMode.LOOP);
}
}
}
| 0 | 0.659382 | 1 | 0.659382 | game-dev | MEDIA | 0.530047 | game-dev,desktop-app | 0.953944 | 1 | 0.953944 |
open-watcom/open-watcom-v2 | 13,177 | bld/cg/c/scinfo.c | /****************************************************************************
*
* Open Watcom Project
*
* Copyright (c) 2002-2025 The Open Watcom Contributors. All Rights Reserved.
* Portions Copyright (c) 1983-2002 Sybase, Inc. All Rights Reserved.
*
* ========================================================================
*
* This file contains Original Code and/or Modifications of Original
* Code as defined in and that are subject to the Sybase Open Watcom
* Public License version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. BY USING THIS FILE YOU AGREE TO
* ALL TERMS AND CONDITIONS OF THE LICENSE. A copy of the License is
* provided with the Original Code and Modifications, and is also
* available at www.sybase.com/developer/opensource.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND SYBASE AND ALL CONTRIBUTORS HEREBY DISCLAIM
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR
* NON-INFRINGEMENT. Please see the License for the specific language
* governing rights and limitations under the License.
*
* ========================================================================
*
* Description: Instruction scoring helper functions.
*
****************************************************************************/
#include "_cgstd.h"
#include "coderep.h"
#include "score.h"
#include "zoiks.h"
#include "data.h"
#include "utils.h"
/*
* following 3 variables are used as unique addresses
* to indicate special type of relocatable constant
*/
static pointer SegConstSymbol;
static pointer HighAddrSymbol;
static pointer HighAddrConst;
static bool ScoreSame( score_info *x, score_info *y )
/*******************************************************/
{
if( x->class != y->class )
return( false );
if( x->base != y->base )
return( false );
if( x->index_reg != y->index_reg )
return( false );
if( x->class == SC_N_TEMP && x->symbol.u.t->v.id == y->symbol.u.t->v.id )
return( true );
if( x->class == SC_N_VOLATILE )
return( false );
if( x->class == SC_N_INITIAL )
return( false );
if( x->class == SC_N_INDEXED && x->scale != y->scale )
return( false );
if( x->symbol.u.p == y->symbol.u.p )
return( true );
return( false );
}
static bool ScoreStomp( score_info *x, score_info *y )
/********************************************************/
{
score_info *tmp;
/*
* get the 'free' index into x if there is one
*/
if( y->class == SC_N_INDEXED && y->base == NULL ) {
tmp = x;
x = y;
y = tmp;
}
if( x->class == SC_N_INDEXED && x->base == NULL ) {
switch( y->class ) {
case SC_N_MEMORY:
if( _IsModel( CGSW_GEN_RELAX_ALIAS ) )
return( false );
/* fall through */
case SC_N_INDEXED:
return( true );
case SC_N_TEMP:
if( y->symbol.u.v->usage & USE_ADDRESS )
return( true );
return( false );
}
}
/*
* get the 'bound' index into x if there is one
*/
if( y->class == SC_N_INDEXED ) {
tmp = x;
x = y;
y = tmp;
}
if( x->class == SC_N_INDEXED && x->base != NULL ) {
switch( y->class ) {
case SC_N_TEMP:
if( x->base->n.class == N_TEMP ) {
if( y->symbol.u.t->v.id == x->base->t.v.id ) {
return( true );
}
}
break;
case SC_N_MEMORY:
if( x->base->n.class == N_MEMORY ) {
if( y->symbol.u.p == x->base->v.symbol ) {
return( true );
}
}
break;
case SC_N_INDEXED:
if( y->base == NULL )
return( true );
if( y->base->n.class != x->base->n.class )
return( false );
switch( x->base->n.class ) {
case N_TEMP:
return( y->base->t.v.id == x->base->t.v.id );
case N_MEMORY:
return( y->base->v.symbol == x->base->v.symbol );
}
break;
}
}
return( false );
}
bool ScoreLookup( score *scoreitem, score_info *info )
/*******************************************************/
{
score_list *curr;
if( info->class == SC_N_VOLATILE )
return( false );
for( curr = *scoreitem->list; curr != NULL; curr = curr->next ) {
if( ScoreSame( &curr->info, info ) && curr->info.offset == info->offset ) {
return( true );
}
}
return( false );
}
bool ScoreEqual( score *scoreboard, int index, score_info *info )
/******************************************************************/
{
if( ScoreLookup( &scoreboard[index], info ) )
return( true );
if( _IsModel( CGSW_GEN_SUPER_OPTIMAL ) ) {
score_reg *entry;
bool is_equal;
type_length half_size;
entry = ScoreList[index];
if( entry->high == NO_INDEX || entry->low == NO_INDEX )
return( false );
/*
* See if low parts & high parts of register pair contain
* the right information
*/
if( info->class == SC_N_CONSTANT )
return( false );
if( !ScoreLookup( &scoreboard[entry->low], info ) )
return( false );
half_size = entry->size / 2;
info->offset += half_size;
is_equal = ScoreLookup( &scoreboard[entry->high], info );
info->offset -= half_size;
return( is_equal );
}
return( false );
}
static void ScoreInsert( score *scoreboard, int i, score_info *info )
/***************************************************************************/
{
score_list *new_sc;
int j;
if( info->class == SC_N_VOLATILE )
return;
if( HW_Ovlap( ScoreList[i]->reg, CurrProc->state.unalterable ) )
return;
new_sc = NewScListEntry();
Copy( info, &new_sc->info, sizeof( score_info ) );
new_sc->next = *scoreboard[i].list;
*scoreboard[i].list = new_sc;
for( j = ScoreCount; j-- > 0; ) {
if( ( j != i ) && ScoreEqual( scoreboard, j, info ) ) {
RegAdd( scoreboard, i, j );
break;
}
}
}
static void ScoreAdd( score *scoreboard, int i, score_info *info )
/********************************************************************/
{
if( _IsModel( CGSW_GEN_SUPER_OPTIMAL ) ) {
score *first;
score *curr;
if( (info->class == SC_N_INDEXED) && (info->index_reg != NO_INDEX) ) {
first = &scoreboard[info->index_reg];
curr = first;
for( ;; ) {
info->index_reg = ScoreList[curr->index]->reg_name->r.reg_index;
if( !ScoreLookup( &scoreboard[i], info ) ) {
ScoreInsert( scoreboard, i, info );
}
curr = curr->next_reg;
if( curr == first ) {
break;
}
}
} else {
if( !ScoreLookup( &scoreboard[i], info ) ) {
ScoreInsert( scoreboard, i, info );
}
}
} else {
if( !ScoreLookup( &scoreboard[i], info ) ) {
ScoreInsert( scoreboard, i, info );
}
}
}
void ScoreAssign( score *scoreboard, int index, score_info *info )
/*******************************************************************/
{
ScoreAdd( scoreboard, index, info );
if( _IsModel( CGSW_GEN_SUPER_OPTIMAL ) ) {
score_reg *entry;
uint hi_off;
uint lo_off;
uint offset;
entry = ScoreList[index];
if( entry->high != NO_INDEX && entry->low != NO_INDEX ) {
if( info->class == SC_N_CONSTANT ) {
if( info->symbol.u.p != NULL )
return; /* relocatable const */
hi_off = info->offset >> ( entry->size * 4 );
lo_off = info->offset & ~( hi_off << ( entry->size * 4 ) );
} else {
hi_off = info->offset + entry->size / 2;
lo_off = info->offset;
}
offset = info->offset;
info->offset = hi_off;
ScoreAdd( scoreboard, entry->high, info );
info->offset = lo_off;
ScoreAdd( scoreboard, entry->low, info );
info->offset = offset;
}
}
}
void ScoreInfo( score_info *info, name *op )
/*********************************************/
{
if( op->n.class == N_INDEXED
&& op->i.index_flags ==( X_FAKE_BASE | X_BASE_IS_INDEX) ) {
op = op->i.base; /* track memory location */
}
info->class = (score_name_class_def)op->n.class;
info->scale = 0;
info->base = NULL;
info->index_reg = NO_INDEX;
switch( op->n.class ) {
case N_CONSTANT:
switch( op->c.const_type ) {
case CONS_ABSOLUTE:
info->symbol.u.p = NULL;
info->offset = op->c.lo.u.int_value;
break;
case CONS_SEGMENT:
info->symbol.u.p = &SegConstSymbol;
info->offset = op->c.lo.u.int_value;
break;
case CONS_OFFSET:
case CONS_ADDRESS:
info->symbol.u.p = op->c.value;
info->offset = op->c.lo.u.int_value;
break;
case CONS_HIGH_ADDR:
/* FIXME: not sure what to do here */
if( op->c.value != NULL ) {
info->symbol.u.p = &HighAddrSymbol;
info->offset = (int_32)(pointer_uint)op->c.value;
} else {
info->symbol.u.p = &HighAddrConst;
info->offset = op->c.lo.u.int_value;
}
break;
default:
_Zoiks( ZOIKS_046 );
break;
}
break;
case N_TEMP:
if( op->v.usage & VAR_VOLATILE ) {
info->class = SC_N_VOLATILE;
}
info->symbol.u.t = &(op->t);
info->offset = op->v.offset;
break;
case N_MEMORY:
if( op->v.usage & VAR_VOLATILE ) {
info->class = SC_N_VOLATILE;
}
info->symbol.u.p = op->v.symbol;
info->offset = op->v.offset;
break;
case N_INDEXED:
if( op->i.index_flags & X_VOLATILE ) {
info->class = SC_N_VOLATILE;
}
info->symbol.u.p = NULL;
info->offset = op->i.constant;
info->index_reg = op->i.index->r.reg_index;
info->base = op->i.base;
info->scale = op->i.scale;
break;
}
}
bool ScoreLAInfo( score_info *info, name *op )
/***********************************************/
{
switch( op->n.class ) {
case N_TEMP:
case N_MEMORY:
info->class = SC_N_ADDRESS;
info->symbol.u.p = op;
info->offset = 0;
info->index_reg = NO_INDEX;
info->base = NULL;
info->scale = 0;
return( true );
default:
return( false );
}
}
void ScoreKillInfo( score *scoreboard, name *op, score_info *info, hw_reg_set except )
/***************************************************************************************/
{
score_list *curr;
score_list **owner;
score_reg *entry;
int last_offset;
int i;
/*
* Memory from info+offset up to (not including) info+last_offset
* has been overwritten
*/
last_offset = info->offset + op->n.size;
entry = ScoreList[0];
for( i = ScoreCount; i > 0; --i ) {
if( !HW_Subset( except, entry->reg ) ) {
for( owner = scoreboard->list; (curr = *owner) != NULL; ) {
/*
* Currently looking at memory
* from curr->info+offset
* to curr->info+offset+entry->size
*
* If the names 'info' and 'curr' match, then have an
* overlap if
* info.start < curr.end AND info.end > curr.start
*
* e.g. info |-------|
* curr |-----|
*/
/* impossible! if( info->base == op ) break;*/
if( !ScoreStomp( info, &curr->info ) ) {
if( ScoreSame( info, &curr->info )
&& last_offset > curr->info.offset
&& info->offset < curr->info.offset + entry->size ) {
*owner = curr->next;
FreeScListEntry( curr );
continue;
}
owner = &curr->next;
} else {
*owner = curr->next;
FreeScListEntry( curr );
}
}
}
++entry;
++scoreboard;
}
}
| 0 | 0.959865 | 1 | 0.959865 | game-dev | MEDIA | 0.302565 | game-dev | 0.975051 | 1 | 0.975051 |
Critical-Impact/InventoryTools | 2,722 | InventoryTools/Logic/Settings/TrackMobSpawnSetting.cs | using CriticalCommonLib.Services;
using DalaMock.Shared.Interfaces;
using Dalamud.Bindings.ImGui;
using InventoryTools.Logic.Settings.Abstract;
using InventoryTools.Services;
using Microsoft.Extensions.Logging;
using OtterGui;
namespace InventoryTools.Logic.Settings;
public class TrackMobSpawnSetting : BooleanSetting
{
private readonly IFileDialogManager _fileDialogManager;
private readonly IMobTracker _mobTracker;
public TrackMobSpawnSetting(ILogger<TrackMobSpawnSetting> logger, ImGuiService imGuiService, IFileDialogManager fileDialogManager, IMobTracker mobTracker) : base(logger, imGuiService)
{
_fileDialogManager = fileDialogManager;
_mobTracker = mobTracker;
}
public override bool DefaultValue { get; set; } = false;
public override bool CurrentValue(InventoryToolsConfiguration configuration)
{
return configuration.TrackMobSpawns;
}
public override void UpdateFilterConfiguration(InventoryToolsConfiguration configuration, bool newValue)
{
configuration.TrackMobSpawns = newValue;
}
public override string Key { get; set; } = "TrackMobSpawns";
public override string Name { get; set; } = "Track Mob Spawns";
public override string HelpText { get; set; } =
"Should the plugin track where mobs spawn as you move around. This data is not used by the plugin yet but once you have collected enough you can hit the button next to the checkbox to export a file containing those positions. If you upload those CSVs and send a url to via feedback I can use that spawn data to provide accurate mob spawns for everyone.";
public override SettingCategory SettingCategory { get; set; } = SettingCategory.MobSpawnTracker;
public override SettingSubCategory SettingSubCategory { get; } = SettingSubCategory.General;
public override void Draw(InventoryToolsConfiguration configuration, string? customName, bool? disableReset,
bool? disableColouring)
{
base.Draw(configuration, null, null, null);
if (configuration.TrackMobSpawns)
{
ImGui.SameLine();
if (ImGui.Button("Export CSV"))
{
_fileDialogManager.SaveFileDialog("Save to csv", "*.csv", "mob_spawns.csv", ".csv",
(b, s) => { SaveMobSpawns(b, s); }, null, true);
}
ImGuiUtil.HoverTooltip("Export a CSV containing the mob spawn IDs and their positions.");
}
}
private void SaveMobSpawns(bool b, string s)
{
if (b)
{
var entries = _mobTracker.GetEntries();
_mobTracker.SaveCsv(s, entries);
}
}
public override string Version => "1.7.0.0";
} | 0 | 0.896062 | 1 | 0.896062 | game-dev | MEDIA | 0.824378 | game-dev | 0.850844 | 1 | 0.850844 |
lua9520/source-engine-2018-hl2_src | 1,060 | game/server/tf/halloween/eyeball_boss/eyeball_behavior/eyeball_boss_emote.h | //========= Copyright Valve Corporation, All rights reserved. ============//
// eyeball_boss_emote.h
// The 2011 Halloween Boss - play an animation
// Michael Booth, October 2011
#ifndef EYEBALL_BOSS_EMOTE_H
#define EYEBALL_BOSS_EMOTE_H
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
class CEyeballBossEmote : public Action< CEyeballBoss >
{
public:
CEyeballBossEmote( int animationSequence, const char *soundName, Action< CEyeballBoss > *nextAction = NULL );
virtual ~CEyeballBossEmote() { }
virtual ActionResult< CEyeballBoss > OnStart( CEyeballBoss *me, Action< CEyeballBoss > *priorAction );
virtual ActionResult< CEyeballBoss > Update( CEyeballBoss *me, float interval );
virtual const char *GetName( void ) const { return "Emote"; } // return name of this action
private:
int m_animationSequence;
const char *m_soundName;
Action< CEyeballBoss > *m_nextAction;
};
#endif // EYEBALL_BOSS_EMOTE_H
| 0 | 0.669654 | 1 | 0.669654 | game-dev | MEDIA | 0.922927 | game-dev | 0.695129 | 1 | 0.695129 |
flarialmc/dll | 2,767 | src/SDK/Client/Core/ClientInstance.cpp | #include "ClientInstance.hpp"
#include "../../SDK.hpp"
#include <libhat/Access.hpp>
LocalPlayer *ClientInstance::getLocalPlayer() {
// Indig0r
static uintptr_t indexRef;
if (indexRef == 0) {
indexRef = GET_SIG_ADDRESS("ClientInstance::getLocalPlayerIndex");
}
int index = *reinterpret_cast<int*>(indexRef + 9) / 8;
return Memory::CallVFuncI<LocalPlayer *>(index, this);
}
BlockSource *ClientInstance::getBlockSource() {
static int off = GET_OFFSET("ClientInstance::getBlockSource");
return Memory::CallVFuncI<BlockSource *>(off, this);
}
void ClientInstance::grabMouse(int delay) {
if (delay > 0 ) {
std::thread troll([this, delay]() {
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
static uintptr_t indexRef;
if (indexRef == 0) {
indexRef = GET_SIG_ADDRESS("ClientInstance::grabMouse");
}
int index = *reinterpret_cast<int*>(indexRef + 3) / 8;
return Memory::CallVFuncI<void>(index, this);
});
troll.detach();
} else {
static uintptr_t indexRef;
if (indexRef == 0) {
indexRef = GET_SIG_ADDRESS("ClientInstance::grabMouse");
}
int index = *reinterpret_cast<int*>(indexRef + 3) / 8;
return Memory::CallVFuncI<void>(index, this);
}
}
void ClientInstance::releaseMouse() {
static uintptr_t indexRef;
if (indexRef == 0) {
indexRef = GET_SIG_ADDRESS("ClientInstance::grabMouse");
if(indexRef == NULL) {
return;
}
}
int index = *reinterpret_cast<int *>(indexRef + 3) / 8;
return Memory::CallVFuncI<void>(index + 1, this);
}
std::string ClientInstance::getTopScreenName() {
return SDK::currentScreen;
}
std::string ClientInstance::getScreenName() {
return SDK::currentScreen;
// std::string screen = "no_screen";
/*static auto sig = GET_SIG_ADDRESS("ClientInstance::getScreenName");
auto fn = reinterpret_cast<std::string& (__thiscall *)(ClientInstance*, std::string&)>(sig);
screen = fn(this, screen);
return screen;*/
}
LevelRender *ClientInstance::getLevelRender() {
return hat::member_at<LevelRender *>(this, GET_OFFSET("ClientInstance::levelRenderer"));
}
void ClientInstance::_updateScreenSizeVariables(Vec2<float> *totalScreenSize,
Vec2<float> *safeZone,
float forcedGuiScale) {
static auto sig = GET_SIG_ADDRESS("ClientInstance::_updateScreenSizeVariables");
auto fn = reinterpret_cast<void (__thiscall *)(ClientInstance*, Vec2<float>*, Vec2<float>*, float)>(sig);
fn(this, totalScreenSize, safeZone, forcedGuiScale);
} | 0 | 0.874175 | 1 | 0.874175 | game-dev | MEDIA | 0.436296 | game-dev | 0.756926 | 1 | 0.756926 |
compatibl/tradeentry | 1,638 | stubs/cl/runtime/records/custom/stub_custom_base.py | # Copyright (C) 2023-present The Project Contributors
#
# 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.
from typing import Dict
from cl.runtime.records.protocols import TDataField
from cl.runtime.records.record_mixin import RecordMixin
from stubs.cl.runtime.records.custom.stub_custom_base_key import StubCustomBaseKey
class StubCustomBase(StubCustomBaseKey, RecordMixin[StubCustomBaseKey]):
"""Stub record used in tests."""
float_field: float | None
"""Float attribute of base class."""
def __init__(self, *, str_field: str = "abc", int_field: int = 123, float_field: float = 4.56):
"""Initialize instance attributes."""
RecordMixin.__init__(self)
StubCustomBaseKey.__init__(self, str_field=str_field, int_field=int_field)
self.float_field = float_field
def to_dict(self) -> Dict[str, TDataField]:
return {
"str_field": self.str_field,
"int_field": self.int_field,
"float_field": self.float_field,
}
def get_key(self) -> StubCustomBaseKey:
return StubCustomBaseKey(str_field=self.str_field, int_field=self.int_field)
| 0 | 0.746193 | 1 | 0.746193 | game-dev | MEDIA | 0.202832 | game-dev | 0.616189 | 1 | 0.616189 |
Hubs-Foundation/hubs-cloud | 1,263 | community-edition/services/hubs/src/components/drop-object-button.js | import { COLLISION_LAYERS } from "../constants";
AFRAME.registerComponent("drop-object-button", {
init() {
this.onClick = () => {
if (!NAF.utils.isMine(this.targetEl) && !NAF.utils.takeOwnership(this.targetEl)) return;
this.targetEl.setAttribute("floaty-object", { modifyGravityOnRelease: false });
this.targetEl.setAttribute("body-helper", {
type: "dynamic",
gravity: { x: 0, y: -9.8, z: 0 },
angularDamping: 0.01,
linearDamping: 0.01,
linearSleepingThreshold: 1.6,
angularSleepingThreshold: 2.5,
collisionFilterMask: COLLISION_LAYERS.DEFAULT_INTERACTABLE
});
const physicsSystem = this.el.sceneEl.systems["hubs-systems"].physicsSystem;
if (this.targetEl.components["body-helper"].uuid) {
physicsSystem.activateBody(this.targetEl.components["body-helper"].uuid);
}
// Remove drop button after using it
this.el.parentNode.removeChild(this.el);
};
NAF.utils.getNetworkedEntity(this.el).then(networkedEl => {
this.targetEl = networkedEl;
});
},
play() {
this.el.object3D.addEventListener("interact", this.onClick);
},
pause() {
this.el.object3D.removeEventListener("interact", this.onClick);
}
});
| 0 | 0.841887 | 1 | 0.841887 | game-dev | MEDIA | 0.760656 | game-dev,web-frontend | 0.906484 | 1 | 0.906484 |
opendilab/DOS | 4,465 | scenario_runner/srunner/scenariomanager/timer.py | #!/usr/bin/env python
# Copyright (c) 2018-2020 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
This module provides access to the CARLA game time and contains a py_trees
timeout behavior using the CARLA game time
"""
import datetime
import py_trees
class GameTime(object):
"""
This (static) class provides access to the CARLA game time.
The elapsed game time can be simply retrieved by calling:
GameTime.get_time()
"""
_current_game_time = 0.0 # Elapsed game time after starting this Timer
_carla_time = 0.0
_last_frame = 0
_platform_timestamp = 0
_init = False
@staticmethod
def on_carla_tick(timestamp):
"""
Callback receiving the CARLA time
Update time only when frame is more recent that last frame
"""
if GameTime._last_frame < timestamp.frame:
frames = timestamp.frame - GameTime._last_frame if GameTime._init else 1
GameTime._current_game_time += timestamp.delta_seconds * frames
GameTime._last_frame = timestamp.frame
GameTime._platform_timestamp = datetime.datetime.now()
GameTime._init = True
GameTime._carla_time = timestamp.elapsed_seconds
@staticmethod
def restart():
"""
Reset game timer to 0
"""
GameTime._current_game_time = 0.0
GameTime._init = False
@staticmethod
def get_time():
"""
Returns elapsed game time
"""
return GameTime._current_game_time
@staticmethod
def get_carla_time():
"""
Returns elapsed game time
"""
return GameTime._carla_time
@staticmethod
def get_wallclocktime():
"""
Returns elapsed game time
"""
return GameTime._platform_timestamp
@staticmethod
def get_frame():
"""
Returns elapsed game time
"""
return GameTime._last_frame
class SimulationTimeCondition(py_trees.behaviour.Behaviour):
"""
This class contains an atomic simulation time condition behavior.
It uses the CARLA game time, not the system time which is used by
the py_trees timer.
Returns, if the provided success_rule (greaterThan, lessThan, equalTo)
was successfully evaluated
"""
def __init__(self, timeout, success_rule="greaterThan", name="SimulationTimeCondition"):
"""
Setup timeout
"""
super(SimulationTimeCondition, self).__init__(name)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._timeout_value = timeout
self._start_time = 0.0
self._success_rule = success_rule
self._ops = {"greaterThan": (lambda x, y: x > y),
"equalTo": (lambda x, y: x == y),
"lessThan": (lambda x, y: x < y)}
def initialise(self):
"""
Set start_time to current GameTime
"""
self._start_time = GameTime.get_time()
self.logger.debug("%s.initialise()" % (self.__class__.__name__))
def update(self):
"""
Get current game time, and compare it to the timeout value
Upon successfully comparison using the provided success_rule operator,
the status changes to SUCCESS
"""
elapsed_time = GameTime.get_time() - self._start_time
if not self._ops[self._success_rule](elapsed_time, self._timeout_value):
new_status = py_trees.common.Status.RUNNING
else:
new_status = py_trees.common.Status.SUCCESS
self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
return new_status
class TimeOut(SimulationTimeCondition):
"""
This class contains an atomic timeout behavior.
It uses the CARLA game time, not the system time which is used by
the py_trees timer.
"""
def __init__(self, timeout, name="TimeOut"):
"""
Setup timeout
"""
super(TimeOut, self).__init__(timeout, name=name)
self.timeout = False
def update(self):
"""
Upon reaching the timeout value the status changes to SUCCESS
"""
new_status = super(TimeOut, self).update()
if new_status == py_trees.common.Status.SUCCESS:
self.timeout = True
return new_status
| 0 | 0.6402 | 1 | 0.6402 | game-dev | MEDIA | 0.848475 | game-dev | 0.890497 | 1 | 0.890497 |
Sandern/lambdawars | 2,685 | src/game/shared/swarm/asw_holdout_wave.cpp | #include "cbase.h"
#include "asw_shareddefs.h"
#include "asw_holdout_wave.h"
#include "gamestringpool.h"
#ifdef GAME_DLL
#include "asw_spawn_group.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar asw_holdout_debug;
//===============================================
// An individual entry in a holdout wave
//===============================================
CASW_Holdout_Wave_Entry::CASW_Holdout_Wave_Entry()
{
}
CASW_Holdout_Wave_Entry::~CASW_Holdout_Wave_Entry()
{
}
void CASW_Holdout_Wave_Entry::LoadFromKeyValues( KeyValues *pKeys )
{
m_flSpawnDelay = pKeys->GetFloat( "SpawnDelay", 1.0f );
m_iszAlienClass = AllocPooledString( pKeys->GetString( "AlienClass" ) );
m_nQuantity = pKeys->GetInt( "Quantity", 1 );
m_flSpawnDuration = pKeys->GetFloat( "SpawnDuration", 0.0f );
m_nModifiers = pKeys->GetInt( "Modifiers", 0 ); // TODO: Turn this into a string parser for the bit flag names
m_iszSpawnGroupName = AllocPooledString( pKeys->GetString( "SpawnGroup" ) );
m_hSpawnGroup = NULL;
}
#ifdef GAME_DLL
CASW_Spawn_Group* CASW_Holdout_Wave_Entry::GetSpawnGroup()
{
if ( m_hSpawnGroup.Get() )
{
return m_hSpawnGroup.Get();
}
CBaseEntity *pEnt = gEntList.FindEntityByName( NULL, m_iszSpawnGroupName );
if ( pEnt && pEnt->Classify() == CLASS_ASW_SPAWN_GROUP )
{
m_hSpawnGroup = assert_cast<CASW_Spawn_Group*>( pEnt );
return m_hSpawnGroup.Get();
}
Warning( "Holdout wave entry can't find spawngroup %s\n", STRING( m_iszSpawnGroupName ) );
return NULL;
}
#endif
//===============================================
// A wave in holdout mode
//===============================================
CASW_Holdout_Wave::CASW_Holdout_Wave()
{
m_nTotalAliens = 0;
}
CASW_Holdout_Wave::~CASW_Holdout_Wave()
{
m_Entries.PurgeAndDeleteElements();
}
void CASW_Holdout_Wave::LoadFromKeyValues( int nWaveNumber, KeyValues *pKeys )
{
m_Entries.PurgeAndDeleteElements();
m_nTotalAliens = 0;
m_nWaveNumber = nWaveNumber;
m_iszWaveName = AllocPooledString( pKeys->GetString( "Name", "Unknown" ) );
m_nEnvironmentModifiers = pKeys->GetInt( "EnvironmentModifiers" ); // TODO: Turn this into a string parser for the bit flag names
m_bWaveHasResupply = pKeys->GetBool( "Resupply", false );
for ( KeyValues *pKey = pKeys->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey() )
{
if ( !Q_stricmp( pKey->GetName(), "ENTRY" ) )
{
if ( asw_holdout_debug.GetBool() )
{
Msg( " Loading a wave entry\n" );
}
CASW_Holdout_Wave_Entry *pEntry = new CASW_Holdout_Wave_Entry();
pEntry->LoadFromKeyValues( pKey );
m_Entries.AddToTail( pEntry );
m_nTotalAliens += pEntry->GetQuantity();
}
}
} | 0 | 0.982749 | 1 | 0.982749 | game-dev | MEDIA | 0.824935 | game-dev | 0.990223 | 1 | 0.990223 |
openjdk/jdk8 | 10,463 | hotspot/src/share/vm/shark/sharkValue.hpp | /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2008, 2009 Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_SHARK_SHARKVALUE_HPP
#define SHARE_VM_SHARK_SHARKVALUE_HPP
#include "ci/ciType.hpp"
#include "memory/allocation.hpp"
#include "shark/llvmHeaders.hpp"
#include "shark/llvmValue.hpp"
#include "shark/sharkType.hpp"
// Items on the stack and in local variables are tracked using
// SharkValue objects.
//
// All SharkValues are one of two core types, SharkNormalValue
// and SharkAddressValue, but no code outside this file should
// ever refer to those directly. The split is because of the
// way JSRs are handled: the typeflow pass expands them into
// multiple copies, so the return addresses pushed by jsr and
// popped by ret only exist at compile time. Having separate
// classes for these allows us to check that our jsr handling
// is correct, via assertions.
//
// There is one more type, SharkPHIValue, which is a subclass
// of SharkNormalValue with a couple of extra methods. Use of
// SharkPHIValue outside of this file is acceptable, so long
// as it is obtained via SharkValue::as_phi().
class SharkBuilder;
class SharkPHIValue;
class SharkValue : public ResourceObj {
protected:
SharkValue() {}
// Cloning
public:
virtual SharkValue* clone() const = 0;
// Casting
public:
virtual bool is_phi() const;
virtual SharkPHIValue* as_phi();
// Comparison
public:
virtual bool equal_to(SharkValue* other) const = 0;
// Type access
public:
virtual BasicType basic_type() const = 0;
virtual ciType* type() const;
virtual bool is_jint() const;
virtual bool is_jlong() const;
virtual bool is_jfloat() const;
virtual bool is_jdouble() const;
virtual bool is_jobject() const;
virtual bool is_jarray() const;
virtual bool is_address() const;
virtual int size() const = 0;
bool is_one_word() const {
return size() == 1;
}
bool is_two_word() const {
return size() == 2;
}
// Typed conversion from SharkValues
public:
virtual llvm::Value* jint_value() const;
virtual llvm::Value* jlong_value() const;
virtual llvm::Value* jfloat_value() const;
virtual llvm::Value* jdouble_value() const;
virtual llvm::Value* jobject_value() const;
virtual llvm::Value* jarray_value() const;
virtual int address_value() const;
// Typed conversion to SharkValues
public:
static SharkValue* create_jint(llvm::Value* value, bool zero_checked) {
assert(value->getType() == SharkType::jint_type(), "should be");
return create_generic(ciType::make(T_INT), value, zero_checked);
}
static SharkValue* create_jlong(llvm::Value* value, bool zero_checked) {
assert(value->getType() == SharkType::jlong_type(), "should be");
return create_generic(ciType::make(T_LONG), value, zero_checked);
}
static SharkValue* create_jfloat(llvm::Value* value) {
assert(value->getType() == SharkType::jfloat_type(), "should be");
return create_generic(ciType::make(T_FLOAT), value, false);
}
static SharkValue* create_jdouble(llvm::Value* value) {
assert(value->getType() == SharkType::jdouble_type(), "should be");
return create_generic(ciType::make(T_DOUBLE), value, false);
}
static SharkValue* create_jobject(llvm::Value* value, bool zero_checked) {
assert(value->getType() == SharkType::oop_type(), "should be");
return create_generic(ciType::make(T_OBJECT), value, zero_checked);
}
// Typed conversion from constants of various types
public:
static SharkValue* jint_constant(jint value) {
return create_jint(LLVMValue::jint_constant(value), value != 0);
}
static SharkValue* jlong_constant(jlong value) {
return create_jlong(LLVMValue::jlong_constant(value), value != 0);
}
static SharkValue* jfloat_constant(jfloat value) {
return create_jfloat(LLVMValue::jfloat_constant(value));
}
static SharkValue* jdouble_constant(jdouble value) {
return create_jdouble(LLVMValue::jdouble_constant(value));
}
static SharkValue* null() {
return create_jobject(LLVMValue::null(), false);
}
static inline SharkValue* address_constant(int bci);
// Type-losing conversions -- use with care!
public:
virtual llvm::Value* generic_value() const = 0;
virtual llvm::Value* intptr_value(SharkBuilder* builder) const;
static inline SharkValue* create_generic(ciType* type,
llvm::Value* value,
bool zero_checked);
static inline SharkValue* create_phi(ciType* type,
llvm::PHINode* phi,
const SharkPHIValue* parent = NULL);
// Phi-style stuff
public:
virtual void addIncoming(SharkValue* value, llvm::BasicBlock* block);
virtual SharkValue* merge(SharkBuilder* builder,
SharkValue* other,
llvm::BasicBlock* other_block,
llvm::BasicBlock* this_block,
const char* name) = 0;
// Repeated null and divide-by-zero check removal
public:
virtual bool zero_checked() const;
virtual void set_zero_checked(bool zero_checked);
};
class SharkNormalValue : public SharkValue {
friend class SharkValue;
protected:
SharkNormalValue(ciType* type, llvm::Value* value, bool zero_checked)
: _type(type), _llvm_value(value), _zero_checked(zero_checked) {}
private:
ciType* _type;
llvm::Value* _llvm_value;
bool _zero_checked;
private:
llvm::Value* llvm_value() const {
return _llvm_value;
}
// Cloning
public:
SharkValue* clone() const;
// Comparison
public:
bool equal_to(SharkValue* other) const;
// Type access
public:
ciType* type() const;
BasicType basic_type() const;
int size() const;
public:
bool is_jint() const;
bool is_jlong() const;
bool is_jfloat() const;
bool is_jdouble() const;
bool is_jobject() const;
bool is_jarray() const;
// Typed conversions to LLVM values
public:
llvm::Value* jint_value() const;
llvm::Value* jlong_value() const;
llvm::Value* jfloat_value() const;
llvm::Value* jdouble_value() const;
llvm::Value* jobject_value() const;
llvm::Value* jarray_value() const;
// Type-losing conversions, use with care
public:
llvm::Value* generic_value() const;
llvm::Value* intptr_value(SharkBuilder* builder) const;
// Phi-style stuff
public:
SharkValue* merge(SharkBuilder* builder,
SharkValue* other,
llvm::BasicBlock* other_block,
llvm::BasicBlock* this_block,
const char* name);
// Repeated null and divide-by-zero check removal
public:
bool zero_checked() const;
void set_zero_checked(bool zero_checked);
};
class SharkPHIValue : public SharkNormalValue {
friend class SharkValue;
protected:
SharkPHIValue(ciType* type, llvm::PHINode* phi, const SharkPHIValue *parent)
: SharkNormalValue(type, phi, parent && parent->zero_checked()),
_parent(parent),
_all_incomers_zero_checked(true) {}
private:
const SharkPHIValue* _parent;
bool _all_incomers_zero_checked;
private:
const SharkPHIValue* parent() const {
return _parent;
}
bool is_clone() const {
return parent() != NULL;
}
public:
bool all_incomers_zero_checked() const {
if (is_clone())
return parent()->all_incomers_zero_checked();
return _all_incomers_zero_checked;
}
// Cloning
public:
SharkValue* clone() const;
// Casting
public:
bool is_phi() const;
SharkPHIValue* as_phi();
// Phi-style stuff
public:
void addIncoming(SharkValue *value, llvm::BasicBlock* block);
};
class SharkAddressValue : public SharkValue {
friend class SharkValue;
protected:
SharkAddressValue(int bci)
: _bci(bci) {}
private:
int _bci;
// Cloning
public:
SharkValue* clone() const;
// Comparison
public:
bool equal_to(SharkValue* other) const;
// Type access
public:
BasicType basic_type() const;
int size() const;
bool is_address() const;
// Typed conversion from SharkValues
public:
int address_value() const;
// Type-losing conversion -- use with care!
public:
llvm::Value* generic_value() const;
// Phi-style stuff
public:
void addIncoming(SharkValue *value, llvm::BasicBlock* block);
SharkValue* merge(SharkBuilder* builder,
SharkValue* other,
llvm::BasicBlock* other_block,
llvm::BasicBlock* this_block,
const char* name);
};
// SharkValue methods that can't be declared above
inline SharkValue* SharkValue::create_generic(ciType* type,
llvm::Value* value,
bool zero_checked) {
return new SharkNormalValue(type, value, zero_checked);
}
inline SharkValue* SharkValue::create_phi(ciType* type,
llvm::PHINode* phi,
const SharkPHIValue* parent) {
return new SharkPHIValue(type, phi, parent);
}
inline SharkValue* SharkValue::address_constant(int bci) {
return new SharkAddressValue(bci);
}
#endif // SHARE_VM_SHARK_SHARKVALUE_HPP
| 0 | 0.87049 | 1 | 0.87049 | game-dev | MEDIA | 0.259009 | game-dev | 0.906535 | 1 | 0.906535 |
SketchUp/sketchup-ruby-debugger | 22,543 | ThirdParty/include/boost/spirit/home/support/utree/utree.hpp | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2010-2011 Bryce Lelbach
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_UTREE)
#define BOOST_SPIRIT_UTREE
#include <cstddef>
#include <algorithm>
#include <string>
#include <iostream>
#include <ios>
#include <sstream>
#include <typeinfo>
#include <boost/io/ios_state.hpp>
#include <boost/integer.hpp>
#include <boost/throw_exception.hpp>
#include <boost/assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/utility/result_of.hpp>
#include <boost/ref.hpp>
#include <boost/config.hpp>
#include <boost/spirit/home/support/utree/detail/utree_detail1.hpp>
#if defined(BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable: 4804)
# pragma warning(disable: 4805)
# pragma warning(disable: 4244)
#endif
namespace boost { namespace spirit
{
//[utree_exceptions
/*` All exceptions thrown by utree are derived from utree_exception. */
struct BOOST_SYMBOL_VISIBLE utree_exception : std::exception {};
/*`The `bad_type_exception` is thrown whenever somebody calls a member
function, which applies to certain stored utree_type's only, but this
precondition is violated as the `utree` instance holds some other type.
*/
struct bad_type_exception /*: utree_exception*/;
/*`The `empty_exception` is thrown whenever a precondition of a list
or range utree method is violated due to the list or range being empty.
*/
struct empty_exception /*: utree_exception*/;
//]
//[utree_types
/*`Each instance of an `utree` data structure can store exactly one of the
following data types at a time:
*/
struct utree_type
{
enum info
{
invalid_type, // the utree has not been initialized (it's
// default constructed)
nil_type, // nil is the sentinel (empty) utree type.
list_type, // A doubly linked list of utrees.
range_type, // A range of list::iterators.
reference_type, // A reference to another utree.
any_type, // A pointer or reference to any C++ type.
function_type, // A utree holding a stored_function<F> object,
// where F is an unary function object taking a
// utree as it's parameter and returning a
// utree.
// numeric atoms
bool_type, // An utree holding a boolean value
int_type, // An utree holding a integer (int) value
double_type, // An utree holding a floating point (double) value
// text atoms (utf8)
string_type, // An UTF-8 string
string_range_type, // A pair of iterators into an UTF-8 string
symbol_type, // An UTF-8 symbol name
binary_type // Arbitrary binary data
};
typedef boost::uint_t<sizeof(info)*8>::exact exact_integral_type;
typedef boost::uint_t<sizeof(info)*8>::fast fast_integral_type;
};
//]
// streaming operator for utree types - essential for diagnostics
inline std::ostream& operator<<(std::ostream& out, utree_type::info t)
{
boost::io::ios_all_saver saver(out);
switch (t) {
case utree_type::invalid_type: { out << "invalid"; break; }
case utree_type::nil_type: { out << "nil"; break; }
case utree_type::list_type: { out << "list"; break; }
case utree_type::range_type: { out << "range"; break; }
case utree_type::reference_type: { out << "reference"; break; }
case utree_type::any_type: { out << "any"; break; }
case utree_type::function_type: { out << "function"; break; }
case utree_type::bool_type: { out << "bool"; break; }
case utree_type::int_type: { out << "int"; break; }
case utree_type::double_type: { out << "double"; break; }
case utree_type::string_type: { out << "string"; break; }
case utree_type::string_range_type: { out << "string_range"; break; }
case utree_type::symbol_type: { out << "symbol"; break; }
case utree_type::binary_type: { out << "binary"; break; }
default: { out << "unknown"; break; }
}
out << std::hex << "[0x"
<< static_cast<utree_type::fast_integral_type>(t) << "]";
return out;
}
struct bad_type_exception : utree_exception
{
std::string msg;
bad_type_exception(char const* error, utree_type::info got)
: msg()
{
std::ostringstream oss;
oss << "utree: " << error
<< " (got utree type '" << got << "')";
msg = oss.str();
}
bad_type_exception(char const* error, utree_type::info got1,
utree_type::info got2)
: msg()
{
std::ostringstream oss;
oss << "utree: " << error
<< " (got utree types '" << got1 << "' and '" << got2 << "')";
msg = oss.str();
}
virtual ~bad_type_exception() BOOST_NOEXCEPT_OR_NOTHROW {}
virtual char const* what() const BOOST_NOEXCEPT_OR_NOTHROW
{ return msg.c_str(); }
};
struct empty_exception : utree_exception
{
char const* msg;
empty_exception(char const* error) : msg(error) {}
virtual ~empty_exception() BOOST_NOEXCEPT_OR_NOTHROW {}
virtual char const* what() const BOOST_NOEXCEPT_OR_NOTHROW
{ return msg; }
};
///////////////////////////////////////////////////////////////////////////
// A typed string with parametric Base storage. The storage can be any
// range or (stl container) of chars.
///////////////////////////////////////////////////////////////////////////
template <typename Base, utree_type::info type_>
struct basic_string : Base
{
static utree_type::info const type = type_;
basic_string()
: Base() {}
basic_string(Base const& base)
: Base(base) {}
template <typename Iterator>
basic_string(Iterator bits, std::size_t len)
: Base(bits, bits + len) {}
template <typename Iterator>
basic_string(Iterator first, Iterator last)
: Base(first, last) {}
basic_string& operator=(Base const& other)
{
Base::operator=(other);
return *this;
}
};
//[utree_strings
/*`The `utree` string types described below are used by the `utree` API
only. These are not used to store information in the `utree` itself.
Their purpose is to refer to different internal `utree` node types
only. For instance, creating a `utree` from a binary data type will
create a `binary_type` utree node (see above).
*/
/*`The binary data type can be represented either verbatim as a sequence
of bytes or as a pair of iterators into some other stored binary data
sequence. Use this string type to access/create a `binary_type` `utree`.
*/
typedef basic_string<
boost::iterator_range<char const*>, utree_type::binary_type
> binary_range_type;
typedef basic_string<
std::string, utree_type::binary_type
> binary_string_type;
/*`The UTF-8 string can be represented either verbatim as a sequence of
characters or as a pair of iterators into some other stored binary data
sequence. Use this string type to access/create a `string_type` `utree`.
*/
typedef basic_string<
boost::iterator_range<char const*>, utree_type::string_type
> utf8_string_range_type;
typedef basic_string<
std::string, utree_type::string_type
> utf8_string_type;
/*`The UTF-8 symbol can be represented either verbatim as a sequence of
characters or as a pair of iterators into some other stored binary data
sequence. Use this string type to access/create a `symbol_type` `utree`.
*/
typedef basic_string<
boost::iterator_range<char const*>, utree_type::symbol_type
> utf8_symbol_range_type;
typedef basic_string<
std::string, utree_type::symbol_type
> utf8_symbol_type;
//]
///////////////////////////////////////////////////////////////////////////
// Our function type
///////////////////////////////////////////////////////////////////////////
class utree;
//[utree_function_object_interface
struct function_base
{
virtual ~function_base() {}
virtual utree operator()(utree const& env) const = 0;
virtual utree operator()(utree& env) const = 0;
// Calling f.clone() must return a newly allocated function_base
// instance that is equal to f.
virtual function_base* clone() const = 0;
};
template <typename F>
struct stored_function : function_base
{
F f;
stored_function(F f = F());
virtual ~stored_function();
virtual utree operator()(utree const& env) const;
virtual utree operator()(utree& env) const;
virtual function_base* clone() const;
};
template <typename F>
struct referenced_function : function_base
{
F& f;
referenced_function(F& f);
virtual ~referenced_function();
virtual utree operator()(utree const& env) const;
virtual utree operator()(utree& env) const;
virtual function_base* clone() const;
};
//]
///////////////////////////////////////////////////////////////////////////
// Shallow tag. Instructs utree to hold an iterator_range
// as-is without deep copying the range.
///////////////////////////////////////////////////////////////////////////
struct shallow_tag {};
shallow_tag const shallow = {};
///////////////////////////////////////////////////////////////////////////
// A void* plus type_info
///////////////////////////////////////////////////////////////////////////
class any_ptr
{
public:
template <typename Ptr>
typename boost::disable_if<
boost::is_polymorphic<
typename boost::remove_pointer<Ptr>::type>,
Ptr>::type
get() const
{
if (*i == typeid(Ptr))
{
return static_cast<Ptr>(p);
}
boost::throw_exception(std::bad_cast());
}
template <typename T>
any_ptr(T* p)
: p(p), i(&typeid(T*))
{}
friend bool operator==(any_ptr const& a, any_ptr const& b)
{
return (a.p == b.p) && (*a.i == *b.i);
}
private:
// constructor is private
any_ptr(void* p, std::type_info const* i)
: p(p), i(i) {}
template <typename UTreeX, typename UTreeY>
friend struct detail::visit_impl;
friend class utree;
void* p;
std::type_info const* i;
};
//[utree
class utree {
public:
///////////////////////////////////////////////////////////////////////
// The invalid type
struct invalid_type {};
///////////////////////////////////////////////////////////////////////
// The nil type
struct nil_type {};
///////////////////////////////////////////////////////////////////////
// The list type, this can be used to initialize an utree to hold an
// empty list
struct list_type;
//[utree_container_types
typedef utree value_type;
typedef utree& reference;
typedef utree const& const_reference;
typedef std::ptrdiff_t difference_type;
typedef std::size_t size_type;
typedef detail::list::node_iterator<utree> iterator;
typedef detail::list::node_iterator<utree const> const_iterator;
//]
typedef detail::list::node_iterator<boost::reference_wrapper<utree> >
ref_iterator;
typedef boost::iterator_range<iterator> range;
typedef boost::iterator_range<const_iterator> const_range;
// dtor
~utree();
////////////////////////////////////////////////////////////////////////
//[utree_initialization
/*`A `utree` can be constructed or initialized from a wide range of
data types, allowing to create `utree` instances for every
possible node type (see the description of `utree_type::info` above).
For this reason it exposes a constructor and an assignment operator
for each of the allowed node types as shown below. All constructors
are non-explicit on purpose, allowing to use an utree instance as
the attribute to almost any Qi parser.
*/
// This constructs an `invalid_type` node. When used in places
// where a boost::optional is expected (i.e. as an attribute for the
// optional component), this represents the 'empty' state.
utree(invalid_type = invalid_type());
// This initializes a `nil_type` node, which represents a valid,
// 'initialized empty' utree (different from invalid_type!).
utree(nil_type);
reference operator=(nil_type);
// This initializes a `boolean_type` node, which can hold 'true' or
// 'false' only.
explicit utree(bool);
reference operator=(bool);
// This initializes an `integer_type` node, which can hold arbitrary
// integers. For convenience these functions are overloaded for signed
// and unsigned integer types.
utree(unsigned int);
utree(int);
reference operator=(unsigned int);
reference operator=(int);
// This initializes a `double_type` node, which can hold arbitrary
// floating point (double) values.
utree(double);
reference operator=(double);
// This initializes a `string_type` node, which can hold a narrow
// character sequence (usually an UTF-8 string).
utree(char);
utree(char const*);
utree(char const*, std::size_t);
utree(std::string const&);
reference operator=(char);
reference operator=(char const*);
reference operator=(std::string const&);
// This constructs a `string_range_type` node, which does not copy the
// data but stores the iterator range to the character sequence the
// range has been initialized from.
utree(utf8_string_range_type const&, shallow_tag);
// This initializes a `reference_type` node, which holds a reference to
// another utree node. All operations on such a node are automatically
// forwarded to the referenced utree instance.
utree(boost::reference_wrapper<utree>);
reference operator=(boost::reference_wrapper<utree>);
// This initializes an `any_type` node, which can hold a pointer to an
// instance of any type together with the typeid of that type. When
// accessing that pointer the typeid will be checked, causing a
// std::bad_cast to be thrown if the typeids do not match.
utree(any_ptr const&);
reference operator=(any_ptr const&);
// This initializes a `range_type` node, which holds an utree list node
// the elements of which are copy constructed (assigned) from the
// elements referenced by the given range of iterators.
template <class Iterator>
utree(boost::iterator_range<Iterator>);
template <class Iterator>
reference operator=(boost::iterator_range<Iterator>);
// This initializes a `function_type` node from a polymorphic function
// object pointer (takes ownership) or reference.
utree(function_base const&);
reference operator=(function_base const&);
utree(function_base*);
reference operator=(function_base*);
// This initializes either a `string_type`, a `symbol_type`, or a
// `binary_type` node (depending on the template parameter `type_`),
// which will hold the corresponding narrow character sequence (usually
// an UTF-8 string).
template <class Base, utree_type::info type_>
utree(basic_string<Base, type_> const&);
template <class Base, utree_type::info type_>
reference operator=(basic_string<Base, type_> const&);
//]
// copy
utree(const_reference);
reference operator=(const_reference);
// range
utree(range, shallow_tag);
utree(const_range, shallow_tag);
// assign dispatch
template <class Iterator>
void assign(Iterator, Iterator);
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// function object visitation interface
// single dispatch
template <class F>
typename boost::result_of<F(utree const&)>::type
static visit(utree const&, F);
template <class F>
typename boost::result_of<F(utree&)>::type
static visit(utree&, F);
// double dispatch
template <class F>
typename boost::result_of<F(utree const&, utree const&)>::type
static visit(utree const&, utree const&, F);
template <class F>
typename boost::result_of<F(utree&, utree const&)>::type
static visit(utree&, utree const&, F);
template <class F>
typename boost::result_of<F(utree const&, utree&)>::type
static visit(utree const&, utree&, F);
template <class F>
typename boost::result_of<F(utree&, utree&)>::type
static visit(utree&, utree&, F);
////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//[utree_container_functions
// STL Container interface
// insertion
template <class T>
void push_back(T const&);
template <class T>
void push_front(T const&);
template <class T>
iterator insert(iterator, T const&);
template <class T>
void insert(iterator, std::size_t, T const&);
template <class Iterator>
void insert(iterator, Iterator, Iterator);
// erasure
void pop_front();
void pop_back();
iterator erase(iterator);
iterator erase(iterator, iterator);
// front access
reference front();
const_reference front() const;
iterator begin();
const_iterator begin() const;
ref_iterator ref_begin();
// back access
reference back();
const_reference back() const;
iterator end();
const_iterator end() const;
ref_iterator ref_end();
//]
// This clears the utree instance and resets its type to `invalid_type`
void clear();
void swap(utree&);
bool empty() const;
size_type size() const;
/*`[warning `size()` has O(n) complexity on `utree` ranges. On utree
lists, it has O(1) complexity.]`*/
////////////////////////////////////////////////////////////////////////
//[utree_variant_functions
// return the data type (`utree_type::info`) of the currently stored
// data item
utree_type::info which() const;
// access the currently stored data in a type safe manner, this will
// throw a `std::bad_cast()` if the currently stored data item is not
// default convertible to `T`.
template <class T>
T get() const;
//]
reference deref();
const_reference deref() const;
short tag() const;
void tag(short);
utree eval(utree const&) const;
utree eval(utree&) const;
utree operator() (utree const&) const;
utree operator() (utree&) const;
//<-
protected:
void ensure_list_type(char const* failed_in = "ensure_list_type()");
private:
typedef utree_type type;
template <class UTreeX, class UTreeY>
friend struct detail::visit_impl;
friend struct detail::index_impl;
type::info get_type() const;
void set_type(type::info);
void free();
void copy(const_reference);
union {
detail::fast_string s;
detail::list l;
detail::range r;
detail::string_range sr;
detail::void_ptr v;
bool b;
int i;
double d;
utree* p;
function_base* pf;
};
//->
};
//]
//[utree_tuple_interface
/*<-*/inline/*->*/
utree::reference get(utree::reference, utree::size_type);
/*<-*/inline/*->*/
utree::const_reference get(utree::const_reference, utree::size_type);
/*`[warning `get()` has O(n) complexity.]`*/
//]
struct utree::list_type : utree
{
using utree::operator=;
list_type() : utree() { ensure_list_type("list_type()"); }
template <typename T0>
list_type(T0 t0) : utree(t0) {}
template <typename T0, typename T1>
list_type(T0 t0, T1 t1) : utree(t0, t1) {}
};
///////////////////////////////////////////////////////////////////////////
// predefined instances for singular types
utree::invalid_type const invalid = {};
utree::nil_type const nil = {};
utree::list_type const empty_list = utree::list_type();
}}
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif
| 0 | 0.992153 | 1 | 0.992153 | game-dev | MEDIA | 0.310928 | game-dev | 0.96892 | 1 | 0.96892 |
mixandjam/AC-Dialogue | 38,709 | Assets/DOTween/Modules/DOTweenModuleUI.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
#if true && (UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER) // MODULE_MARKER
using System;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening.Core;
using DG.Tweening.Core.Enums;
using DG.Tweening.Plugins.Options;
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenModuleUI
{
#region Shortcuts
#region CanvasGroup
/// <summary>Tweens a CanvasGroup's alpha color to the given value.
/// Also stores the canvasGroup as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOFade(this CanvasGroup target, float endValue, float duration)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.alpha, x => target.alpha = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region Graphic
/// <summary>Tweens an Graphic's color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Graphic target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Graphic's alpha color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Graphic target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region Image
/// <summary>Tweens an Image's color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Image target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's alpha color to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Image target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's fillAmount to the given value.
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param>
public static TweenerCore<float, float, FloatOptions> DOFillAmount(this Image target, float endValue, float duration)
{
if (endValue > 1) endValue = 1;
else if (endValue < 0) endValue = 0;
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.fillAmount, x => target.fillAmount = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens an Image's colors using the given gradient
/// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener).
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param>
public static Sequence DOGradientColor(this Image target, Gradient gradient, float duration)
{
Sequence s = DOTween.Sequence();
GradientColorKey[] colors = gradient.colorKeys;
int len = colors.Length;
for (int i = 0; i < len; ++i) {
GradientColorKey c = colors[i];
if (i == 0 && c.time <= 0) {
target.color = c.color;
continue;
}
float colorDuration = i == len - 1
? duration - s.Duration(false) // Verifies that total duration is correct
: duration * (i == 0 ? c.time : c.time - colors[i - 1].time);
s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear));
}
s.SetTarget(target);
return s;
}
#endregion
#region LayoutElement
/// <summary>Tweens an LayoutElement's flexibleWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOFlexibleSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.flexibleWidth, target.flexibleHeight), x => {
target.flexibleWidth = x.x;
target.flexibleHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens an LayoutElement's minWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOMinSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.minWidth, target.minHeight), x => {
target.minWidth = x.x;
target.minHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens an LayoutElement's preferredWidth/Height to the given value.
/// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPreferredSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.preferredWidth, target.preferredHeight), x => {
target.preferredWidth = x.x;
target.preferredHeight = x.y;
}, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
#endregion
#region Outline
/// <summary>Tweens a Outline's effectColor to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Outline target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.effectColor, x => target.effectColor = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Outline's effectColor alpha to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Outline target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.effectColor, x => target.effectColor = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Outline's effectDistance to the given value.
/// Also stores the Outline as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOScale(this Outline target, Vector2 endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.effectDistance, x => target.effectDistance = x, endValue, duration);
t.SetTarget(target);
return t;
}
#endregion
#region RectTransform
/// <summary>Tweens a RectTransform's anchoredPosition to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPos(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosX(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue, 0), duration);
t.SetOptions(AxisConstraint.X, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosY(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, endValue), duration);
t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3D(this RectTransform target, Vector3 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DX(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(endValue, 0, 0), duration);
t.SetOptions(AxisConstraint.X, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DY(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, endValue, 0), duration);
t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchoredPosition3D Z to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DZ(this RectTransform target, float endValue, float duration, bool snapping = false)
{
TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, 0, endValue), duration);
t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchorMax to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMax(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMax, x => target.anchorMax = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's anchorMin to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMin(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMin, x => target.anchorMin = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivot(this RectTransform target, Vector2 endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot X to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotX(this RectTransform target, float endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(endValue, 0), duration);
t.SetOptions(AxisConstraint.X).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's pivot Y to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotY(this RectTransform target, float endValue, float duration)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(0, endValue), duration);
t.SetOptions(AxisConstraint.Y).SetTarget(target);
return t;
}
/// <summary>Tweens a RectTransform's sizeDelta to the given value.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<Vector2, Vector2, VectorOptions> DOSizeDelta(this RectTransform target, Vector2 endValue, float duration, bool snapping = false)
{
TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.sizeDelta, x => target.sizeDelta = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
/// <summary>Punches a RectTransform's anchoredPosition towards the given direction and then back to the starting one
/// as if it was connected to the starting position via an elastic.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="punch">The direction and strength of the punch (added to the RectTransform's current position)</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="vibrato">Indicates how much will the punch vibrate</param>
/// <param name="elasticity">Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards.
/// 1 creates a full oscillation between the punch direction and the opposite direction,
/// while 0 oscillates only between the punch and the start position</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOPunchAnchorPos(this RectTransform target, Vector2 punch, float duration, int vibrato = 10, float elasticity = 1, bool snapping = false)
{
return DOTween.Punch(() => target.anchoredPosition, x => target.anchoredPosition = x, punch, duration, vibrato, elasticity)
.SetTarget(target).SetOptions(snapping);
}
/// <summary>Shakes a RectTransform's anchoredPosition with the given values.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="strength">The shake strength</param>
/// <param name="vibrato">Indicates how much will the shake vibrate</param>
/// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware).
/// Setting it to 0 will shake along a single direction.</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
/// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param>
public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, float strength = 100, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true)
{
return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, true, fadeOut)
.SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping);
}
/// <summary>Shakes a RectTransform's anchoredPosition with the given values.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="strength">The shake strength on each axis</param>
/// <param name="vibrato">Indicates how much will the shake vibrate</param>
/// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware).
/// Setting it to 0 will shake along a single direction.</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
/// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param>
public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, Vector2 strength, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true)
{
return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, fadeOut)
.SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping);
}
#region Special
/// <summary>Tweens a RectTransform's anchoredPosition to the given value, while also applying a jump effect along the Y axis.
/// Returns a Sequence instead of a Tweener.
/// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param>
/// <param name="jumpPower">Power of the jump (the max height of the jump is represented by this plus the final Y offset)</param>
/// <param name="numJumps">Total number of jumps</param>
/// <param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Sequence DOJumpAnchorPos(this RectTransform target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false)
{
if (numJumps < 1) numJumps = 1;
float startPosY = 0;
float offsetY = -1;
bool offsetYSet = false;
// Separate Y Tween so we can elaborate elapsedPercentage on that insted of on the Sequence
// (in case users add a delay or other elements to the Sequence)
Sequence s = DOTween.Sequence();
Tween yTween = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, jumpPower), duration / (numJumps * 2))
.SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative()
.SetLoops(numJumps * 2, LoopType.Yoyo)
.OnStart(()=> startPosY = target.anchoredPosition.y);
s.Append(DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue.x, 0), duration)
.SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear)
).Join(yTween)
.SetTarget(target).SetEase(DOTween.defaultEaseType);
s.OnUpdate(() => {
if (!offsetYSet) {
offsetYSet = true;
offsetY = s.isRelative ? endValue.y : endValue.y - startPosY;
}
Vector2 pos = target.anchoredPosition;
pos.y += DOVirtual.EasedValue(0, offsetY, s.ElapsedDirectionalPercentage(), Ease.OutQuad);
target.anchoredPosition = pos;
});
return s;
}
#endregion
#endregion
#region ScrollRect
/// <summary>Tweens a ScrollRect's horizontal/verticalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DONormalizedPos(this ScrollRect target, Vector2 endValue, float duration, bool snapping = false)
{
return DOTween.To(() => new Vector2(target.horizontalNormalizedPosition, target.verticalNormalizedPosition),
x => {
target.horizontalNormalizedPosition = x.x;
target.verticalNormalizedPosition = x.y;
}, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
/// <summary>Tweens a ScrollRect's horizontalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOHorizontalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false)
{
return DOTween.To(() => target.horizontalNormalizedPosition, x => target.horizontalNormalizedPosition = x, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
/// <summary>Tweens a ScrollRect's verticalNormalizedPosition to the given value.
/// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOVerticalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false)
{
return DOTween.To(() => target.verticalNormalizedPosition, x => target.verticalNormalizedPosition = x, endValue, duration)
.SetOptions(snapping).SetTarget(target);
}
#endregion
#region Slider
/// <summary>Tweens a Slider's value to the given value.
/// Also stores the Slider as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static TweenerCore<float, float, FloatOptions> DOValue(this Slider target, float endValue, float duration, bool snapping = false)
{
TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.value, x => target.value = x, endValue, duration);
t.SetOptions(snapping).SetTarget(target);
return t;
}
#endregion
#region Text
/// <summary>Tweens a Text's color to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this Text target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Text's alpha color to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this Text target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Text's text to the given value.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end string to tween to</param><param name="duration">The duration of the tween</param>
/// <param name="richTextEnabled">If TRUE (default), rich text will be interpreted correctly while animated,
/// otherwise all tags will be considered as normal text</param>
/// <param name="scrambleMode">The type of scramble mode to use, if any</param>
/// <param name="scrambleChars">A string containing the characters to use for scrambling.
/// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters.
/// Leave it to NULL (default) to use default ones</param>
public static TweenerCore<string, string, StringOptions> DOText(this Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null)
{
if (endValue == null) {
if (Debugger.logPriority > 0) Debugger.LogWarning("You can't pass a NULL string to DOText: an empty string will be used instead to avoid errors");
endValue = "";
}
TweenerCore<string, string, StringOptions> t = DOTween.To(() => target.text, x => target.text = x, endValue, duration);
t.SetOptions(richTextEnabled, scrambleMode, scrambleChars)
.SetTarget(target);
return t;
}
#endregion
#region Blendables
#region Graphic
/// <summary>Tweens a Graphic's color to the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Graphic as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Graphic target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#region Image
/// <summary>Tweens a Image's color to the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Image as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Image target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#region Text
/// <summary>Tweens a Text's color BY the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the Text as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this Text target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#endregion
#endregion
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
// ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
public static class Utils
{
/// <summary>
/// Converts the anchoredPosition of the first RectTransform to the second RectTransform,
/// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition
/// </summary>
public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to)
{
Vector2 localPoint;
Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin);
Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position);
screenP += fromPivotDerivedOffset;
RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint);
Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin);
return to.anchoredPosition + localPoint - pivotDerivedOffset;
}
}
}
}
#endif
| 0 | 0.924686 | 1 | 0.924686 | game-dev | MEDIA | 0.427239 | game-dev | 0.968405 | 1 | 0.968405 |
Joshua-F/osrs-dumps | 14,004 | script/[proc,league_tasks_draw_list].cs2 | // 3204
[proc,league_tasks_draw_list](int $int0, component $component1, component $component2, component $component3, component $component4, component $component5, component $component6, component $component7, component $component8, component $component9, component $component10, component $component11, component $component12, component $component13, component $component14, component $component15, component $component16, component $component17, component $component18)
def_int $int19 = %league_tasks_scroll_pos;
if ($int19 = -1) {
$int19 = if_getscrolly($component1);
}
if_setonresize("league_tasks_draw_list($int0, $component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, $component13, $component14, $component15, $component16, $component17, $component18)", league_tasks:infinity);
if_setonvartransmit("league_tasks_transmit($int0, $component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, $component13, $component14, $component15, $component16, $component17, $component18){league_points_completed}", league_tasks:infinity);
cc_deleteall($component2);
cc_deleteall($component3);
cc_deleteall($component4);
cc_deleteall($component5);
cc_deleteall($component6);
cc_deleteall($component7);
cc_deleteall($component8);
cc_deleteall($component9);
cc_deleteall($component12);
cc_deleteall($component13);
def_int $int20 = if_getwidth(league_tasks:infinity);
def_int $int21 = ~script1912;
def_int $int22 = calc(if_getheight(league_tasks:infinity) - $int21);
def_int $int23 = 0;
def_boolean $boolean24 = ~on_mobile;
if (~script7925 = false | %league_tasks_has_been_moved = 0) {
$int23 = 1;
}
def_enum $enum25 = ~toplevel_getcomponents;
def_component $component26 = enum(component, component, $enum25, toplevel_osrs_stretch:mainmodal);
def_int $int27 = 512;
def_int $int28 = 334;
def_int $int29 = if_getx($component26);
def_int $int30 = if_gety($component26);
if_sethide(false, league_tasks:universe);
if_sethide(true, league_tasks:resize_preview);
if ($int23 = 0) {
$int27 = max(350, min(%league_tasks_width, $int20));
$int28 = max(300, min(%league_tasks_height, $int22));
$int29 = max(0, min(%league_tasks_x, calc($int20 - $int27)));
$int30 = max($int21, min(%league_tasks_y, calc($int21 + $int22 - $int28)));
}
if ($boolean24 = false) {
if_setposition($int29, $int30, ^setpos_abs_left, ^setpos_abs_top, league_tasks:universe);
if_setsize($int27, $int28, ^setsize_abs, ^setsize_abs, league_tasks:universe);
}
~script1785(league_tasks:content_outer);
if ($int23 = 0) {
if (cc_find(league_tasks:infinity, 0) = ^true) {
cc_setsize(calc($int27 - 6 * 2), calc(if_gety(league_tasks:content_outer) - 2 * 6), ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + 6), calc($int30 + 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 1) = ^true) {
cc_setsize(calc($int27 - 6 * 2), 6, ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + 6), calc($int30 + $int28 - 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 2) = ^true) {
cc_setsize(6, calc($int28 - 6 * 2), ^setsize_abs, ^setsize_abs);
cc_setposition($int29, calc($int30 + 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 3) = ^true) {
cc_setsize(6, calc($int28 - 6 * 2), ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + $int27 - 6), calc($int30 + 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 4) = ^true) {
cc_setsize(6, 6, ^setsize_abs, ^setsize_abs);
cc_setposition($int29, $int30, ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 5) = ^true) {
cc_setsize(6, 6, ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + $int27 - 6), $int30, ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 6) = ^true) {
cc_setsize(6, 6, ^setsize_abs, ^setsize_abs);
cc_setposition($int29, calc($int30 + $int28 - 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 7) = ^true) {
cc_setsize(6, 6, ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + $int27 - 6), calc($int30 + $int28 - 6), ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
if (cc_find(league_tasks:infinity, 8) = ^true) {
cc_setsize(calc($int27 - 28 - 6 * 2), 6, ^setsize_abs, ^setsize_abs);
cc_setposition(calc($int29 + 28 + 6), $int30, ^setpos_abs_left, ^setpos_abs_top);
~script2438($int21);
}
}
def_int $int31 = 0;
def_struct $struct32 = enum(int, struct, enum_2670, %league_type);
if ($struct32 = null) {
return;
}
def_int $rgb33 = struct_param($struct32, param_1027);
def_enum $enum34 = struct_param($struct32, param_868);
def_int $int35 = enum_getoutputcount($enum34);
~league_points_progress_bar($component15, $component16, false, false);
~searchbar_create($component17, $component18);
~script2441($component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, $component13, $component14, $component15, $component16, $component17, $component18, $rgb33, 0);
if (~in_league_tutorial = false) {
~leagues_menu_button($component12, $int31, $component13, $component14);
}
~league_create_dropdown($component12, $component13, $component14, $int31, 1);
if ($int23 = 1) {
~steelborder(league_tasks:frame, "League Tasks <col=ffffff><tostring($int31)>/<tostring($int35)></col>", 1);
} else {
~steelborder(league_tasks:frame, "League Tasks <col=ffffff><tostring($int31)>/<tostring($int35)></col>", 3);
}
if (cc_find(league_tasks:frame, 1) = ^true) {
cc_setcolour($rgb33);
}
def_int $int36 = 0;
def_int $int37 = 0;
def_struct $struct38 = null;
def_int $int39 = 0;
def_int $int40 = -1;
def_int $int41 = -1;
def_string $string0 = null;
def_string $string1 = null;
def_int $int42 = -1;
def_int $int43 = -1;
def_int $int44 = -1;
def_int $int45 = -1;
def_int $int46 = 0;
def_string $string2 = %league_tasks_search_string;
def_int $int47 = string_length(~script7124($string2));
def_int $int48 = 1;
if (%league_task_filter_tier = 0 & %league_task_filter_type = 0 & %league_task_filter_area = 0 & $int47 <= 1) {
$int48 = 0;
}
def_boolean $boolean49 = true;
while ($int36 < $int35) {
$struct38 = enum(int, struct, $enum34, $int36);
$int40 = ~league_task_is_completed($struct38);
$int41 = struct_param($struct38, param_2044);
$string0 = struct_param($struct38, param_874);
$string1 = struct_param($struct38, param_875);
$int42 = enum(int, int, enum_2671, $int41);
$int43 = struct_param($struct38, param_1016);
$int44 = struct_param($struct38, param_1017);
if ($int48 = 1) {
$boolean49 = ~league_task_display($int41, $int40, $int43, $int44, struct_param($struct38, param_1018), $string0, $string1, $string2, $int47);
} else if (%league_task_filter_completed ! 0 & calc(%league_task_filter_completed - 1) ! $int40) {
$boolean49 = false;
} else {
$boolean49 = true;
}
if ($boolean49 = true) {
cc_create($component2, ^iftype_rectangle, $int31);
cc_setposition(0, $int39, ^setpos_abs_centre, ^setpos_abs_top);
cc_setcolour(^white);
cc_setfill(true);
if ($int36 = $int0) {
$int45 = paraheight("Description: <$string1>.", calc(if_getwidth($component2) - 10), p11_full);
cc_setsize(0, calc(40 + (10 * $int45 + 25)), ^setsize_minus, ^setsize_abs);
cc_settrans(210);
if ($boolean24 = false) {
cc_setonmouserepeat("league_task_hover(event_comsubid, $component2, $component8, 210, \"open_buttons_small,3\")");
if (calc($int31 % 2) = 1) {
cc_setonmouseleave("league_task_hover(event_comsubid, $component2, $component8, 230, \"open_buttons_small,2\")");
} else {
cc_setonmouseleave("league_task_hover(event_comsubid, $component2, $component8, 245, \"open_buttons_small,2\")");
}
}
cc_setop(1, "Collapse");
cc_setonop("script7700(-1, $component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, $component13, $component14, $component15, $component16, $component17, $component18)");
cc_setopbase("<col=ff981f><$string0></col>");
cc_create($component5, ^iftype_text, 0);
cc_settext("Type: <col=ffffff><enum(int, string, enum_3411, $int43)></col>");
cc_setsize(51, 11, ^setsize_minus, ^setsize_abs);
cc_setposition(5, calc($int39 + 40), ^setpos_abs_left, ^setpos_abs_top);
cc_settextfont(p11_full);
cc_settextalign(^settextalign_left, ^settextalign_centre, 0);
cc_settextshadow(true);
cc_setcolour($rgb33);
cc_create($component6, ^iftype_text, 0);
cc_settext("Area: <col=ffffff><enum(int, string, enum_3412, $int44)></col>");
cc_setsize(51, 11, ^setsize_minus, ^setsize_abs);
cc_setposition(104, calc($int39 + 40), ^setpos_abs_left, ^setpos_abs_top);
cc_settextfont(p11_full);
cc_settextalign(^settextalign_left, ^settextalign_centre, 0);
cc_settextshadow(true);
cc_setcolour($rgb33);
cc_create($component7, ^iftype_text, 0);
cc_settext("Description: <col=ffffff><$string1>.</col>");
cc_setsize(10, calc(10 * $int45), ^setsize_minus, ^setsize_abs);
cc_setposition(5, calc($int39 + 59), ^setpos_abs_left, ^setpos_abs_top);
cc_settextfont(p11_full);
cc_settextalign(^settextalign_left, ^settextalign_centre, 0);
cc_settextshadow(true);
cc_setcolour($rgb33);
cc_create($component8, ^iftype_graphic, $int31);
cc_setgraphic("open_buttons_small,2");
} else {
cc_setsize(0, 40, ^setsize_minus, ^setsize_abs);
if ($boolean24 = false) {
cc_setonmouserepeat("league_task_hover(event_comsubid, $component2, $component8, 210, \"open_buttons_small,1\")");
if (calc($int31 % 2) = 1) {
cc_setonmouseleave("league_task_hover(event_comsubid, $component2, $component8, 230, \"open_buttons_small,0\")");
} else {
cc_setonmouseleave("league_task_hover(event_comsubid, $component2, $component8, 245, \"open_buttons_small,0\")");
}
}
if (calc($int31 % 2) = 1) {
cc_settrans(230);
} else {
cc_settrans(245);
}
cc_setop(1, "Expand");
cc_setonop("script7700($int36, $component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, $component13, $component14, $component15, $component16, $component17, $component18)");
cc_setopbase("<col=ff981f><$string0></col>");
cc_create($component8, ^iftype_graphic, $int31);
cc_setgraphic("open_buttons_small,0");
}
cc_setsize(18, 18, ^setsize_abs, ^setsize_abs);
cc_setposition(5, calc($int39 + 11), ^setpos_abs_left, ^setpos_abs_top);
cc_create($component9, ^iftype_graphic, $int31);
cc_setsize(18, 18, ^setsize_abs, ^setsize_abs);
cc_setposition(28, calc($int39 + 11), ^setpos_abs_left, ^setpos_abs_top);
cc_setgraphic(enum(int, graphic, enum_2674, $int41));
cc_create($component3, ^iftype_text, $int31);
cc_settext($string0);
cc_setsize(51, 16, ^setsize_minus, ^setsize_abs);
cc_setposition(51, calc($int39 + 4), ^setpos_abs_left, ^setpos_abs_top);
cc_settextfont(p12_full);
cc_settextalign(^settextalign_left, ^settextalign_centre, 0);
cc_settextshadow(true);
if ($int40 = 1) {
cc_setcolour($rgb33);
$int46 = calc($int46 + 1);
} else {
cc_setcolour(0x9f9f9f);
}
cc_create($component4, ^iftype_text, $int31);
cc_settext("Reward: <col=ffffff><tostring($int42)> League Points</col>");
cc_setsize(51, 11, ^setsize_minus, ^setsize_abs);
cc_setposition(51, calc($int39 + 22), ^setpos_abs_left, ^setpos_abs_top);
cc_settextfont(p11_full);
cc_settextalign(^settextalign_left, ^settextalign_centre, 0);
cc_settextshadow(true);
cc_setcolour($rgb33);
if ($int36 = $int0) {
$int39 = calc($int39 + $int45 * 10 + 65);
} else {
$int39 = calc($int39 + 40);
}
$int31 = calc($int31 + 1);
}
$int36 = calc($int36 + 1);
}
if ($int39 > if_getheight($component1)) {
if_setscrollsize(0, $int39, $component1);
} else {
if_setscrollsize(0, 0, $component1);
}
if_setscrollpos(0, $int19, $component1);
cc_deleteall($component11);
~scrollbar_vertical($component11, $component1, "scrollbar_dragger_v2,3", "scrollbar_dragger_v2,0", "scrollbar_dragger_v2,1", "scrollbar_dragger_v2,2", "scrollbar_v2,0", "scrollbar_v2,1");
~scrollbar_resize($component11, $component1, $int19);
if ($int31 = 0 & %league_tasks_is_searching = 0) {
if_sethide(false, $component10);
} else {
if_sethide(true, $component10);
}
if (cc_find(league_tasks:frame, 1) = ^true) {
cc_settext("League Tasks <col=ffffff><tostring($int46)>/<tostring($int31)></col>");
}
| 0 | 0.904229 | 1 | 0.904229 | game-dev | MEDIA | 0.448144 | game-dev | 0.83274 | 1 | 0.83274 |
SwitchGDX/switch-gdx | 2,054 | switch-gdx/res/switchgdx/bullet/extras/InverseDynamics/SimpleTreeCreator.cpp | #include "SimpleTreeCreator.hpp"
#include <cstdio>
namespace btInverseDynamics {
/// minimal "tree" (chain)
SimpleTreeCreator::SimpleTreeCreator(int dim) : m_num_bodies(dim) {
m_mass = 1.0;
m_body_T_parent_ref(0, 0) = 1;
m_body_T_parent_ref(0, 1) = 0;
m_body_T_parent_ref(0, 2) = 0;
m_body_T_parent_ref(1, 0) = 0;
m_body_T_parent_ref(1, 1) = 1;
m_body_T_parent_ref(1, 2) = 0;
m_body_T_parent_ref(2, 0) = 0;
m_body_T_parent_ref(2, 1) = 0;
m_body_T_parent_ref(2, 2) = 1;
m_parent_r_parent_body_ref(0) = 1.0;
m_parent_r_parent_body_ref(1) = 0.0;
m_parent_r_parent_body_ref(2) = 0.0;
m_body_r_body_com(0) = 0.5;
m_body_r_body_com(1) = 0.0;
m_body_r_body_com(2) = 0.0;
m_body_I_body(0, 0) = 1;
m_body_I_body(0, 1) = 0;
m_body_I_body(0, 2) = 0;
m_body_I_body(1, 0) = 0;
m_body_I_body(1, 1) = 1;
m_body_I_body(1, 2) = 0;
m_body_I_body(2, 0) = 0;
m_body_I_body(2, 1) = 0;
m_body_I_body(2, 2) = 1;
m_axis(0) = 0;
m_axis(1) = 0;
m_axis(2) = 1;
}
int SimpleTreeCreator::getNumBodies(int* num_bodies) const {
*num_bodies = m_num_bodies;
return 0;
}
int SimpleTreeCreator::getBody(const int body_index, int* parent_index, JointType* joint_type,
vec3* parent_r_parent_body_ref, mat33* body_T_parent_ref,
vec3* body_axis_of_motion, idScalar* mass, vec3* body_r_body_com,
mat33* body_I_body, int* user_int, void** user_ptr) const {
*parent_index = body_index - 1;
if (body_index % 2) {
*joint_type = PRISMATIC;
} else {
*joint_type = REVOLUTE;
}
*parent_r_parent_body_ref = m_parent_r_parent_body_ref;
if (0 == body_index) {
(*parent_r_parent_body_ref)(2) = 1.0;
}
*body_T_parent_ref = m_body_T_parent_ref;
*body_axis_of_motion = m_axis;
*mass = m_mass;
*body_r_body_com = m_body_r_body_com;
*body_I_body = m_body_I_body;
*user_int = 0;
*user_ptr = 0;
return 0;
}
}
| 0 | 0.770748 | 1 | 0.770748 | game-dev | MEDIA | 0.851143 | game-dev | 0.644386 | 1 | 0.644386 |
InfernumTeam/InfernumMode | 15,082 | Content/BehaviorOverrides/BossAIs/WallOfFlesh/WallOfFleshMouthBehaviorOverride.cs | using System;
using System.Collections.Generic;
using CalamityMod;
using CalamityMod.Events;
using InfernumMode.Core.GlobalInstances.Systems;
using InfernumMode.Core.OverridingSystem;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace InfernumMode.Content.BehaviorOverrides.BossAIs.WallOfFlesh
{
public class WallOfFleshMouthBehaviorOverride : NPCBehaviorOverride
{
public override int NPCOverrideType => NPCID.WallofFlesh;
public const float Phase2LifeRatio = 0.45f;
public static int EyeLaserDamage => 100;
public static int FleshTentacleDamage => 105;
public static int FireBeamDamage => 185;
public override float[] PhaseLifeRatioThresholds =>
[
Phase2LifeRatio
];
#region AI
public override bool PreAI(NPC npc)
{
int totalAttachedEyes = 0;
for (int i = 0; i < Main.maxNPCs; i++)
{
if (!Main.npc[i].active || Main.npc[i].type != NPCID.WallofFleshEye || Main.npc[i].Infernum().ExtraAI[2] != 0f)
continue;
totalAttachedEyes++;
}
npc.Calamity().DR = Lerp(0.225f, 0.725f, Utils.GetLerpValue(0f, 3f, totalAttachedEyes, true));
ref float initialized01Flag = ref npc.localAI[0];
ref float attackTimer = ref npc.ai[3];
// Eye of Night debuffs.
npc.buffImmune[BuffID.CursedInferno] = true;
// Select a new target if an old one was lost.
npc.TargetClosestIfTargetIsInvalid();
Player target = Main.player[npc.target];
float lifeRatio = Clamp(npc.life / (float)npc.lifeMax, 0f, 1f);
// If the target isn't in the underworld check to see if anyone else is. If not, despawn.
if (target.Center.Y <= (Main.maxTilesY - 300f) * 16f)
{
int newTarget = -1;
for (int i = 0; i < Main.maxPlayers; i++)
{
if (!Main.player[i].active || Main.player[i].dead)
continue;
if (Main.player[i].Center.Y > (Main.maxTilesY - 300f) * 16f)
{
newTarget = i;
break;
}
}
if (newTarget >= 0f)
{
npc.target = newTarget;
npc.netUpdate = true;
}
else
npc.active = false;
}
Main.wofNPCIndex = npc.whoAmI;
if (npc.Center.X <= 160f || npc.Center.X >= Main.maxTilesX * 16f - 160f)
{
npc.active = false;
npc.netUpdate = true;
}
if (initialized01Flag == 0f)
{
Main.wofDrawAreaBottom = -1;
Main.wofDrawAreaTop = -1;
SetEyePositions(npc);
SummonEyes(npc);
initialized01Flag = 1f;
}
// Despawn.
if (target.dead)
{
npc.localAI[1] += 1f / 18f;
if (npc.localAI[1] >= 1f)
{
SoundEngine.PlaySound(SoundID.NPCDeath10, npc.position);
npc.life = 0;
npc.active = false;
if (Main.netMode != NetmodeID.MultiplayerClient)
NetMessage.SendData(MessageID.DamageNPC, -1, -1, null, npc.whoAmI, -1f);
return false;
}
}
else
npc.localAI[1] = Clamp(npc.localAI[1] - 1f / 30f, 0f, 1f);
SetEyePositions(npc);
PerformMouthMotion(npc, lifeRatio);
AngerEffects(npc, target);
DetermineMouthRotation(npc, target);
attackTimer++;
// Have high DR when eyes are attached.
npc.Calamity().DR = totalAttachedEyes > 0 ? 0.98f : 0.3f;
npc.chaseable = totalAttachedEyes <= 0;
int beamShootRate = 380;
if (totalAttachedEyes <= 0 && attackTimer % beamShootRate == beamShootRate - 1f)
PrepareFireBeam(npc, target);
int miscEnemyCount = NPC.CountNPCS(NPCID.LeechHead) + NPC.CountNPCS(NPCID.TheHungryII);
if (Main.netMode != NetmodeID.MultiplayerClient && miscEnemyCount < 3 && totalAttachedEyes <= 0 && attackTimer % 180f == 179f)
{
int leech = NPC.NewNPC(npc.GetSource_FromAI(), (int)npc.Center.X, (int)npc.Center.Y, Main.rand.NextBool() ? NPCID.LeechHead : NPCID.TheHungryII);
if (Main.npc.IndexInRange(leech))
Main.npc[leech].velocity = npc.velocity * 1.25f;
}
// Start recording for the credits.
if (lifeRatio <= Phase2LifeRatio && npc.Infernum().ExtraAI[0] == 0f)
npc.Infernum().ExtraAI[0] = 1f;
// Roar before beginning the eye laser bursts.
if (attackTimer % 1200f == 600f && lifeRatio < Phase2LifeRatio)
SoundEngine.PlaySound(SoundID.NPCDeath10, npc.position);
return false;
}
internal static void SetEyePositions(NPC npc)
{
int left = (int)(npc.Left.X / 16f);
int right = (int)(npc.Right.X / 16f);
int tries = 0;
int y = (int)(npc.Center.Y / 16f) + 7;
while (tries < 15 && y > Main.maxTilesY - 200)
{
y++;
for (int x = left; x <= right; x++)
{
try
{
if (WorldGen.SolidTile(x, y) || Main.tile[x, y].LiquidAmount > 0)
tries++;
}
catch
{
tries += 15;
}
}
}
y += 4;
if (Main.wofDrawAreaBottom == -1)
Main.wofDrawAreaBottom = y * 16;
else if (Main.wofDrawAreaBottom > y * 16)
{
Main.wofDrawAreaBottom--;
if (Main.wofDrawAreaBottom < y * 16)
Main.wofDrawAreaBottom = y * 16;
}
else if (Main.wofDrawAreaBottom < y * 16)
{
Main.wofDrawAreaBottom++;
if (Main.wofDrawAreaBottom > y * 16)
Main.wofDrawAreaBottom = y * 16;
}
tries = 0;
y = (int)(npc.Center.Y / 16f) - 7;
while (tries < 15 && y < Main.maxTilesY - 10)
{
y--;
for (int x = left; x <= right; x++)
{
try
{
if (WorldGen.SolidTile(x, y) || Main.tile[x, y].LiquidAmount > 0)
tries++;
}
catch
{
tries += 15;
}
}
}
y -= 4;
if (Main.wofDrawAreaTop == -1)
Main.wofDrawAreaTop = y * 16;
else if (Main.wofDrawAreaTop > y * 16)
{
Main.wofDrawAreaTop--;
if (Main.wofDrawAreaTop < y * 16)
Main.wofDrawAreaTop = y * 16;
}
else if (Main.wofDrawAreaTop < y * 16)
{
Main.wofDrawAreaTop++;
if (Main.wofDrawAreaTop > y * 16)
Main.wofDrawAreaTop = y * 16;
}
}
internal static void PerformMouthMotion(NPC npc, float lifeRatio)
{
float verticalDestination = (Main.wofDrawAreaBottom + Main.wofDrawAreaTop) / 2 - npc.height / 2;
float horizontalSpeed = Lerp(4.1f, 7.2f, 1f - lifeRatio);
if (verticalDestination < (Main.maxTilesY - 180) * 16f)
verticalDestination = (Main.maxTilesY - 180) * 16f;
if (BossRushEvent.BossRushActive)
horizontalSpeed *= 1.7f;
npc.position.Y = verticalDestination;
if (npc.velocity.X == 0f)
npc.velocity.X = npc.direction;
if (npc.velocity.X < 0f)
{
npc.velocity.X = -horizontalSpeed;
npc.direction = -1;
}
else
{
npc.velocity.X = horizontalSpeed;
npc.direction = 1;
}
}
internal static void SummonEyes(NPC npc)
{
if (Main.netMode == NetmodeID.MultiplayerClient)
return;
for (int i = 0; i < 5; i++)
{
int hungry = NPC.NewNPC(npc.GetSource_FromAI(), (int)npc.position.X, (int)npc.Center.Y, NPCID.TheHungry, npc.whoAmI, 0f, 0f, 0f, 0f, 255);
Main.npc[hungry].ai[0] = i * 0.2f - 0.05f;
}
for (int i = 0; i < 4; i++)
{
float potentialOffsetFactor = i / 3f;
NPC.NewNPC(npc.GetSource_FromAI(), (int)npc.Center.X, (int)npc.Center.Y, NPCID.WallofFleshEye, ai0: potentialOffsetFactor);
}
}
internal static void AngerEffects(NPC npc, Player target)
{
ref float angerStrength = ref npc.ai[0];
ref float timeSpentRunning = ref npc.ai[1];
ref float enrageAttackCountdown = ref npc.ai[2];
ref float roarTimer = ref npc.localAI[2];
float idealAngerStrength = Lerp(0f, 0.8f, Utils.GetLerpValue(1150f, 2300f, Math.Abs(target.Center.X - npc.Center.X), true));
// Check if the player is running in one direction.
if (Math.Abs(Vector2.Dot(target.velocity.SafeNormalize(Vector2.Zero), Vector2.UnitX)) > 0.74f && Math.Abs(target.Center.X - npc.Center.X) > 500f)
timeSpentRunning++;
else
timeSpentRunning--;
if (roarTimer > 0)
roarTimer--;
timeSpentRunning = Clamp(timeSpentRunning, 0f, 1200f);
idealAngerStrength += Lerp(0f, 0.2f, Utils.GetLerpValue(240f, 420f, timeSpentRunning, true));
idealAngerStrength = Clamp(idealAngerStrength, 0f, 1f);
angerStrength = Lerp(angerStrength, idealAngerStrength, 0.03f);
bool targetInHell = target.Center.Y > (Main.maxTilesY - 320f) * 16f;
if (enrageAttackCountdown > 0)
{
// Summon tentacles near the player.
if (Main.netMode != NetmodeID.MultiplayerClient && targetInHell && enrageAttackCountdown % 30f == 29f)
{
Vector2 spawnPosition = target.Center + Main.rand.NextVector2CircularEdge(320f, 320f);
for (int tries = 0; tries < 2500; tries++)
{
int checkArea = 30 + tries / 20;
Vector2 potentialSpawnPosition = target.Center + target.velocity * 10f + Main.rand.NextVector2CircularEdge(checkArea, checkArea) * 16f;
Tile spawnTile = Framing.GetTileSafely((int)potentialSpawnPosition.X / 16, (int)potentialSpawnPosition.Y / 16);
Tile aboveTile = Framing.GetTileSafely((int)potentialSpawnPosition.X / 16, (int)potentialSpawnPosition.Y / 16 - 2);
Tile belowTile = Framing.GetTileSafely((int)potentialSpawnPosition.X / 16, (int)potentialSpawnPosition.Y / 16 + 2);
bool aboveTileInvalid = aboveTile.HasTile && Main.tileSolid[aboveTile.TileType];
bool bottomTileInvalid = belowTile.HasTile && Main.tileSolid[belowTile.TileType];
if (spawnTile.HasUnactuatedTile && Main.tileSolid[spawnTile.TileType] && !aboveTileInvalid && !bottomTileInvalid)
{
spawnPosition = potentialSpawnPosition;
break;
}
}
spawnPosition = spawnPosition.ToTileCoordinates().ToWorldCoordinates();
Vector2 tentacleDirection = target.DirectionFrom(spawnPosition);
Utilities.NewProjectileBetter(spawnPosition, tentacleDirection, ModContent.ProjectileType<TileTentacle>(), FleshTentacleDamage, 0f);
}
enrageAttackCountdown--;
}
// Roaring and preparing for enrage attack.
if (roarTimer <= 0f && targetInHell && enrageAttackCountdown <= 0f && idealAngerStrength >= 0.5f && angerStrength < idealAngerStrength)
{
if (Main.netMode != NetmodeID.Server)
{
roarTimer = 660f;
// Roar.
if (Main.LocalPlayer.Center.Y > (Main.maxTilesY - 300f) * 16f)
SoundEngine.PlaySound(SoundID.NPCDeath10 with { Volume = 1.2f, Pitch = 0.3f }, target.Center);
}
if (Main.netMode != NetmodeID.MultiplayerClient)
{
enrageAttackCountdown = 300f;
npc.netUpdate = true;
}
}
}
internal static void DetermineMouthRotation(NPC npc, Player target)
{
npc.spriteDirection = npc.direction;
if (Utilities.AnyProjectiles(ModContent.ProjectileType<FireBeamWoF>()))
return;
if (npc.direction > 0)
{
if (target.Center.X > npc.Center.X)
npc.rotation = npc.AngleTo(target.Center);
else
npc.rotation = Pi;
}
else if (target.Center.X < npc.Center.X)
npc.rotation = npc.AngleTo(target.Center) + Pi;
else
npc.rotation = 0f;
}
internal static void PrepareFireBeam(NPC npc, Player target)
{
if (Main.netMode == NetmodeID.MultiplayerClient)
return;
Vector2 aimDirection = npc.SafeDirectionTo(target.Center);
Utilities.NewProjectileBetter(npc.Center, aimDirection, ModContent.ProjectileType<FireBeamTelegraph>(), 0, 0f, -1, 0f, npc.whoAmI);
}
#endregion
#region Tips
public override IEnumerable<Func<NPC, string>> GetTips()
{
yield return n => "Mods.InfernumMode.PetDialog.WoFTip2";
yield return n =>
{
if (TipsManager.ShouldUseJokeText)
return "Mods.InfernumMode.PetDialog.WoFTip1";
return string.Empty;
};
yield return n =>
{
if (TipsManager.ShouldUseJokeText)
return "Mods.InfernumMode.PetDialog.WoFJokeTip1";
return string.Empty;
};
}
#endregion Tips
}
}
| 0 | 0.925066 | 1 | 0.925066 | game-dev | MEDIA | 0.99345 | game-dev | 0.961555 | 1 | 0.961555 |
hrydgard/pspautotests | 1,176 | tests/libs/xlib/xtime.c | /*
* xlib - http://xfacter.wordpress.com
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE for details.
*
* Copyright (c) 2009 Alex Wickes
*/
#include <stdio.h>
#include <psptypes.h>
#include <psprtc.h>
#include "xtime.h"
static u64 time_cur;
static u64 time_last;
static float inv_tick_res;
static float delta_time;
static float rel_last_sec;
static float rel_time;
static u32 frames_passed;
static u32 fps;
void xTimeInit()
{
sceRtcGetCurrentTick(&time_last);
inv_tick_res = 1.0f/sceRtcGetTickResolution();
rel_last_sec = 0.0f;
rel_time = 0.0f;
frames_passed = 0;
}
void xTimeUpdate()
{
sceRtcGetCurrentTick(&time_cur);
delta_time = (time_cur - time_last) * inv_tick_res;
time_last = time_cur;
rel_time += delta_time;
frames_passed += 1;
if (rel_time >= rel_last_sec + 1.0f)
{
fps = frames_passed;
frames_passed = 0;
rel_last_sec = rel_time;
}
}
inline float xTimeGetDeltaTime()
{
return delta_time;
}
inline int xTimeFpsApprox()
{
return (int)fps;
}
inline float xTimeSecPassed()
{
return rel_time;
}
| 0 | 0.927318 | 1 | 0.927318 | game-dev | MEDIA | 0.308629 | game-dev | 0.937714 | 1 | 0.937714 |
w3champions/flo | 7,140 | crates/w3map/src/info.rs | use crate::trigger_string::TriggerStringRef;
use flo_util::binary::*;
use flo_util::dword_string::DwordString;
use flo_util::{BinDecode, BinEncode};
#[derive(Debug, BinEncode, BinDecode, PartialEq, PartialOrd, Clone, Copy)]
#[bin(enum_repr(u32))]
pub enum MapFormatVersion {
#[bin(value = 18)]
ROC,
#[bin(value = 25)]
TFT,
#[bin(value = 28)]
TFT131,
#[bin(value = 31)]
Reforged,
#[bin(value = 32)]
Reforged32,
#[bin(value = 33)]
Reforged33,
UnknownValue(u32),
}
#[derive(Debug, BinDecode)]
pub struct MapInfo {
pub version: MapFormatVersion,
#[bin(condition = "version >= MapFormatVersion::ROC")]
pub save_count: Option<u32>,
#[bin(condition = "version >= MapFormatVersion::ROC")]
pub editor_version: Option<u32>,
#[bin(condition = "version >= MapFormatVersion::TFT131")]
pub game_version: Option<GameVersion>,
pub name: TriggerStringRef,
pub author: TriggerStringRef,
pub description: TriggerStringRef,
pub suggested_players: TriggerStringRef,
pub camera_bounds: CameraBounds,
pub width: u32,
pub height: u32,
pub flags: u32,
pub tile_set: u8,
pub ls_background: i32,
#[bin(condition = "version != MapFormatVersion::ROC")]
pub ls_path: Option<TriggerStringRef>,
pub ls_text: TriggerStringRef,
pub ls_title: TriggerStringRef,
pub ls_sub_title: TriggerStringRef,
#[bin(condition = "version >= MapFormatVersion::ROC")]
pub data_set: Option<u32>,
#[bin(condition = "version != MapFormatVersion::ROC")]
pub ps_path: Option<TriggerStringRef>,
pub ps_text: TriggerStringRef,
pub ps_title: TriggerStringRef,
pub ps_sub_title: TriggerStringRef,
#[bin(condition = "version >= MapFormatVersion::TFT")]
pub env: Option<GameEnv>,
#[bin(condition = "version >= MapFormatVersion::TFT131")]
pub code_format: Option<CodeLanguage>,
#[bin(condition = "version >= MapFormatVersion::Reforged")]
pub asset_modes: Option<AssetMode>,
#[bin(condition = "version >= MapFormatVersion::Reforged")]
pub data_version: Option<GameDataVersion>,
#[bin(condition = "version >= MapFormatVersion::Reforged32")]
pub default_cam_distance: Option<u32>,
#[bin(condition = "version >= MapFormatVersion::Reforged32")]
pub max_cam_distance: Option<u32>,
#[bin(condition = "version >= MapFormatVersion::Reforged33")]
pub min_cam_distance: Option<u32>,
pub num_players: u32,
#[bin(condition = "version < MapFormatVersion::Reforged")]
#[bin(repeat = "num_players")]
pub players_classic: Option<Vec<ClassicPlayer>>,
#[bin(condition = "version >= MapFormatVersion::Reforged")]
#[bin(repeat = "num_players")]
pub players_reforged: Option<Vec<ReforgedPlayer>>,
pub num_forces: u32,
#[bin(repeat = "num_forces")]
pub forces: Vec<Force>,
}
#[derive(Debug, Clone, BinDecode)]
pub struct GameVersion {
pub major: u32,
pub minor: u32,
pub patch: u32,
pub commit: u32,
}
#[derive(Debug, Clone, BinDecode)]
pub struct CameraBounds {
pub bounds: [f32; 8],
pub complements: [u32; 4],
}
#[derive(Debug, Clone, BinDecode)]
pub struct GameEnv {
pub fog: u32,
pub fog_start: f32,
pub fog_end: f32,
pub fog_density: f32,
pub fog_color: [u8; 4],
pub weather_id: DwordString,
pub sound_env: TriggerStringRef,
pub light_env: u8,
pub water_color: [u8; 4],
}
#[derive(Debug, BinEncode, BinDecode, PartialEq, PartialOrd, Clone, Copy)]
#[bin(enum_repr(u32))]
pub enum CodeLanguage {
#[bin(value = 0)]
Jass,
#[bin(value = 1)]
Lua,
UnknownValue(u32),
}
#[derive(Debug, BinEncode, BinDecode, PartialEq, PartialOrd, Clone, Copy)]
#[bin(enum_repr(u32))]
pub enum AssetMode {
#[bin(value = 1)]
SD,
#[bin(value = 2)]
HD,
#[bin(value = 3)]
SDAndHD,
UnknownValue(u32),
}
#[derive(Debug, BinEncode, BinDecode, PartialEq, PartialOrd, Clone, Copy)]
#[bin(enum_repr(u32))]
pub enum GameDataVersion {
#[bin(value = 1)]
ROC,
#[bin(value = 2)]
TFT,
UnknownValue(u32),
}
#[derive(Debug, Clone, BinDecode)]
pub struct ClassicPlayer {
pub id: u32,
pub type_: u32,
pub race: u32,
pub flags: u32,
pub name: TriggerStringRef,
pub start_pos_x: f32,
pub start_pos_y: f32,
pub ally_prio_low: u32,
pub ally_prio_high: u32,
}
#[derive(Debug, Clone, BinDecode)]
pub struct ReforgedPlayer {
pub id: u32,
pub type_: u32,
pub race: u32,
pub flags: u32,
pub name: TriggerStringRef,
pub start_pos_x: f32,
pub start_pos_y: f32,
pub ally_prio_low: u32,
pub ally_prio_high: u32,
pub enemy_prio_low: u32,
pub enemy_prio_high: u32,
}
#[derive(Debug, Clone, BinDecode)]
pub struct Force {
pub flags: u32,
pub player_set: u32,
pub name: TriggerStringRef,
}
#[test]
fn test_parse_w3i_reforged() {
let mut map = crate::open_archive(flo_util::sample_path!("map", "(2)ConcealedHill.w3x")).unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
assert_eq!(info.version, MapFormatVersion::Reforged);
assert_eq!(info.num_players, 2);
assert_eq!(info.num_forces, 1);
dbg!("{:#?}", info);
}
#[test]
fn test_parse_w3i_roc() {
let mut map = crate::open_archive(flo_util::sample_path!("map", "test_roc.w3m")).unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
assert_eq!(info.version, MapFormatVersion::ROC);
//assert_eq!(info.num_players, 0);
assert_eq!(info.num_forces, 1);
dbg!("{:#?}", info);
}
#[test]
fn test_parse_w3i_tft() {
let mut map = crate::open_archive(flo_util::sample_path!("map", "test_tft.w3x")).unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
assert_eq!(info.version, MapFormatVersion::TFT);
//assert_eq!(info.num_players, 0);
assert_eq!(info.num_forces, 1);
dbg!("{:#?}", info);
}
#[test]
fn test_parse_custom() {
let mut map = crate::open_archive(flo_util::sample_path!(
"map",
"Impossible.Bosses.v1.10.5.w3x"
))
.unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
// assert_eq!(info.version, MapFormatVersion::TFT);
// assert_eq!(info.num_players, 0);
// assert_eq!(info.num_forces, 1);
dbg!("{:#?}", info);
}
#[test]
fn test_fixed_player() {
let mut map = crate::open_archive(flo_util::sample_path!(
"map",
"fixed_player.w3m"
))
.unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
// assert_eq!(info.version, MapFormatVersion::TFT);
// assert_eq!(info.num_players, 0);
// assert_eq!(info.num_forces, 1);
dbg!("{:#?}", info);
}
#[test]
fn test_patch_203() {
let mut map = crate::open_archive(flo_util::sample_path!("map", "patch2.0.3.w3m")).unwrap();
let bytes = map.open_file("war3map.w3i").unwrap().read_all().unwrap();
let mut buf = bytes.as_slice();
let info = MapInfo::decode(&mut buf).unwrap();
dbg!("{:#?}", info);
} | 0 | 0.729132 | 1 | 0.729132 | game-dev | MEDIA | 0.424346 | game-dev | 0.822817 | 1 | 0.822817 |
sinshu/managed-doom | 38,176 | ManagedDoom/src/Doom/World/ThingMovement.cs | //
// Copyright (C) 1993-1996 Id Software, Inc.
// Copyright (C) 2019-2020 Nobuaki Tanaka
//
// 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.
//
using System;
namespace ManagedDoom
{
public sealed class ThingMovement
{
private World world;
public ThingMovement(World world)
{
this.world = world;
InitThingMovement();
InitSlideMovement();
InitTeleportMovement();
}
////////////////////////////////////////////////////////////
// General thing movement
////////////////////////////////////////////////////////////
public static readonly Fixed FloatSpeed = Fixed.FromInt(4);
private static readonly int maxSpecialCrossCount = 64;
private static readonly Fixed maxMove = Fixed.FromInt(30);
private static readonly Fixed gravity = Fixed.One;
private Mobj currentThing;
private MobjFlags currentFlags;
private Fixed currentX;
private Fixed currentY;
private Fixed[] currentBox;
private Fixed currentFloorZ;
private Fixed currentCeilingZ;
private Fixed currentDropoffZ;
private bool floatOk;
private LineDef currentCeilingLine;
public int crossedSpecialCount;
public LineDef[] crossedSpecials;
private Func<LineDef, bool> checkLineFunc;
private Func<Mobj, bool> checkThingFunc;
private void InitThingMovement()
{
currentBox = new Fixed[4];
crossedSpecials = new LineDef[maxSpecialCrossCount];
checkLineFunc = CheckLine;
checkThingFunc = CheckThing;
}
/// <summary>
/// Links a thing into both a block and a subsector based on
/// its x and y. Sets thing.Subsector properly.
/// </summary>
public void SetThingPosition(Mobj thing)
{
var map = world.Map;
var subsector = Geometry.PointInSubsector(thing.X, thing.Y, map);
thing.Subsector = subsector;
// Invisible things don't go into the sector links.
if ((thing.Flags & MobjFlags.NoSector) == 0)
{
var sector = subsector.Sector;
thing.SectorPrev = null;
thing.SectorNext = sector.ThingList;
if (sector.ThingList != null)
{
sector.ThingList.SectorPrev = thing;
}
sector.ThingList = thing;
}
// Inert things don't need to be in blockmap.
if ((thing.Flags & MobjFlags.NoBlockMap) == 0)
{
var index = map.BlockMap.GetIndex(thing.X, thing.Y);
if (index != -1)
{
var link = map.BlockMap.ThingLists[index];
thing.BlockPrev = null;
thing.BlockNext = link;
if (link != null)
{
link.BlockPrev = thing;
}
map.BlockMap.ThingLists[index] = thing;
}
else
{
// Thing is off the map.
thing.BlockNext = null;
thing.BlockPrev = null;
}
}
}
/// <summary>
/// Unlinks a thing from block map and sectors.
/// On each position change, BLOCKMAP and other lookups
/// maintaining lists ot things inside these structures
/// need to be updated.
/// </summary>
public void UnsetThingPosition(Mobj thing)
{
var map = world.Map;
// Invisible things don't go into the sector links.
if ((thing.Flags & MobjFlags.NoSector) == 0)
{
// Unlink from subsector.
if (thing.SectorNext != null)
{
thing.SectorNext.SectorPrev = thing.SectorPrev;
}
if (thing.SectorPrev != null)
{
thing.SectorPrev.SectorNext = thing.SectorNext;
}
else
{
thing.Subsector.Sector.ThingList = thing.SectorNext;
}
}
// Inert things don't need to be in blockmap.
if ((thing.Flags & MobjFlags.NoBlockMap) == 0)
{
// Unlink from block map.
if (thing.BlockNext != null)
{
thing.BlockNext.BlockPrev = thing.BlockPrev;
}
if (thing.BlockPrev != null)
{
thing.BlockPrev.BlockNext = thing.BlockNext;
}
else
{
var index = map.BlockMap.GetIndex(thing.X, thing.Y);
if (index != -1)
{
map.BlockMap.ThingLists[index] = thing.BlockNext;
}
}
}
}
/// <summary>
/// Adjusts currentFloorZ and currentCeilingZ as lines are contacted.
/// </summary>
private bool CheckLine(LineDef line)
{
var mc = world.MapCollision;
if (currentBox.Right() <= line.BoundingBox.Left() ||
currentBox.Left() >= line.BoundingBox.Right() ||
currentBox.Top() <= line.BoundingBox.Bottom() ||
currentBox.Bottom() >= line.BoundingBox.Top())
{
return true;
}
if (Geometry.BoxOnLineSide(currentBox, line) != -1)
{
return true;
}
// A line has been hit.
//
// The moving thing's destination position will cross the given line.
// If this should not be allowed, return false.
// If the line is special, keep track of it to process later if the move is proven ok.
//
// NOTE:
// specials are NOT sorted by order, so two special lines that are only 8 pixels
// apart could be crossed in either order.
if (line.BackSector == null)
{
// One sided line.
return false;
}
if ((currentThing.Flags & MobjFlags.Missile) == 0)
{
if ((line.Flags & LineFlags.Blocking) != 0)
{
// Explicitly blocking everything.
return false;
}
if (currentThing.Player == null && (line.Flags & LineFlags.BlockMonsters) != 0)
{
// Block monsters only.
return false;
}
}
// Set openrange, opentop, openbottom.
mc.LineOpening(line);
// Adjust floor / ceiling heights.
if (mc.OpenTop < currentCeilingZ)
{
currentCeilingZ = mc.OpenTop;
currentCeilingLine = line;
}
if (mc.OpenBottom > currentFloorZ)
{
currentFloorZ = mc.OpenBottom;
}
if (mc.LowFloor < currentDropoffZ)
{
currentDropoffZ = mc.LowFloor;
}
// If contacted a special line, add it to the list.
if (line.Special != 0)
{
crossedSpecials[crossedSpecialCount] = line;
crossedSpecialCount++;
}
return true;
}
private bool CheckThing(Mobj thing)
{
if ((thing.Flags & (MobjFlags.Solid | MobjFlags.Special | MobjFlags.Shootable)) == 0)
{
return true;
}
var blockDist = thing.Radius + currentThing.Radius;
if (Fixed.Abs(thing.X - currentX) >= blockDist ||
Fixed.Abs(thing.Y - currentY) >= blockDist)
{
// Didn't hit it.
return true;
}
// Don't clip against self.
if (thing == currentThing)
{
return true;
}
// Check for skulls slamming into things.
if ((currentThing.Flags & MobjFlags.SkullFly) != 0)
{
var damage = ((world.Random.Next() % 8) + 1) * currentThing.Info.Damage;
world.ThingInteraction.DamageMobj(thing, currentThing, currentThing, damage);
currentThing.Flags &= ~MobjFlags.SkullFly;
currentThing.MomX = currentThing.MomY = currentThing.MomZ = Fixed.Zero;
currentThing.SetState(currentThing.Info.SpawnState);
// Stop moving.
return false;
}
// Missiles can hit other things.
if ((currentThing.Flags & MobjFlags.Missile) != 0)
{
// See if it went over / under.
if (currentThing.Z > thing.Z + thing.Height)
{
// Overhead.
return true;
}
if (currentThing.Z + currentThing.Height < thing.Z)
{
// Underneath.
return true;
}
if (currentThing.Target != null &&
(currentThing.Target.Type == thing.Type ||
(currentThing.Target.Type == MobjType.Knight && thing.Type == MobjType.Bruiser) ||
(currentThing.Target.Type == MobjType.Bruiser && thing.Type == MobjType.Knight)))
{
// Don't hit same species as originator.
if (thing == currentThing.Target)
{
return true;
}
if (thing.Type != MobjType.Player && !DoomInfo.DeHackEdConst.MonstersInfight)
{
// Explode, but do no damage.
// Let players missile other players.
return false;
}
}
if ((thing.Flags & MobjFlags.Shootable) == 0)
{
// Didn't do any damage.
return (thing.Flags & MobjFlags.Solid) == 0;
}
// Damage / explode.
var damage = ((world.Random.Next() % 8) + 1) * currentThing.Info.Damage;
world.ThingInteraction.DamageMobj(thing, currentThing, currentThing.Target, damage);
// Don't traverse any more.
return false;
}
// Check for special pickup.
if ((thing.Flags & MobjFlags.Special) != 0)
{
var solid = (thing.Flags & MobjFlags.Solid) != 0;
if ((currentFlags & MobjFlags.PickUp) != 0)
{
// Can remove thing.
world.ItemPickup.TouchSpecialThing(thing, currentThing);
}
return !solid;
}
return (thing.Flags & MobjFlags.Solid) == 0;
}
/// <summary>
/// This is purely informative, nothing is modified
/// (except things picked up).
///
/// In:
/// A Mobj (can be valid or invalid)
/// A position to be checked
/// (doesn't need to be related to the mobj.X and Y)
///
/// During:
/// Special things are touched if MobjFlags.PickUp
/// Early out on solid lines?
///
/// Out:
/// New subsector
/// CurrentFloorZ
/// CurrentCeilingZ
/// CurrentDropoffZ
/// The lowest point contacted
/// (monsters won't move to a dropoff)
/// crossedSpecials[]
/// crossedSpecialCount
/// </summary>
public bool CheckPosition(Mobj thing, Fixed x, Fixed y)
{
var map = world.Map;
var bm = map.BlockMap;
currentThing = thing;
currentFlags = thing.Flags;
currentX = x;
currentY = y;
currentBox[Box.Top] = y + currentThing.Radius;
currentBox[Box.Bottom] = y - currentThing.Radius;
currentBox[Box.Right] = x + currentThing.Radius;
currentBox[Box.Left] = x - currentThing.Radius;
var newSubsector = Geometry.PointInSubsector(x, y, map);
currentCeilingLine = null;
// The base floor / ceiling is from the subsector that contains the point.
// Any contacted lines the step closer together will adjust them.
currentFloorZ = currentDropoffZ = newSubsector.Sector.FloorHeight;
currentCeilingZ = newSubsector.Sector.CeilingHeight;
var validCount = world.GetNewValidCount();
crossedSpecialCount = 0;
if ((currentFlags & MobjFlags.NoClip) != 0)
{
return true;
}
// Check things first, possibly picking things up.
// The bounding box is extended by MaxThingRadius because mobj_ts are grouped into
// mapblocks based on their origin point, and can overlap into adjacent blocks by up
// to MaxThingRadius units.
{
var blockX1 = bm.GetBlockX(currentBox[Box.Left] - GameConst.MaxThingRadius);
var blockX2 = bm.GetBlockX(currentBox[Box.Right] + GameConst.MaxThingRadius);
var blockY1 = bm.GetBlockY(currentBox[Box.Bottom] - GameConst.MaxThingRadius);
var blockY2 = bm.GetBlockY(currentBox[Box.Top] + GameConst.MaxThingRadius);
for (var bx = blockX1; bx <= blockX2; bx++)
{
for (var by = blockY1; by <= blockY2; by++)
{
if (!map.BlockMap.IterateThings(bx, by, checkThingFunc))
{
return false;
}
}
}
}
// Check lines.
{
var blockX1 = bm.GetBlockX(currentBox[Box.Left]);
var blockX2 = bm.GetBlockX(currentBox[Box.Right]);
var blockY1 = bm.GetBlockY(currentBox[Box.Bottom]);
var blockY2 = bm.GetBlockY(currentBox[Box.Top]);
for (var bx = blockX1; bx <= blockX2; bx++)
{
for (var by = blockY1; by <= blockY2; by++)
{
if (!map.BlockMap.IterateLines(bx, by, checkLineFunc, validCount))
{
return false;
}
}
}
}
return true;
}
/// <summary>
/// Attempt to move to a new position, crossing special lines unless
/// MobjFlags.Teleport is set.
/// </summary>
public bool TryMove(Mobj thing, Fixed x, Fixed y)
{
floatOk = false;
if (!CheckPosition(thing, x, y))
{
// Solid wall or thing.
return false;
}
if ((thing.Flags & MobjFlags.NoClip) == 0)
{
if (currentCeilingZ - currentFloorZ < thing.Height)
{
// Doesn't fit.
return false;
}
floatOk = true;
if ((thing.Flags & MobjFlags.Teleport) == 0 &&
currentCeilingZ - thing.Z < thing.Height)
{
// Mobj must lower itself to fit.
return false;
}
if ((thing.Flags & MobjFlags.Teleport) == 0 &&
currentFloorZ - thing.Z > Fixed.FromInt(24))
{
// Too big a step up.
return false;
}
if ((thing.Flags & (MobjFlags.DropOff | MobjFlags.Float)) == 0 &&
currentFloorZ - currentDropoffZ > Fixed.FromInt(24))
{
// Don't stand over a dropoff.
return false;
}
}
// The move is ok,
// so link the thing into its new position.
UnsetThingPosition(thing);
var oldx = thing.X;
var oldy = thing.Y;
thing.FloorZ = currentFloorZ;
thing.CeilingZ = currentCeilingZ;
thing.X = x;
thing.Y = y;
SetThingPosition(thing);
// If any special lines were hit, do the effect.
if ((thing.Flags & (MobjFlags.Teleport | MobjFlags.NoClip)) == 0)
{
while (crossedSpecialCount-- > 0)
{
// See if the line was crossed.
var line = crossedSpecials[crossedSpecialCount];
var newSide = Geometry.PointOnLineSide(thing.X, thing.Y, line);
var oldSide = Geometry.PointOnLineSide(oldx, oldy, line);
if (newSide != oldSide)
{
if (line.Special != 0)
{
world.MapInteraction.CrossSpecialLine(line, oldSide, thing);
}
}
}
}
return true;
}
private static readonly Fixed stopSpeed = new Fixed(0x1000);
private static readonly Fixed friction = new Fixed(0xe800);
public void XYMovement(Mobj thing)
{
if (thing.MomX == Fixed.Zero && thing.MomY == Fixed.Zero)
{
if ((thing.Flags & MobjFlags.SkullFly) != 0)
{
// The skull slammed into something.
thing.Flags &= ~MobjFlags.SkullFly;
thing.MomX = thing.MomY = thing.MomZ = Fixed.Zero;
thing.SetState(thing.Info.SpawnState);
}
return;
}
var player = thing.Player;
if (thing.MomX > maxMove)
{
thing.MomX = maxMove;
}
else if (thing.MomX < -maxMove)
{
thing.MomX = -maxMove;
}
if (thing.MomY > maxMove)
{
thing.MomY = maxMove;
}
else if (thing.MomY < -maxMove)
{
thing.MomY = -maxMove;
}
var moveX = thing.MomX;
var moveY = thing.MomY;
do
{
Fixed pMoveX;
Fixed pMoveY;
if (moveX > maxMove / 2 || moveY > maxMove / 2)
{
pMoveX = thing.X + moveX / 2;
pMoveY = thing.Y + moveY / 2;
moveX >>= 1;
moveY >>= 1;
}
else
{
pMoveX = thing.X + moveX;
pMoveY = thing.Y + moveY;
moveX = moveY = Fixed.Zero;
}
if (!TryMove(thing, pMoveX, pMoveY))
{
// Blocked move.
if (thing.Player != null)
{ // Try to slide along it.
SlideMove(thing);
}
else if ((thing.Flags & MobjFlags.Missile) != 0)
{
// Explode a missile.
if (currentCeilingLine != null &&
currentCeilingLine.BackSector != null &&
currentCeilingLine.BackSector.CeilingFlat == world.Map.SkyFlatNumber)
{
// Hack to prevent missiles exploding against the sky.
// Does not handle sky floors.
world.ThingAllocation.RemoveMobj(thing);
return;
}
world.ThingInteraction.ExplodeMissile(thing);
}
else
{
thing.MomX = thing.MomY = Fixed.Zero;
}
}
}
while (moveX != Fixed.Zero || moveY != Fixed.Zero);
// Slow down.
if (player != null && (player.Cheats & CheatFlags.NoMomentum) != 0)
{
// Debug option for no sliding at all.
thing.MomX = thing.MomY = Fixed.Zero;
return;
}
if ((thing.Flags & (MobjFlags.Missile | MobjFlags.SkullFly)) != 0)
{
// No friction for missiles ever.
return;
}
if (thing.Z > thing.FloorZ)
{
// No friction when airborne.
return;
}
if ((thing.Flags & MobjFlags.Corpse) != 0)
{
// Do not stop sliding if halfway off a step with some momentum.
if (thing.MomX > Fixed.One / 4 ||
thing.MomX < -Fixed.One / 4 ||
thing.MomY > Fixed.One / 4 ||
thing.MomY < -Fixed.One / 4)
{
if (thing.FloorZ != thing.Subsector.Sector.FloorHeight)
{
return;
}
}
}
if (thing.MomX > -stopSpeed &&
thing.MomX < stopSpeed &&
thing.MomY > -stopSpeed &&
thing.MomY < stopSpeed &&
(player == null || (player.Cmd.ForwardMove == 0 && player.Cmd.SideMove == 0)))
{
// If in a walking frame, stop moving.
if (player != null && (player.Mobj.State.Number - (int)MobjState.PlayRun1) < 4)
{
player.Mobj.SetState(MobjState.Play);
}
thing.MomX = Fixed.Zero;
thing.MomY = Fixed.Zero;
}
else
{
thing.MomX = thing.MomX * friction;
thing.MomY = thing.MomY * friction;
}
}
public void ZMovement(Mobj thing)
{
// Check for smooth step up.
if (thing.Player != null && thing.Z < thing.FloorZ)
{
thing.Player.ViewHeight -= thing.FloorZ - thing.Z;
thing.Player.DeltaViewHeight =
(Player.NormalViewHeight - thing.Player.ViewHeight) >> 3;
}
// Adjust height.
thing.Z += thing.MomZ;
if ((thing.Flags & MobjFlags.Float) != 0 && thing.Target != null)
{
// Float down towards target if too close.
if ((thing.Flags & MobjFlags.SkullFly) == 0 &&
(thing.Flags & MobjFlags.InFloat) == 0)
{
var dist = Geometry.AproxDistance(
thing.X - thing.Target.X,
thing.Y - thing.Target.Y);
var delta = (thing.Target.Z + (thing.Height >> 1)) - thing.Z;
if (delta < Fixed.Zero && dist < -(delta * 3))
{
thing.Z -= FloatSpeed;
}
else if (delta > Fixed.Zero && dist < (delta * 3))
{
thing.Z += FloatSpeed;
}
}
}
// Clip movement.
if (thing.Z <= thing.FloorZ)
{
// Hit the floor.
//
// The lost soul bounce fix below is based on Chocolate Doom's implementation.
//
var correctLostSoulBounce = world.Options.GameVersion >= GameVersion.Ultimate;
if (correctLostSoulBounce && (thing.Flags & MobjFlags.SkullFly) != 0)
{
// The skull slammed into something.
thing.MomZ = -thing.MomZ;
}
if (thing.MomZ < Fixed.Zero)
{
if (thing.Player != null && thing.MomZ < -gravity * 8)
{
// Squat down.
// Decrease viewheight for a moment after hitting the ground (hard),
// and utter appropriate sound.
thing.Player.DeltaViewHeight = (thing.MomZ >> 3);
world.StartSound(thing, Sfx.OOF, SfxType.Voice);
}
thing.MomZ = Fixed.Zero;
}
thing.Z = thing.FloorZ;
if (!correctLostSoulBounce &&
(thing.Flags & MobjFlags.SkullFly) != 0)
{
thing.MomZ = -thing.MomZ;
}
if ((thing.Flags & MobjFlags.Missile) != 0 &&
(thing.Flags & MobjFlags.NoClip) == 0)
{
world.ThingInteraction.ExplodeMissile(thing);
return;
}
}
else if ((thing.Flags & MobjFlags.NoGravity) == 0)
{
if (thing.MomZ == Fixed.Zero)
{
thing.MomZ = -gravity * 2;
}
else
{
thing.MomZ -= gravity;
}
}
if (thing.Z + thing.Height > thing.CeilingZ)
{
// Hit the ceiling.
if (thing.MomZ > Fixed.Zero)
{
thing.MomZ = Fixed.Zero;
}
{
thing.Z = thing.CeilingZ - thing.Height;
}
if ((thing.Flags & MobjFlags.SkullFly) != 0)
{
// The skull slammed into something.
thing.MomZ = -thing.MomZ;
}
if ((thing.Flags & MobjFlags.Missile) != 0 &&
(thing.Flags & MobjFlags.NoClip) == 0)
{
world.ThingInteraction.ExplodeMissile(thing);
return;
}
}
}
public Fixed CurrentFloorZ => currentFloorZ;
public Fixed CurrentCeilingZ => currentCeilingZ;
public Fixed CurrentDropoffZ => currentDropoffZ;
public bool FloatOk => floatOk;
////////////////////////////////////////////////////////////
// Player's slide movement
////////////////////////////////////////////////////////////
private Fixed bestSlideFrac;
private Fixed secondSlideFrac;
private LineDef bestSlideLine;
private LineDef secondSlideLine;
private Mobj slideThing;
private Fixed slideMoveX;
private Fixed slideMoveY;
private Func<Intercept, bool> slideTraverseFunc;
private void InitSlideMovement()
{
slideTraverseFunc = SlideTraverse;
}
/// <summary>
/// Adjusts the x and y movement so that the next move will
/// slide along the wall.
/// </summary>
private void HitSlideLine(LineDef line)
{
if (line.SlopeType == SlopeType.Horizontal)
{
slideMoveY = Fixed.Zero;
return;
}
if (line.SlopeType == SlopeType.Vertical)
{
slideMoveX = Fixed.Zero;
return;
}
var side = Geometry.PointOnLineSide(slideThing.X, slideThing.Y, line);
var lineAngle = Geometry.PointToAngle(Fixed.Zero, Fixed.Zero, line.Dx, line.Dy);
if (side == 1)
{
lineAngle += Angle.Ang180;
}
var moveAngle = Geometry.PointToAngle(Fixed.Zero, Fixed.Zero, slideMoveX, slideMoveY);
var deltaAngle = moveAngle - lineAngle;
if (deltaAngle > Angle.Ang180)
{
deltaAngle += Angle.Ang180;
}
var moveDist = Geometry.AproxDistance(slideMoveX, slideMoveY);
var newDist = moveDist * Trig.Cos(deltaAngle);
slideMoveX = newDist * Trig.Cos(lineAngle);
slideMoveY = newDist * Trig.Sin(lineAngle);
}
private bool SlideTraverse(Intercept intercept)
{
var mc = world.MapCollision;
if (intercept.Line == null)
{
throw new Exception("ThingMovement.SlideTraverse: Not a line?");
}
var line = intercept.Line;
if ((line.Flags & LineFlags.TwoSided) == 0)
{
if (Geometry.PointOnLineSide(slideThing.X, slideThing.Y, line) != 0)
{
// Don't hit the back side.
return true;
}
goto isBlocking;
}
// Set openrange, opentop, openbottom.
mc.LineOpening(line);
if (mc.OpenRange < slideThing.Height)
{
// Doesn't fit.
goto isBlocking;
}
if (mc.OpenTop - slideThing.Z < slideThing.Height)
{
// Mobj is too high.
goto isBlocking;
}
if (mc.OpenBottom - slideThing.Z > Fixed.FromInt(24))
{
// Too big a step up.
goto isBlocking;
}
// This line doesn't block movement.
return true;
// The line does block movement, see if it is closer than best so far.
isBlocking:
if (intercept.Frac < bestSlideFrac)
{
secondSlideFrac = bestSlideFrac;
secondSlideLine = bestSlideLine;
bestSlideFrac = intercept.Frac;
bestSlideLine = line;
}
// Stop.
return false;
}
/// <summary>
/// The MomX / MomY move is bad, so try to slide along a wall.
/// Find the first line hit, move flush to it, and slide along it.
/// This is a kludgy mess.
/// </summary>
private void SlideMove(Mobj thing)
{
var pt = world.PathTraversal;
slideThing = thing;
var hitCount = 0;
retry:
// Don't loop forever.
if (++hitCount == 3)
{
// The move most have hit the middle, so stairstep.
StairStep(thing);
return;
}
Fixed leadX;
Fixed leadY;
Fixed trailX;
Fixed trailY;
// Trace along the three leading corners.
if (thing.MomX > Fixed.Zero)
{
leadX = thing.X + thing.Radius;
trailX = thing.X - thing.Radius;
}
else
{
leadX = thing.X - thing.Radius;
trailX = thing.X + thing.Radius;
}
if (thing.MomY > Fixed.Zero)
{
leadY = thing.Y + thing.Radius;
trailY = thing.Y - thing.Radius;
}
else
{
leadY = thing.Y - thing.Radius;
trailY = thing.Y + thing.Radius;
}
bestSlideFrac = Fixed.OnePlusEpsilon;
pt.PathTraverse(
leadX, leadY, leadX + thing.MomX, leadY + thing.MomY,
PathTraverseFlags.AddLines, slideTraverseFunc);
pt.PathTraverse(
trailX, leadY, trailX + thing.MomX, leadY + thing.MomY,
PathTraverseFlags.AddLines, slideTraverseFunc);
pt.PathTraverse(
leadX, trailY, leadX + thing.MomX, trailY + thing.MomY,
PathTraverseFlags.AddLines, slideTraverseFunc);
// Move up to the wall.
if (bestSlideFrac == Fixed.OnePlusEpsilon)
{
// The move most have hit the middle, so stairstep.
StairStep(thing);
return;
}
// Fudge a bit to make sure it doesn't hit.
bestSlideFrac = new Fixed(bestSlideFrac.Data - 0x800);
if (bestSlideFrac > Fixed.Zero)
{
var newX = thing.MomX * bestSlideFrac;
var newY = thing.MomY * bestSlideFrac;
if (!TryMove(thing, thing.X + newX, thing.Y + newY))
{
// The move most have hit the middle, so stairstep.
StairStep(thing);
return;
}
}
// Now continue along the wall.
// First calculate remainder.
bestSlideFrac = new Fixed(Fixed.FracUnit - (bestSlideFrac.Data + 0x800));
if (bestSlideFrac > Fixed.One)
{
bestSlideFrac = Fixed.One;
}
if (bestSlideFrac <= Fixed.Zero)
{
return;
}
slideMoveX = thing.MomX * bestSlideFrac;
slideMoveY = thing.MomY * bestSlideFrac;
// Clip the moves.
HitSlideLine(bestSlideLine);
thing.MomX = slideMoveX;
thing.MomY = slideMoveY;
if (!TryMove(thing, thing.X + slideMoveX, thing.Y + slideMoveY))
{
goto retry;
}
}
private void StairStep(Mobj thing)
{
if (!TryMove(thing, thing.X, thing.Y + thing.MomY))
{
TryMove(thing, thing.X + thing.MomX, thing.Y);
}
}
////////////////////////////////////////////////////////////
// Teleport movement
////////////////////////////////////////////////////////////
private Func<Mobj, bool> stompThingFunc;
private void InitTeleportMovement()
{
stompThingFunc = StompThing;
}
private bool StompThing(Mobj thing)
{
if ((thing.Flags & MobjFlags.Shootable) == 0)
{
return true;
}
var blockDist = thing.Radius + currentThing.Radius;
var dx = Fixed.Abs(thing.X - currentX);
var dy = Fixed.Abs(thing.Y - currentY);
if (dx >= blockDist || dy >= blockDist)
{
// Didn't hit it.
return true;
}
// Don't clip against self.
if (thing == currentThing)
{
return true;
}
// Monsters don't stomp things except on boss level.
if (currentThing.Player == null && world.Options.Map != 30)
{
return false;
}
world.ThingInteraction.DamageMobj(thing, currentThing, currentThing, 10000);
return true;
}
public bool TeleportMove(Mobj thing, Fixed x, Fixed y)
{
// Kill anything occupying the position.
currentThing = thing;
currentFlags = thing.Flags;
currentX = x;
currentY = y;
currentBox[Box.Top] = y + currentThing.Radius;
currentBox[Box.Bottom] = y - currentThing.Radius;
currentBox[Box.Right] = x + currentThing.Radius;
currentBox[Box.Left] = x - currentThing.Radius;
var ss = Geometry.PointInSubsector(x, y, world.Map);
currentCeilingLine = null;
// The base floor / ceiling is from the subsector that contains the point.
// Any contacted lines the step closer together will adjust them.
currentFloorZ = currentDropoffZ = ss.Sector.FloorHeight;
currentCeilingZ = ss.Sector.CeilingHeight;
var validcount = world.GetNewValidCount();
crossedSpecialCount = 0;
// Stomp on any things contacted.
var bm = world.Map.BlockMap;
var blockX1 = bm.GetBlockX(currentBox[Box.Left] - GameConst.MaxThingRadius);
var blockX2 = bm.GetBlockX(currentBox[Box.Right] + GameConst.MaxThingRadius);
var blockY1 = bm.GetBlockY(currentBox[Box.Bottom] - GameConst.MaxThingRadius);
var blockY2 = bm.GetBlockY(currentBox[Box.Top] + GameConst.MaxThingRadius);
for (var bx = blockX1; bx <= blockX2; bx++)
{
for (var by = blockY1; by <= blockY2; by++)
{
if (!bm.IterateThings(bx, by, stompThingFunc))
{
return false;
}
}
}
// the move is ok, so link the thing into its new position
UnsetThingPosition(thing);
thing.FloorZ = currentFloorZ;
thing.CeilingZ = currentCeilingZ;
thing.X = x;
thing.Y = y;
SetThingPosition(thing);
return true;
}
}
}
| 0 | 0.921145 | 1 | 0.921145 | game-dev | MEDIA | 0.925937 | game-dev | 0.944108 | 1 | 0.944108 |
MaksymHernets/AutoTranslateForUnityLocalization | 1,976 | Assets/AutoTranslate/Editor/BaseCustomWindow_EditorWindow.cs | using EqualchanceGames.Tools.GUIPro;
using EqualchanceGames.Tools.Helpers;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace EqualchanceGames.Tools.AutoTranslate.Windows
{
public class BaseCustomWindow_EditorWindow : EditorWindow
{
protected UnityEditor.SceneManagement.PrefabStage _prefabStage;
protected Scene _currentScene;
// Window parameters
protected int k_SeparationWidth = 260;
//public static void ShowWindow()
//{
// Type gameview = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView");
// CleanupLocalization_EditorWindow window = GetWindow<CleanupLocalization_EditorWindow>(k_WindowTitle, true, typeof(SceneView), gameview);
// window.titleContent = new GUIContent(k_WindowTitle, EditorIcons.CleanupLocalization);
// window.Show();
//}
protected virtual void OnEnable()
{
_currentScene = DatabaseProject.GetCurrentScene();
_prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
}
protected virtual void OnFocus()
{
_currentScene = DatabaseProject.GetCurrentScene();
_prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
}
protected void ShowNameWindow(string name)
{
GUI.enabled = false;
GUILayout.Button(name, GUILayout.Height(30));
GUI.enabled = true;
GUILayout.Space(10);
}
protected void Show_CurrentOpen()
{
if (_prefabStage == null)
{
LinesGUI.DrawTexts("Current Scene", _currentScene.name, k_SeparationWidth);
}
else
{
LinesGUI.DrawTexts("Current Prefab", _prefabStage.prefabContentsRoot.name, k_SeparationWidth);
}
}
}
} | 0 | 0.816825 | 1 | 0.816825 | game-dev | MEDIA | 0.910116 | game-dev | 0.860842 | 1 | 0.860842 |
blackbeard334/djoom3 | 4,364 | src/main/java/neo/CM/CollisionModel_translate.java | package neo.CM;
import neo.CM.CollisionModel_local.cm_edge_s;
import neo.CM.CollisionModel_local.cm_traceWork_s;
import neo.CM.CollisionModel_local.cm_vertex_s;
import neo.idlib.math.Plane.idPlane;
import neo.idlib.math.Pluecker.idPluecker;
import neo.idlib.math.Vector.idVec3;
import static neo.CM.CollisionModel.CM_CLIP_EPSILON;
import static neo.CM.CollisionModel.contactInfo_t;
import static neo.idlib.math.Math_h.FLOATSIGNBITNOTSET;
import static neo.idlib.math.Math_h.FLOATSIGNBITSET;
/**
*
*/
public class CollisionModel_translate {
/*
===============================================================================
Trace model vs. polygonal model collision detection.
===============================================================================
*/
/*
===============================================================================
Collision detection for translational motion
===============================================================================
*/
/*
================
CM_AddContact
================
*/ private static int DBG_CM_AddContact = 0;
static void CM_AddContact(cm_traceWork_s tw) {
if (tw.numContacts >= tw.maxContacts) {
return;
} DBG_CM_AddContact++;
// copy contact information from trace_t
tw.contacts[tw.numContacts] = new contactInfo_t(tw.trace.c);
tw.numContacts++;
// set fraction back to 1 to find all other contacts
tw.trace.fraction = 1.0f;
}
/*
================
CM_SetVertexSidedness
stores for the given model vertex at which side of one of the trm edges it passes
================
*/
static void CM_SetVertexSidedness(cm_vertex_s v, final idPluecker vpl, final idPluecker epl, final int bitNum) {
if (0 == (v.sideSet & (1 << bitNum))) {
float fl;
fl = vpl.PermutedInnerProduct(epl);
v.side = (v.side & ~(1 << bitNum)) | (FLOATSIGNBITSET(fl) << bitNum);
v.sideSet |= (1 << bitNum);
}
}
/*
================
CM_SetEdgeSidedness
stores for the given model edge at which side one of the trm vertices
================
*/
static void CM_SetEdgeSidedness(cm_edge_s edge, final idPluecker vpl, final idPluecker epl, final int bitNum) {
if (0 == (edge.sideSet & (1 << bitNum))) {
float fl;
fl = vpl.PermutedInnerProduct(epl);
edge.side = (edge.side & ~(1 << bitNum)) | (FLOATSIGNBITSET(fl) << bitNum);
edge.sideSet |= (1 << bitNum);
}
}
/*
================
CM_TranslationPlaneFraction
================
*/
static float CM_TranslationPlaneFraction(idPlane plane, idVec3 start, idVec3 end) {
// if (false) {
// float d1, d2;
//
// d2 = plane.Distance(end);
// // if the end point is closer to the plane than an epsilon we still take it for a collision
// if (d2 >= CM_CLIP_EPSILON) {
// return 1.0f;
// }
// d1 = plane.Distance(start);
//
// // if completely behind the polygon
// if (d1 <= 0.0f) {
// return 1.0f;
// }
// // leaves polygon
// if (d1 <= d2) {
// return 1.0f;
// }
// return (d1 - CM_CLIP_EPSILON) / (d1 - d2);
//
// } else
{
float d1, d2, d2eps;
d2 = plane.Distance(end);
// if the end point is closer to the plane than an epsilon we still take it for a collision
// if ( d2 >= CM_CLIP_EPSILON ) {
d2eps = d2 - CM_CLIP_EPSILON;
if (FLOATSIGNBITNOTSET(d2eps) != 0) {
return 1.0f;
}
d1 = plane.Distance(start);
// if completely behind the polygon
if (FLOATSIGNBITSET(d1) != 0) {
return 1.0f;
}
// if going towards the front of the plane and
// the start and end point are not at equal distance from the plane
// if ( d1 > d2 )
d2 = d1 - d2;
if (d2 <= 0.0f) {
return 1.0f;
}
return (d1 - CM_CLIP_EPSILON) / d2;
}
}
}
| 0 | 0.888913 | 1 | 0.888913 | game-dev | MEDIA | 0.966411 | game-dev | 0.998051 | 1 | 0.998051 |
CafeFPS/r5_flowstate | 1,649 | vscripts/client/cl_passives.gnut | global function Cl_Passives_Init
global function AddCallback_CreatePlayerPassiveRui
global function AddCallback_DestroyPlayerPassiveRui
struct
{
array<void functionref( entity player )> CreatePlayerPassiveRui
array<void functionref( entity player )> DestroyPlayerPassiveRui
} file
void function Cl_Passives_Init()
{
AddCallback_OnInitWeaponStatusRuis( OnInitWeaponStatusRuis_CLPassives )
AddCallback_PlayerClassChanged( OnPlayerClassChanged_CLPassives )
AddOnSpectatorTargetChangedCallback( OnSpectatorTargetChanged )
}
void function AddCallback_CreatePlayerPassiveRui( void functionref( entity ) callbackFunc )
{
file.CreatePlayerPassiveRui.append( callbackFunc )
}
void function AddCallback_DestroyPlayerPassiveRui( void functionref( entity ) callbackFunc )
{
file.DestroyPlayerPassiveRui.append( callbackFunc )
}
void function OnInitWeaponStatusRuis_CLPassives( entity player )
{
if ( player != GetLocalViewPlayer() )
return
foreach ( callbackFunc in file.DestroyPlayerPassiveRui )
{
callbackFunc( player )
}
foreach ( callbackFunc in file.CreatePlayerPassiveRui )
{
callbackFunc( player )
}
}
void function OnPlayerClassChanged_CLPassives( entity player )
{
if ( player != GetLocalViewPlayer() )
return
foreach ( callbackFunc in file.DestroyPlayerPassiveRui )
{
callbackFunc( player )
}
}
void function OnSpectatorTargetChanged( entity observer, entity prevTarget, entity newTarget )
{
if ( !IsPrivateMatch() )
return
if ( observer.GetTeam() != TEAM_SPECTATOR )
return
if( !IsValid(newTarget) )
return
foreach ( callbackFunc in file.DestroyPlayerPassiveRui )
{
callbackFunc( newTarget )
}
} | 0 | 0.522922 | 1 | 0.522922 | game-dev | MEDIA | 0.79404 | game-dev | 0.615046 | 1 | 0.615046 |
Nebukam/PCGExtendedToolkit | 1,714 | Source/PCGExtendedToolkit/Public/Graph/Edges/Refining/PCGExEdgeRefineKeepHighestScore.h | // Copyright 2025 Timothé Lapetite and contributors
// Released under the MIT license https://opensource.org/license/MIT/
#pragma once
#include "CoreMinimal.h"
#include "PCGExEdgeRefineOperation.h"
#include "Graph/PCGExCluster.h"
#include "Graph/Pathfinding/Heuristics/PCGExHeuristics.h"
#include "PCGExEdgeRefineKeepHighestScore.generated.h"
/**
*
*/
class FPCGExEdgeKeepHighestScore : public FPCGExEdgeRefineOperation
{
public:
virtual void ProcessNode(PCGExCluster::FNode& Node) override
{
int32 BestIndex = -1;
double HighestScore = MIN_dbl_neg;
const PCGExCluster::FNode& RoamingSeedNode = *Heuristics->GetRoamingSeed();
const PCGExCluster::FNode& RoamingGoalNode = *Heuristics->GetRoamingGoal();
for (const PCGExGraph::FLink Lk : Node.Links)
{
const double Score = Heuristics->GetEdgeScore(Node, *Cluster->GetNode(Lk), *Cluster->GetEdge(Lk), RoamingSeedNode, RoamingGoalNode);
if (Score > HighestScore)
{
HighestScore = Score;
BestIndex = Lk.Edge;
}
}
if (BestIndex == -1) { return; }
//if (!*(EdgesFilters->GetData() + BestIndex)) { return; }
FPlatformAtomics::InterlockedExchange(&Cluster->GetEdge(BestIndex)->bValid, 1);
}
};
/**
*
*/
UCLASS(MinimalAPI, BlueprintType, meta=(DisplayName="Keep Highest Score", PCGExNodeLibraryDoc="clusters/refine-cluster/edge-score"))
class UPCGExEdgeKeepHighestScore : public UPCGExEdgeRefineInstancedFactory
{
GENERATED_BODY()
public:
virtual bool GetDefaultEdgeValidity() const override { return false; }
virtual bool WantsHeuristics() const override { return true; }
virtual bool WantsIndividualNodeProcessing() const override { return true; }
PCGEX_CREATE_REFINE_OPERATION(EdgeKeepHighestScore, {})
};
| 0 | 0.842104 | 1 | 0.842104 | game-dev | MEDIA | 0.779323 | game-dev | 0.749719 | 1 | 0.749719 |
magefree/mage | 1,247 | Mage.Sets/src/mage/cards/i/InspiringCaptain.java | package mage.cards.i;
import mage.MageInt;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import java.util.UUID;
/**
* @author fireshoes
*/
public final class InspiringCaptain extends CardImpl {
public InspiringCaptain(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.KNIGHT);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// When Inspiring Captain enters the battlefield, creatures you control get +1/+1 until end of turn.
this.addAbility(new EntersBattlefieldTriggeredAbility(new BoostControlledEffect(1, 1, Duration.EndOfTurn, StaticFilters.FILTER_PERMANENT_CREATURES)));
}
private InspiringCaptain(final InspiringCaptain card) {
super(card);
}
@Override
public InspiringCaptain copy() {
return new InspiringCaptain(this);
}
}
| 0 | 0.938904 | 1 | 0.938904 | game-dev | MEDIA | 0.983724 | game-dev | 0.993941 | 1 | 0.993941 |
ShuangYu1145/Faiths-Fix | 8,336 | src/main/java/net/minecraft/block/BlockHopper.java | package net.minecraft.block;
import com.google.common.base.Predicate;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.List;
public class BlockHopper extends BlockContainer
{
public static final PropertyDirection FACING = PropertyDirection.create("facing", new Predicate<EnumFacing>()
{
public boolean apply(EnumFacing p_apply_1_)
{
return p_apply_1_ != EnumFacing.UP;
}
});
public static final PropertyBool ENABLED = PropertyBool.create("enabled");
public BlockHopper()
{
super(Material.iron, MapColor.stoneColor);
this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.DOWN).withProperty(ENABLED, Boolean.valueOf(true)));
this.setCreativeTab(CreativeTabs.tabRedstone);
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos)
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Add all collision boxes of this Block to the list that intersect with the given mask.
*/
public void addCollisionBoxesToList(World worldIn, BlockPos pos, IBlockState state, AxisAlignedBB mask, List<AxisAlignedBB> list, Entity collidingEntity)
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F);
super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
float f = 0.125F;
this.setBlockBounds(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F);
super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f);
super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
this.setBlockBounds(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
this.setBlockBounds(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F);
super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the
* IBlockstate
*/
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
EnumFacing enumfacing = facing.getOpposite();
if (enumfacing == EnumFacing.UP)
{
enumfacing = EnumFacing.DOWN;
}
return this.getDefaultState().withProperty(FACING, enumfacing).withProperty(ENABLED, Boolean.valueOf(true));
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileEntityHopper();
}
/**
* Called by ItemBlocks after a block is set in the world, to allow post-place logic
*/
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
if (stack.hasDisplayName())
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityHopper)
{
((TileEntityHopper)tileentity).setCustomName(stack.getDisplayName());
}
}
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
this.updateState(worldIn, pos, state);
}
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
{
if (worldIn.isRemote)
{
return true;
}
else
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityHopper)
{
playerIn.displayGUIChest((TileEntityHopper)tileentity);
playerIn.triggerAchievement(StatList.field_181732_P);
}
return true;
}
}
/**
* Called when a neighboring block changes.
*/
public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock)
{
this.updateState(worldIn, pos, state);
}
private void updateState(World worldIn, BlockPos pos, IBlockState state)
{
boolean flag = !worldIn.isBlockPowered(pos);
if (flag != ((Boolean)state.getValue(ENABLED)).booleanValue())
{
worldIn.setBlockState(pos, state.withProperty(ENABLED, Boolean.valueOf(flag)), 4);
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityHopper)
{
InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityHopper)tileentity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
/**
* The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render
*/
public int getRenderType()
{
return 3;
}
public boolean isFullCube()
{
return false;
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube()
{
return false;
}
public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side)
{
return true;
}
public static EnumFacing getFacing(int meta)
{
return EnumFacing.getFront(meta & 7);
}
/**
* Get's the hopper's active status from the 8-bit of the metadata. Note that the metadata stores whether the block
* is powered, so this returns true when that bit is 0.
*/
public static boolean isEnabled(int meta)
{
return (meta & 8) != 8;
}
public boolean hasComparatorInputOverride()
{
return true;
}
public int getComparatorInputOverride(World worldIn, BlockPos pos)
{
return Container.calcRedstone(worldIn.getTileEntity(pos));
}
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.CUTOUT_MIPPED;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(FACING, getFacing(meta)).withProperty(ENABLED, Boolean.valueOf(isEnabled(meta)));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
int i = 0;
i = i | ((EnumFacing)state.getValue(FACING)).getIndex();
if (!((Boolean)state.getValue(ENABLED)).booleanValue())
{
i |= 8;
}
return i;
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {FACING, ENABLED});
}
}
| 0 | 0.843633 | 1 | 0.843633 | game-dev | MEDIA | 0.998186 | game-dev | 0.960404 | 1 | 0.960404 |
oot-pc-port/oot-pc-port | 2,946 | asm/non_matchings/overlays/actors/ovl_En_Dodongo/func_809F8BFC.s | glabel func_809F8BFC
/* 009AC 809F8BFC 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00
/* 009B0 809F8C00 27BDFFD0 */ addiu $sp, $sp, 0xFFD0 ## $sp = FFFFFFD0
/* 009B4 809F8C04 3C01C080 */ lui $at, 0xC080 ## $at = C0800000
/* 009B8 809F8C08 44812000 */ mtc1 $at, $f4 ## $f4 = -4.00
/* 009BC 809F8C0C AFB00028 */ sw $s0, 0x0028($sp)
/* 009C0 809F8C10 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 009C4 809F8C14 AFBF002C */ sw $ra, 0x002C($sp)
/* 009C8 809F8C18 3C050600 */ lui $a1, 0x0600 ## $a1 = 06000000
/* 009CC 809F8C1C 240E0002 */ addiu $t6, $zero, 0x0002 ## $t6 = 00000002
/* 009D0 809F8C20 44060000 */ mfc1 $a2, $f0
/* 009D4 809F8C24 AFAE0014 */ sw $t6, 0x0014($sp)
/* 009D8 809F8C28 24A528F0 */ addiu $a1, $a1, 0x28F0 ## $a1 = 060028F0
/* 009DC 809F8C2C 2484014C */ addiu $a0, $a0, 0x014C ## $a0 = 0000014C
/* 009E0 809F8C30 3C0741C8 */ lui $a3, 0x41C8 ## $a3 = 41C80000
/* 009E4 809F8C34 E7A00010 */ swc1 $f0, 0x0010($sp)
/* 009E8 809F8C38 0C029468 */ jal SkelAnime_ChangeAnimation
/* 009EC 809F8C3C E7A40018 */ swc1 $f4, 0x0018($sp)
/* 009F0 809F8C40 921803CC */ lbu $t8, 0x03CC($s0) ## 000003CC
/* 009F4 809F8C44 44803000 */ mtc1 $zero, $f6 ## $f6 = 0.00
/* 009F8 809F8C48 240F0007 */ addiu $t7, $zero, 0x0007 ## $t7 = 00000007
/* 009FC 809F8C4C 2401000F */ addiu $at, $zero, 0x000F ## $at = 0000000F
/* 00A00 809F8C50 AE0F0304 */ sw $t7, 0x0304($s0) ## 00000304
/* 00A04 809F8C54 17010003 */ bne $t8, $at, .L809F8C64
/* 00A08 809F8C58 E6060068 */ swc1 $f6, 0x0068($s0) ## 00000068
/* 00A0C 809F8C5C 24190024 */ addiu $t9, $zero, 0x0024 ## $t9 = 00000024
/* 00A10 809F8C60 A6190312 */ sh $t9, 0x0312($s0) ## 00000312
.L809F8C64:
/* 00A14 809F8C64 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 00A18 809F8C68 0C00BE0A */ jal Audio_PlayActorSound2
/* 00A1C 809F8C6C 2405389E */ addiu $a1, $zero, 0x389E ## $a1 = 0000389E
/* 00A20 809F8C70 3C0580A0 */ lui $a1, %hi(func_809F9C3C) ## $a1 = 80A00000
/* 00A24 809F8C74 24A59C3C */ addiu $a1, $a1, %lo(func_809F9C3C) ## $a1 = 809F9C3C
/* 00A28 809F8C78 0C27E094 */ jal func_809F8250
/* 00A2C 809F8C7C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 00A30 809F8C80 8FBF002C */ lw $ra, 0x002C($sp)
/* 00A34 809F8C84 8FB00028 */ lw $s0, 0x0028($sp)
/* 00A38 809F8C88 27BD0030 */ addiu $sp, $sp, 0x0030 ## $sp = 00000000
/* 00A3C 809F8C8C 03E00008 */ jr $ra
/* 00A40 809F8C90 00000000 */ nop
| 0 | 0.551951 | 1 | 0.551951 | game-dev | MEDIA | 0.979309 | game-dev | 0.632324 | 1 | 0.632324 |
bijington/orbit | 2,249 | engine/Orbit.Engine/GameObject.cs | using Microsoft.Maui.Graphics;
#if WINDOWS
using Microsoft.Maui.Graphics.Win2D;
#else
using Microsoft.Maui.Graphics.Platform;
#endif
namespace Orbit.Engine;
/// <summary>
/// Base class definition representing an object in a game.
/// </summary>
public abstract class GameObject : GameObjectContainer, IGameObject, IDrawable
{
private GameScene currentScene;
/// <inheritdoc />
public RectF Bounds { get; set; }
/// <inheritdoc />
public GameScene CurrentScene
{
get => this.currentScene;
set
{
if (this.currentScene != value)
{
this.currentScene = value;
this.UpdateCurrentScene();
}
}
}
void IDrawable.Draw(ICanvas canvas, RectF dirtyRect)
{
canvas.SaveState();
Render(canvas, dirtyRect);
canvas.RestoreState();
}
/// <summary>
/// Lifecycle method called to inform this <see cref="GameObject"/> that it has been added to a container and ultimately a game.
/// </summary>
/// <remarks>
/// Use this to perform any initialization that may be required when this <see cref="GameObject"/> is added.
/// </remarks>
public virtual void OnAdded()
{
}
/// <summary>
/// Lifecycle method called to inform this <see cref="GameObject"/> that it has been removed from a container and ultimately a game.
/// </summary>
/// <remarks>
/// Use this to tidy up any resource that may be required when this <see cref="GameObject"/> is removed from a container and most likely a game.
/// </remarks>
public virtual void OnRemoved()
{
}
/// <inheritdoc />
protected override void OnGameObjectAdded(GameObject gameObject)
{
base.OnGameObjectAdded(gameObject);
gameObject.CurrentScene = this.CurrentScene;
}
/// <inheritdoc />
protected override void OnGameObjectRemoved(GameObject gameObject)
{
base.OnGameObjectRemoved(gameObject);
gameObject.CurrentScene = null;
}
private void UpdateCurrentScene()
{
foreach (var gameObject in GameObjectsSnapshot)
{
gameObject.CurrentScene = this.CurrentScene;
}
}
}
| 0 | 0.805542 | 1 | 0.805542 | game-dev | MEDIA | 0.960409 | game-dev | 0.720372 | 1 | 0.720372 |
CalamityTeam/CalamityModPublic | 1,498 | Items/Materials/CoreofCalamity.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Items.Materials
{
public class CoreofCalamity : ModItem, ILocalizedModType
{
public new string LocalizationCategory => "Items.Materials";
public override void SetStaticDefaults()
{
Item.ResearchUnlockCount = 25;
ItemID.Sets.ItemNoGravity[Item.type] = true;
ItemID.Sets.SortingPriorityMaterials[Type] = 94; // Spectre Bar
}
public override void SetDefaults()
{
Item.width = 36;
Item.height = 36;
Item.maxStack = 9999;
Item.value = Item.sellPrice(gold: 4);
Item.rare = ItemRarityID.Yellow;
}
public override void PostDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, float rotation, float scale, int whoAmI)
{
Item.DrawItemGlowmaskSingleFrame(spriteBatch, rotation, ModContent.Request<Texture2D>("CalamityMod/Items/Materials/CoreofCalamityGlow").Value);
}
public override void AddRecipes()
{
CreateRecipe().
AddIngredient<CoreofSunlight>(3).
AddIngredient<CoreofEleum>(3).
AddIngredient<CoreofHavoc>(3).
AddIngredient<AshesofCalamity>().
AddTile(TileID.MythrilAnvil).
Register();
}
}
}
| 0 | 0.873155 | 1 | 0.873155 | game-dev | MEDIA | 0.974604 | game-dev | 0.646131 | 1 | 0.646131 |
Retera/WarsmashModEngine | 10,012 | core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/abilities/nightelf/moonwell/CAbilityMoonWell.java | package com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.nightelf.moonwell;
import com.badlogic.gdx.math.Rectangle;
import com.etheller.warsmash.units.GameObject;
import com.etheller.warsmash.util.War3ID;
import com.etheller.warsmash.util.WarsmashConstants;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CSimulation;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnit;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnitEnumFunction;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CWidget;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.autocast.AutocastType;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.autocast.CAutocastAbility;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.skills.CAbilitySpellBase;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.targeting.AbilityPointTarget;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.targeting.AbilityTarget;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.targeting.AbilityTargetVisitor;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.types.definitions.impl.AbilityFields;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.behaviors.CBehavior;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.data.CUnitRace;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.orders.OrderIds;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.trigger.enumtypes.CEffectType;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.util.AbilityTargetCheckReceiver;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.util.CommandStringErrorKeys;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.util.SimulationRenderComponentModel;
public class CAbilityMoonWell extends CAbilitySpellBase implements CAutocastAbility {
private boolean autoCastActive = false;
private SimulationRenderComponentModel waterRenderComponent;
private float manaGained;
private float hitPointsGained;
private float autocastRequirement;
private float waterHeight;
private boolean regenerateOnlyAtNight;
private boolean manaRegenActive = false;
private float baseManaRegen;
private int lastAutoCastCheckTick = 0;
private final Rectangle recycleRect = new Rectangle();
private float areaOfEffect;
public CAbilityMoonWell(final int handleId, final War3ID alias) {
super(handleId, alias);
}
@Override
public void onAdd(final CSimulation game, final CUnit unit) {
this.baseManaRegen = unit.getManaRegen();
unit.setManaRegen(0);
this.manaRegenActive = false;
}
@Override
public void onRemove(final CSimulation game, final CUnit unit) {
removeWaterRenderComponent();
enableManaRegen(unit);
}
@Override
public void onDeath(final CSimulation game, final CUnit cUnit) {
removeWaterRenderComponent();
}
private void disableManaRegen(final CUnit unit) {
if (this.manaRegenActive) {
unit.setManaRegen(0);
this.manaRegenActive = false;
}
}
private void enableManaRegen(final CUnit unit) {
if (!this.manaRegenActive) {
unit.setManaRegen(this.baseManaRegen);
this.manaRegenActive = true;
}
}
@Override
public void onTick(final CSimulation game, final CUnit unit) {
if (this.waterRenderComponent == null) {
if (!isDisabled()) {
final CUnitRace unitRace = unit.getUnitType().getRace();
this.waterRenderComponent = game.spawnSpellEffectOnPoint(unit.getX(), unit.getY(), 0, getAlias(),
CEffectType.EFFECT, unitRace.ordinal());
}
}
else {
if (isDisabled()) {
removeWaterRenderComponent();
}
else {
this.waterRenderComponent.setHeight(this.waterHeight * (unit.getMana() / unit.getMaximumMana()));
}
}
if (this.regenerateOnlyAtNight) {
if (game.isNight()) {
enableManaRegen(unit);
}
else {
disableManaRegen(unit);
}
}
if (this.autoCastActive) {
final int gameTurnTick = game.getGameTurnTick();
if (gameTurnTick >= this.lastAutoCastCheckTick && unit.getMana() > this.autocastRequirement) {
checkAutoCast(game, unit);
this.lastAutoCastCheckTick = gameTurnTick + (int) (2.0f / WarsmashConstants.SIMULATION_STEP_TIME);
}
}
super.onTick(game, unit);
}
private void removeWaterRenderComponent() {
if (this.waterRenderComponent != null) {
this.waterRenderComponent.remove();
this.waterRenderComponent = null;
}
}
private void checkAutoCast(final CSimulation game, final CUnit unit) {
final float castRange = getCastRange();
game.getWorldCollision().enumUnitsInRect(
this.recycleRect.set(unit.getX() - castRange, unit.getY() - castRange, castRange * 2, castRange * 2),
new CUnitEnumFunction() {
@Override
public boolean call(final CUnit enumUnit) {
if (unit.canReach(enumUnit, castRange)
&& enumUnit.canBeTargetedBy(game, unit, getTargetsAllowed())) {
unit.order(game, getBaseOrderId(), enumUnit);
}
return false;
}
});
}
@Override
public CBehavior begin(final CSimulation game, final CUnit caster, final int orderId, final CWidget target) {
final CUnit unitTarget = target.visit(AbilityTargetVisitor.UNIT);
if (unitTarget != null) {
final float life = unitTarget.getLife();
final int maximumLife = unitTarget.getMaximumLife();
final float mana = unitTarget.getMana();
final int maximumMana = unitTarget.getMaximumMana();
final float lifeWanted = life > maximumLife ? 0 : maximumLife - life;
final float manaWanted = mana > maximumMana ? 0 : maximumMana - mana;
float availableCasterMana = caster.getMana();
if (lifeWanted > 0 && availableCasterMana > 0) {
final float availableLifeOffered = availableCasterMana / this.hitPointsGained;
final float lifeGained = Math.min(availableLifeOffered, lifeWanted);
unitTarget.heal(game, lifeGained);
availableCasterMana -= lifeGained * this.hitPointsGained;
}
if (manaWanted > 0 && availableCasterMana > 0) {
final float availableManaOffered = availableCasterMana / this.manaGained;
final float manaGained = Math.min(availableManaOffered, manaWanted);
unitTarget.setMana(mana + manaGained);
availableCasterMana -= manaGained * this.manaGained;
}
if (availableCasterMana != caster.getMana()) {
caster.setMana(availableCasterMana);
game.createTemporarySpellEffectOnUnit(caster, getAlias(), CEffectType.CASTER);
game.createTemporarySpellEffectOnUnit(unitTarget, getAlias(), CEffectType.SPECIAL);
}
}
return caster.pollNextOrderBehavior(game);
}
@Override
public CBehavior begin(final CSimulation game, final CUnit caster, final int orderId,
final AbilityPointTarget point) {
return null;
}
@Override
public CBehavior beginNoTarget(final CSimulation game, final CUnit caster, final int orderId) {
return null;
}
@Override
public void populateData(final GameObject worldEditorAbility, final int level) {
this.manaGained = worldEditorAbility.getFieldAsFloat(AbilityFields.DATA_A + level, 0);
this.hitPointsGained = worldEditorAbility.getFieldAsFloat(AbilityFields.DATA_B + level, 0);
this.autocastRequirement = worldEditorAbility.getFieldAsFloat(AbilityFields.DATA_C + level, 0);
this.waterHeight = worldEditorAbility.getFieldAsFloat(AbilityFields.DATA_D + level, 0);
this.regenerateOnlyAtNight = worldEditorAbility.getFieldAsBoolean(AbilityFields.DATA_E + level, 0);
this.areaOfEffect = worldEditorAbility.getFieldAsFloat(AbilityFields.AREA_OF_EFFECT + level, 0);
setCastRange(this.areaOfEffect); // TODO use cast range as a smart right click interact radius
}
@Override
public boolean doEffect(final CSimulation simulation, final CUnit unit, final AbilityTarget target) {
return false;
}
@Override
protected void innerCheckCanTarget(final CSimulation game, final CUnit unit, final int orderId,
final CWidget target, final AbilityTargetCheckReceiver<CWidget> receiver) {
if (target.canBeTargetedBy(game, unit, getTargetsAllowed(), receiver)) {
if (!unit.isMovementDisabled() || unit.canReach(target, getCastRange())) {
receiver.targetOk(target);
}
else {
receiver.targetCheckFailed(CommandStringErrorKeys.TARGET_IS_OUTSIDE_RANGE);
}
}
}
@Override
protected void innerCheckCanTarget(final CSimulation game, final CUnit unit, final int orderId,
final AbilityPointTarget target, final AbilityTargetCheckReceiver<AbilityPointTarget> receiver) {
receiver.orderIdNotAccepted();
}
@Override
protected void innerCheckCanTargetNoTarget(final CSimulation game, final CUnit unit, final int orderId,
final AbilityTargetCheckReceiver<Void> receiver) {
receiver.orderIdNotAccepted();
}
@Override
public AutocastType getAutocastType() {
return AutocastType.NEARESTVALID;
}
@Override
public boolean isAutoCastOn() {
return this.autoCastActive;
}
@Override
public void setAutoCastOn(final CUnit caster, final boolean autoCastOn) {
this.autoCastActive = autoCastOn;
caster.setAutocastAbility(autoCastOn ? this : null);
}
@Override
public int getBaseOrderId() {
return OrderIds.replenish;
}
@Override
public int getAutoCastOnOrderId() {
return OrderIds.replenishon;
}
@Override
public int getAutoCastOffOrderId() {
return OrderIds.replenishoff;
}
@Override
public void setAutoCastOff() {
this.autoCastActive = false;
}
@Override
public void checkCanAutoTarget(CSimulation game, CUnit unit, int orderId, CWidget target,
AbilityTargetCheckReceiver<CWidget> receiver) {
this.checkCanTarget(game, unit, orderId, target, receiver);
}
@Override
public void checkCanAutoTarget(CSimulation game, CUnit unit, int orderId, AbilityPointTarget target,
AbilityTargetCheckReceiver<AbilityPointTarget> receiver) {
receiver.orderIdNotAccepted();
}
@Override
public void checkCanAutoTargetNoTarget(CSimulation game, CUnit unit, int orderId,
AbilityTargetCheckReceiver<Void> receiver) {
receiver.orderIdNotAccepted();
}
}
| 0 | 0.956011 | 1 | 0.956011 | game-dev | MEDIA | 0.98731 | game-dev | 0.975761 | 1 | 0.975761 |
emileb/OpenGames | 11,991 | opengames/src/main/jni/abuse-0.8/data/addon/pong/pong.lsp | ;;;; Copyright 1995 Crack dot Com, All Rights reserved
;;;; See licensing information for more details on usage rights
;;;; to play this game, go to the abuse root directory and type :
;;;; abuse -lsf addon/pong/pong.lsp
;;;; -lsf tells abuse to use an alternate Lisp Startup File than abuse.lsp
;;;; Notes :
;;;; This "game" was written by Jonathan Clark as a demonstration of the
;;;; capabilities of the abuse engine. It is not meant to be a complete game
;;;; and is released strictly for purpose of study only. Any part of this file
;;;; may be used by others and distributed in any form, but it uses some of the
;;;; lisp, sound effects, and artwork from Abuse (TM) which may only distributed
;;;; as a complete package with no files missing or changed.
;;;; ***** Emacs plug *********
;;;; If you don't already have emacs, get it! It's free.
;;;; Firstly it makes editing lisp 100% easier because it matches braces.
;;;; Secondly if you load the hi-lighting .el file you can read this file much
;;;; easier because all comments, strings, etc will be different colors.
;;;; I don't know the exact site where to find it, but if you telnet to
;;;; archie.unl.edu or look it up on a web search server you are sure to find it.
;;;; You might be interest to know emacs is also very customizable using a language
;;;; called lisp :-)
;;;; Please do not ask me for docs on how to code with the abuse engine, there are
;;;; none at this time and there won't be any until networked abuse is available.
;;;; ALL games written with the abuse engine are network ready with no additional
;;;; work including this one, but there are some issues that need addressing
;;;; that cannot be fully discussed until the net code is finished. When these
;;;; docs are written they will be available at http://www.crack.com Estimated
;;;; date for these docs is sometime late Oct. 1995
(perm-space) ; define all functions and global variable in "perm space" which
; is a space which will be garbage collected when it fills up.
; The down side to garbage collection is that it is a little slow
; and users of very slow machines will notice a very small pause
; from time to time, though writers of games may ignore this issue and
; always stay in "perm space"
;
; "tmp space" on the other hand, is not garbage collected, but rather
; at the end of executing an object's function will be completely
; thrown away it's important not to do a setq on a global variable
; (not local and not a member of the object) because the memory the
; item resides in will be lost after the function finishes.. see the
; add_score function in this file.
;; this is a simple check to see if they player has an engine version
;; capable of playing the game. All games should at least check for version 1.0
;; because all version before that are beta and have known bugs.
(if (< (+ (* (major_version) 100) (minor_version)) 100) ; require at least version 1.0
(progn
(print "Your engine is out of date. This game requires verion 1.0")
(quit)))
(setq pong_dir "addon/pong/") ; in case we change the location of these files later
; this is always a very good idea to do because the user of
; this program may/may not be able to install into this directory
(setq pong_art (concatenate 'string pong_dir "pong.spe")) ; all artwork is in this file
(setq load_warn nil) ; don't show a waringing if these files aren't there
(load "gamma.lsp") ; gamma correction values (if saved)
(setq load_warn T)
(load "addon/pong/common.lsp") ; grab the definition of abuse's light holder & obj mover
(load "addon/pong/userfuns.lsp") ; load seq defun
(load "lisp/input.lsp") ; get input mapping stuff from abuse
;; these are a few things that the engine requires you to load...
(load_big_font "art/letters.spe" "letters")
(load_small_font "art/letters.spe" "small_font")
(load_console_font "art/consfnt.spe" "fnt5x7")
(load_color_filter "art/back/backgrnd.spe")
(load_palette "art/back/backgrnd.spe")
(load_tiles pong_art) ; load all foreground & background type images from pong.spe
;; this is the image that will be displayed when the game starts
;; this needs to be in the form (X . Y) where X is the filename and
;; Y is the name of the image
(setq title_screen (cons pong_art "title_screen"))
;; define a few sound effects to be used (these are all from abuse)
(def_sound 'METAL "sfx/lasrmis2.wav")
(def_sound 'BHIT "sfx/delobj01.wav")
(def_sound 'BLOWUP "sfx/ball01.wav")
(def_sound 'BUTTON_PRESS_SND "sfx/button02.wav") ; used by menu system
;; use these images to draw the score
(setq nums (make-array 10 :initial-contents (list (def_image pong_art "0")
(def_image pong_art "1")
(def_image pong_art "2")
(def_image pong_art "3")
(def_image pong_art "4")
(def_image pong_art "5")
(def_image pong_art "6")
(def_image pong_art "7")
(def_image pong_art "8")
(def_image pong_art "9"))))
(setq score 0)
(defun show_score (x y digs_left score)
(if (not (eq digs_left 0)) ; end recursion
(let ((this-digit (/ score digs_left)))
(put_image x y (aref nums this-digit))
(show_score (+ x (image_width (aref nums this-digit))) y
(/ digs_left 10) (- score (* digs_left this-digit))))))
(defun paddle_draw ()
(draw) ; normal draw function
(show_score (- (view_x2) 80) (view_y1) 1000000 score))
(defun add_score (amount)
(perm-space) ; we are modifing a global var, so we need swith to perm space
(setq score (+ score amount))
(tmp-space)) ; switch back to tmp space which is not garbage collected
(defun destroyable_tile (x) (> x 1))
(defun blow_up_tile (tilex tiley)
(let ((gamex (+ (* tilex 16) 8))
(gamey (+ (* tiley 7) 7)))
(add_score 200)
(add_object EXPLOSION gamex gamey)
(destroy_tile tilex tiley)))
(defun destroy_tile (tilex tiley)
(let ((gamex (+ (* tilex 16) 8))
(gamey (+ (* tiley 7) 7))
(type (fg_tile tilex tiley)))
(add_score 100)
(set_fg_tile tilex tiley 0) ; clear the tile and start animation
(if (eq type 6) ; dinamite tile?
(progn
(blow_up_tile tilex tiley)
(if (and (> tilex 0))
(blow_up_tile (- tilex 1) tiley))
(if (and (> tiley 0))
(blow_up_tile tilex (- tiley 1)))
(blow_up_tile tilex (+ tiley 1))
(blow_up_tile (+ tilex 1) tiley)))
(with_object (bg) (add_hp 10)) ; give player points
(add_object TILE_BLOW_UP gamex gamey)
(if (eq (random 10) 0)
(add_object PILL1 gamex gamey)
(if (eq (random 30) 0)
(add_object PILL2 gamex gamey)))))
(defun check_collide (status) ;; returns T if we hit something
(if (not (eq status T)) ; did we hit anything?
(if (eq (car (cdr status)) 'object) ; did we hit an object?
(let ((object (car (cdr (cdr status)))))
(if (eq (with_object object (otype)) PADDLE) ; did we hit the paddle?
(if (<= (aistate) 180)
(progn
(set_aistate (+ (aistate) (- (with_object object (x)) (x))))
(if (> 20 (aistate)) (set_aistate 20)
(if (< 160 (aistate)) (set_aistate 160)))
T)
nil)
nil)
nil)
(if (eq (car (cdr status)) 'tile) ; did we hit a tile?
(let ((tilex (car (cdr (cdr status))))
(tiley (car (cdr (cdr (cdr status))))))
(let ((type (fg_tile tilex tiley)))
(if (destroyable_tile type) ; can we destroy the tile?
(progn
(destroy_tile tilex tiley)
(if (eq type 6)
(play_sound BLOWUP 100)
(play_sound BHIT)))
(play_sound METAL 60)))
T)
nil))
nil))
(defun move_ball () ;; returns status of move
(let ((status (float_tick)))
(if (not (eq status T)) ; T means we did not hit anything
(let ((block_flags (car status)))
(if (or (blocked_left block_flags) (blocked_right block_flags)) ; bounce left/right
(if (<= (aistate) 180)
(set_aistate (- 180 (aistate)))
(set_aistate (+ 180 (- 360 (aistate))))))
(if (or (blocked_up block_flags) (blocked_down block_flags)) ; bounce up/down
(progn
(if (<= (aistate) 180)
(set_aistate (mod (+ (- 180 (aistate)) 180) 360))
(set_aistate (- 360 (aistate))))
))
(if (not (eq block_flags 0)) ; move the ball one tick, because we just bounced
(progn
(set_course (aistate) 7)
(float_tick)))))
status))
(defun ball_ai ()
(set_course (aistate) 7)
(select (aitype)
(0 ; normal play, bounce around and stuff..
(check_collide (move_ball))
(if (> (y) 240) ; check to see if we are dead
(progn
(if (> score 500)
(add_score -500))
(if (find_closest BALL) ; don't regenerate if other balls exsist
nil
(progn
(set_aistate 90) ; reset ball to 90 degree angle
(set_fade_count 15)
(set_aitype 1)
T)))
T))
(1 ; ball is dead - go to paddle and fade in
(set_x (with_object (bg) (x)))
(set_y (- (with_object (bg) (y)) 14))
(set_fade_count (- (fade_count) 1))
(if (eq (fade_count) 0)
(set_aitype 0))
T)))
(def_char BALL
(funs (ai_fun ball_ai))
(flags (hurt_all T))
(range 100 100) ; make sure ball doesn't stop when off screen
(states pong_art (stopped "ball")))
(defun paddle_mover (xm ym but)
(print xm)
(set_gravity 0)
(set_shift_down (me) 80)
(set_shift_right (me) (- 0 (x))) ; adjust screen shift so it doesn't scroll
(if (> fire_delay 0)
(setq fire_delay (- fire_delay 1))
(if (> shooting_time 0)
(progn
(add_object MISSLE (x) (- (y) 20))
(setq fire_delay 5)
(setq shooting_time (- shooting_time 1)))))
(if (or (and (< xm 0) (> (x) 20)) (and (> xm 0) (< (x) 300)))
(mover xm 0 0)
0))
(def_char PADDLE
(vars shooting_time fire_delay)
(funs (move_fun paddle_mover) ; move fun get's passed the player input and responsible for calling ai_fun
(draw_fun paddle_draw))
(abilities (walk_top_speed 8)
(start_accel 8))
(flags (can_block T))
(states pong_art (stopped "big_paddle")))
(defun do_nothing () T)
(def_char START
(funs (draw_fun dev_draw) ; dev draw is a compiled fun
(ai_fun do_nothing)) ; always return T, therefore it never "dies"
(states pong_art (stopped "start")))
(def_char TILE_BLOW_UP
(funs (ai_fun block_ai))
(states pong_art (stopped (seq "block_die" 1 9))))
(defun pill1_ai ()
(set_y (+ (y) 3))
(next_picture)
(if (touching_bg) ; are we touching the paddle
(progn
(add_score 1000)
(with_object (add_object BALL (x) (y) 1) (progn (set_fade_count 15) (set_aistate 80)))
nil)
(> 240 (y))))
(defun pill2_ai ()
(set_y (+ (y) 3))
(next_picture)
(if (touching_bg) ; are we touching the paddle?
(progn
(add_score 300)
(with_object (bg) (setq shooting_time 20)) ; give 'em a 20 ticks of fire power
nil)
(> 240 (y))))
(def_char PILL1 ; the extra ball pill
(funs (ai_fun pill1_ai))
(states pong_art (stopped (seq "pill" 1 24))))
(def_char PILL2 ; the extra ball pill
(funs (ai_fun pill2_ai))
(states pong_art (stopped (seq "pill2" 1 24))))
(defun missle_ai ()
(set_course 90 10)
(not (check_collide (move_ball))))
(def_char MISSLE
(funs (ai_fun missle_ai))
(states pong_art (stopped "missle")))
(defun block_ai () (next_picture))
(def_char EXPLOSION
(funs (ai_fun block_ai))
(states pong_art (stopped (seq "exp" 1 10))))
(setq current_level 1)
(defun get_level_name (num)
(concatenate 'string pong_dir "pong" (digstr num 2) ".lvl"))
(create_players PADDLE)
(set_first_level (get_level_name current_level))
(gc) ; garbage collect
(tmp-space)
| 0 | 0.881289 | 1 | 0.881289 | game-dev | MEDIA | 0.87251 | game-dev | 0.973785 | 1 | 0.973785 |
uni-due-syssec/efcf-framework | 17,646 | data/cov-max-testset/0x8e48f1fd56abd20d86bfb995f4b7ef1eb4f32d1c.sol | pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract SkinBase is Pausable {
struct Skin {
uint128 appearance;
uint64 cooldownEndTime;
uint64 mixingWithId;
}
// All skins, mapping from skin id to skin apprance
mapping (uint256 => Skin) skins;
// Mapping from skin id to owner
mapping (uint256 => address) public skinIdToOwner;
// Whether a skin is on sale
mapping (uint256 => bool) public isOnSale;
// Number of all total valid skins
// skinId 0 should not correspond to any skin, because skin.mixingWithId==0 indicates not mixing
uint256 public nextSkinId = 1;
// Number of skins an account owns
mapping (address => uint256) public numSkinOfAccounts;
// // Give some skins to init account for unit tests
// function SkinBase() public {
// address account0 = 0x627306090abaB3A6e1400e9345bC60c78a8BEf57;
// address account1 = 0xf17f52151EbEF6C7334FAD080c5704D77216b732;
// // Create simple skins
// Skin memory skin = Skin({appearance: 0, cooldownEndTime:0, mixingWithId: 0});
// for (uint256 i = 1; i <= 15; i++) {
// if (i < 10) {
// skin.appearance = uint128(i);
// if (i < 7) {
// skinIdToOwner[i] = account0;
// numSkinOfAccounts[account0] += 1;
// } else {
// skinIdToOwner[i] = account1;
// numSkinOfAccounts[account1] += 1;
// }
// } else {
// skin.appearance = uint128(block.blockhash(block.number - i + 9));
// skinIdToOwner[i] = account1;
// numSkinOfAccounts[account1] += 1;
// }
// skins[i] = skin;
// isOnSale[i] = false;
// nextSkinId += 1;
// }
// }
// Get the i-th skin an account owns, for off-chain usage only
function skinOfAccountById(address account, uint256 id) external view returns (uint256) {
uint256 count = 0;
uint256 numSkinOfAccount = numSkinOfAccounts[account];
require(numSkinOfAccount > 0);
require(id < numSkinOfAccount);
for (uint256 i = 1; i < nextSkinId; i++) {
if (skinIdToOwner[i] == account) {
// This skin belongs to current account
if (count == id) {
// This is the id-th skin of current account, a.k.a, what we need
return i;
}
count++;
}
}
revert();
}
// Get skin by id
function getSkin(uint256 id) public view returns (uint128, uint64, uint64) {
require(id > 0);
require(id < nextSkinId);
Skin storage skin = skins[id];
return (skin.appearance, skin.cooldownEndTime, skin.mixingWithId);
}
function withdrawETH() external onlyOwner {
owner.transfer(this.balance);
}
}
contract MixFormulaInterface {
function calcNewSkinAppearance(uint128 x, uint128 y) public pure returns (uint128);
// create random appearance
function randomSkinAppearance() public view returns (uint128);
// bleach
function bleachAppearance(uint128 appearance, uint128 attributes) public pure returns (uint128);
}
contract SkinMix is SkinBase {
// Mix formula
MixFormulaInterface public mixFormula;
// Pre-paid ether for synthesization, will be returned to user if the synthesization failed (minus gas).
uint256 public prePaidFee = 2500000 * 5000000000; // (0.15million gas * 5 gwei)
// Events
event MixStart(address account, uint256 skinAId, uint256 skinBId);
event AutoMix(address account, uint256 skinAId, uint256 skinBId, uint64 cooldownEndTime);
event MixSuccess(address account, uint256 skinId, uint256 skinAId, uint256 skinBId);
// Set mix formula contract address
function setMixFormulaAddress(address mixFormulaAddress) external onlyOwner {
mixFormula = MixFormulaInterface(mixFormulaAddress);
}
// setPrePaidFee: set advance amount, only owner can call this
function setPrePaidFee(uint256 newPrePaidFee) external onlyOwner {
prePaidFee = newPrePaidFee;
}
// _isCooldownReady: check whether cooldown period has been passed
function _isCooldownReady(uint256 skinAId, uint256 skinBId) private view returns (bool) {
return (skins[skinAId].cooldownEndTime <= uint64(now)) && (skins[skinBId].cooldownEndTime <= uint64(now));
}
// _isNotMixing: check whether two skins are in another mixing process
function _isNotMixing(uint256 skinAId, uint256 skinBId) private view returns (bool) {
return (skins[skinAId].mixingWithId == 0) && (skins[skinBId].mixingWithId == 0);
}
// _setCooldownTime: set new cooldown time
function _setCooldownEndTime(uint256 skinAId, uint256 skinBId) private {
uint256 end = now + 5 minutes;
// uint256 end = now;
skins[skinAId].cooldownEndTime = uint64(end);
skins[skinBId].cooldownEndTime = uint64(end);
}
// _isValidSkin: whether an account can mix using these skins
// Make sure two things:
// 1. these two skins do exist
// 2. this account owns these skins
function _isValidSkin(address account, uint256 skinAId, uint256 skinBId) private view returns (bool) {
// Make sure those two skins belongs to this account
if (skinAId == skinBId) {
return false;
}
if ((skinAId == 0) || (skinBId == 0)) {
return false;
}
if ((skinAId >= nextSkinId) || (skinBId >= nextSkinId)) {
return false;
}
return (skinIdToOwner[skinAId] == account) && (skinIdToOwner[skinBId] == account);
}
// _isNotOnSale: whether a skin is not on sale
function _isNotOnSale(uint256 skinId) private view returns (bool) {
return (isOnSale[skinId] == false);
}
// mix
function mix(uint256 skinAId, uint256 skinBId) public whenNotPaused {
// Check whether skins are valid
require(_isValidSkin(msg.sender, skinAId, skinBId));
// Check whether skins are neither on sale
require(_isNotOnSale(skinAId) && _isNotOnSale(skinBId));
// Check cooldown
require(_isCooldownReady(skinAId, skinBId));
// Check these skins are not in another process
require(_isNotMixing(skinAId, skinBId));
// Set new cooldown time
_setCooldownEndTime(skinAId, skinBId);
// Mark skins as in mixing
skins[skinAId].mixingWithId = uint64(skinBId);
skins[skinBId].mixingWithId = uint64(skinAId);
// Emit MixStart event
MixStart(msg.sender, skinAId, skinBId);
}
// Mixing auto
function mixAuto(uint256 skinAId, uint256 skinBId) public payable whenNotPaused {
require(msg.value >= prePaidFee);
mix(skinAId, skinBId);
Skin storage skin = skins[skinAId];
AutoMix(msg.sender, skinAId, skinBId, skin.cooldownEndTime);
}
// Get mixing result, return the resulted skin id
function getMixingResult(uint256 skinAId, uint256 skinBId) public whenNotPaused {
// Check these two skins belongs to the same account
address account = skinIdToOwner[skinAId];
require(account == skinIdToOwner[skinBId]);
// Check these two skins are in the same mixing process
Skin storage skinA = skins[skinAId];
Skin storage skinB = skins[skinBId];
require(skinA.mixingWithId == uint64(skinBId));
require(skinB.mixingWithId == uint64(skinAId));
// Check cooldown
require(_isCooldownReady(skinAId, skinBId));
// Create new skin
uint128 newSkinAppearance = mixFormula.calcNewSkinAppearance(skinA.appearance, skinB.appearance);
Skin memory newSkin = Skin({appearance: newSkinAppearance, cooldownEndTime: uint64(now), mixingWithId: 0});
skins[nextSkinId] = newSkin;
skinIdToOwner[nextSkinId] = account;
isOnSale[nextSkinId] = false;
nextSkinId++;
// Clear old skins
skinA.mixingWithId = 0;
skinB.mixingWithId = 0;
// In order to distinguish created skins in minting with destroyed skins
// skinIdToOwner[skinAId] = owner;
// skinIdToOwner[skinBId] = owner;
delete skinIdToOwner[skinAId];
delete skinIdToOwner[skinBId];
// require(numSkinOfAccounts[account] >= 2);
numSkinOfAccounts[account] -= 1;
MixSuccess(account, nextSkinId - 1, skinAId, skinBId);
}
}
contract SkinMarket is SkinMix {
// Cut ratio for a transaction
// Values 0-10,000 map to 0%-100%
uint128 public trCut = 290;
// Sale orders list
mapping (uint256 => uint256) public desiredPrice;
// events
event PutOnSale(address account, uint256 skinId);
event WithdrawSale(address account, uint256 skinId);
event BuyInMarket(address buyer, uint256 skinId);
// functions
// Put asset on sale
function putOnSale(uint256 skinId, uint256 price) public whenNotPaused {
// Only owner of skin pass
require(skinIdToOwner[skinId] == msg.sender);
// Check whether skin is mixing
require(skins[skinId].mixingWithId == 0);
// Check whether skin is already on sale
require(isOnSale[skinId] == false);
require(price > 0);
// Put on sale
desiredPrice[skinId] = price;
isOnSale[skinId] = true;
// Emit the Approval event
PutOnSale(msg.sender, skinId);
}
// Withdraw an sale order
function withdrawSale(uint256 skinId) external whenNotPaused {
// Check whether this skin is on sale
require(isOnSale[skinId] == true);
// Can only withdraw self's sale
require(skinIdToOwner[skinId] == msg.sender);
// Withdraw
isOnSale[skinId] = false;
desiredPrice[skinId] = 0;
// Emit the cancel event
WithdrawSale(msg.sender, skinId);
}
// Buy skin in market
function buyInMarket(uint256 skinId) external payable whenNotPaused {
// Check whether this skin is on sale
require(isOnSale[skinId] == true);
address seller = skinIdToOwner[skinId];
// Check the sender isn't the seller
require(msg.sender != seller);
uint256 _price = desiredPrice[skinId];
// Check whether pay value is enough
require(msg.value >= _price);
// Cut and then send the proceeds to seller
uint256 sellerProceeds = _price - _computeCut(_price);
seller.transfer(sellerProceeds);
// Transfer skin from seller to buyer
numSkinOfAccounts[seller] -= 1;
skinIdToOwner[skinId] = msg.sender;
numSkinOfAccounts[msg.sender] += 1;
isOnSale[skinId] = false;
desiredPrice[skinId] = 0;
// Emit the buy event
BuyInMarket(msg.sender, skinId);
}
// Compute the marketCut
function _computeCut(uint256 _price) internal view returns (uint256) {
return _price * trCut / 10000;
}
}
contract SkinMinting is SkinMarket {
// Limits the number of skins the contract owner can ever create.
uint256 public skinCreatedLimit = 50000;
// The summon numbers of each accouts: will be cleared every day
mapping (address => uint256) public accoutToSummonNum;
// Pay level of each accouts
mapping (address => uint256) public accoutToPayLevel;
mapping (address => uint256) public accountsLastClearTime;
uint256 public levelClearTime = now;
// price
uint256 public baseSummonPrice = 3 finney;
uint256 public bleachPrice = 30 finney;
// Pay level
uint256[5] public levelSplits = [10,
20,
50,
100,
200];
uint256[6] public payMultiple = [1,
2,
4,
8,
20,
100];
// events
event CreateNewSkin(uint256 skinId, address account);
event Bleach(uint256 skinId, uint128 newAppearance);
// functions
// Set price
function setBaseSummonPrice(uint256 newPrice) external onlyOwner {
baseSummonPrice = newPrice;
}
function setBleachPrice(uint256 newPrice) external onlyOwner {
bleachPrice = newPrice;
}
// Create base skin for sell. Only owner can create
function createSkin(uint128 specifiedAppearance, uint256 salePrice) external onlyOwner whenNotPaused {
require(numSkinOfAccounts[owner] < skinCreatedLimit);
// Create specified skin
// uint128 randomAppearance = mixFormula.randomSkinAppearance();
Skin memory newSkin = Skin({appearance: specifiedAppearance, cooldownEndTime: uint64(now), mixingWithId: 0});
skins[nextSkinId] = newSkin;
skinIdToOwner[nextSkinId] = owner;
isOnSale[nextSkinId] = false;
// Emit the create event
CreateNewSkin(nextSkinId, owner);
// Put this skin on sale
putOnSale(nextSkinId, salePrice);
nextSkinId++;
numSkinOfAccounts[owner] += 1;
}
// Summon
function summon() external payable whenNotPaused {
// Clear daily summon numbers
if (accountsLastClearTime[msg.sender] == uint256(0)) {
// This account's first time to summon, we do not need to clear summon numbers
accountsLastClearTime[msg.sender] = now;
} else {
if (accountsLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) {
accoutToSummonNum[msg.sender] = 0;
accoutToPayLevel[msg.sender] = 0;
accountsLastClearTime[msg.sender] = now;
}
}
uint256 payLevel = accoutToPayLevel[msg.sender];
uint256 price = payMultiple[payLevel] * baseSummonPrice;
require(msg.value >= price);
// Create random skin
uint128 randomAppearance = mixFormula.randomSkinAppearance();
// uint128 randomAppearance = 0;
Skin memory newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0});
skins[nextSkinId] = newSkin;
skinIdToOwner[nextSkinId] = msg.sender;
isOnSale[nextSkinId] = false;
// Emit the create event
CreateNewSkin(nextSkinId, msg.sender);
nextSkinId++;
numSkinOfAccounts[msg.sender] += 1;
accoutToSummonNum[msg.sender] += 1;
// Handle the paylevel
if (payLevel < 5) {
if (accoutToSummonNum[msg.sender] >= levelSplits[payLevel]) {
accoutToPayLevel[msg.sender] = payLevel + 1;
}
}
}
// Bleach some attributes
function bleach(uint128 skinId, uint128 attributes) external payable whenNotPaused {
// Check whether msg.sender is owner of the skin
require(msg.sender == skinIdToOwner[skinId]);
// Check whether this skin is on sale
require(isOnSale[skinId] == false);
// Check whether there is enough money
require(msg.value >= bleachPrice);
Skin storage originSkin = skins[skinId];
// Check whether this skin is in mixing
require(originSkin.mixingWithId == 0);
uint128 newAppearance = mixFormula.bleachAppearance(originSkin.appearance, attributes);
originSkin.appearance = newAppearance;
// Emit bleach event
Bleach(skinId, newAppearance);
}
// Our daemon will clear daily summon numbers
function clearSummonNum() external onlyOwner {
uint256 nextDay = levelClearTime + 1 days;
if (now > nextDay) {
levelClearTime = nextDay;
}
}
} | 0 | 0.680548 | 1 | 0.680548 | game-dev | MEDIA | 0.749494 | game-dev | 0.687888 | 1 | 0.687888 |
McKay42/McEngine | 2,944 | McEngine/libraries/bullet/include/BulletDynamics/ConstraintSolver/btNNCGConstraintSolver.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_NNCG_CONSTRAINT_SOLVER_H
#define BT_NNCG_CONSTRAINT_SOLVER_H
#include "btSequentialImpulseConstraintSolver.h"
ATTRIBUTE_ALIGNED16(class) btNNCGConstraintSolver : public btSequentialImpulseConstraintSolver
{
protected:
btScalar m_deltafLengthSqrPrev;
btAlignedObjectArray<btScalar> m_pNC; // p for None Contact constraints
btAlignedObjectArray<btScalar> m_pC; // p for Contact constraints
btAlignedObjectArray<btScalar> m_pCF; // p for ContactFriction constraints
btAlignedObjectArray<btScalar> m_pCRF; // p for ContactRollingFriction constraints
//These are recalculated in every iterations. We just keep these to prevent reallocation in each iteration.
btAlignedObjectArray<btScalar> m_deltafNC; // deltaf for NoneContact constraints
btAlignedObjectArray<btScalar> m_deltafC; // deltaf for Contact constraints
btAlignedObjectArray<btScalar> m_deltafCF; // deltaf for ContactFriction constraints
btAlignedObjectArray<btScalar> m_deltafCRF; // deltaf for ContactRollingFriction constraints
protected:
virtual btScalar solveGroupCacheFriendlyFinish(btCollisionObject** bodies,int numBodies,const btContactSolverInfo& infoGlobal);
virtual btScalar solveSingleIteration(int iteration, btCollisionObject** bodies ,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer);
virtual btScalar solveGroupCacheFriendlySetup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer);
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btNNCGConstraintSolver() : btSequentialImpulseConstraintSolver(), m_onlyForNoneContact(false) {}
virtual btConstraintSolverType getSolverType() const
{
return BT_NNCG_SOLVER;
}
bool m_onlyForNoneContact;
};
#endif //BT_NNCG_CONSTRAINT_SOLVER_H
| 0 | 0.78168 | 1 | 0.78168 | game-dev | MEDIA | 0.993226 | game-dev | 0.786099 | 1 | 0.786099 |
AngelicPretty/Gshine-Server | 4,243 | src/main/java/emu/grasscutter/game/home/GameHome.java | package emu.grasscutter.game.home;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexed;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.HomeWorldLevelData;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.packet.send.*;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Entity(value = "homes", useDiscriminator = false)
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
@Builder(builderMethodName = "of")
public class GameHome {
@Id
String id;
@Indexed(options = @IndexOptions(unique = true))
long ownerUid;
@Transient Player player;
int level;
int exp;
List<FurnitureMakeSlotItem> furnitureMakeSlotItemList;
ConcurrentHashMap<Integer, HomeSceneItem> sceneMap;
Set<Integer> unlockedHomeBgmList;
int enterHomeOption;
public void save() {
DatabaseHelper.saveHome(this);
}
public static GameHome getByUid(Integer uid) {
var home = DatabaseHelper.getHomeByUid(uid);
if (home == null) {
home = GameHome.create(uid);
}
return home;
}
public static GameHome create(Integer uid) {
return GameHome.of()
.ownerUid(uid)
.level(1)
.sceneMap(new ConcurrentHashMap<>())
.unlockedHomeBgmList(new HashSet<>())
.build();
}
public HomeSceneItem getHomeSceneItem(int sceneId) {
return sceneMap.computeIfAbsent(sceneId, e -> {
var defaultItem = GameData.getHomeworldDefaultSaveData().get(sceneId);
if (defaultItem != null) {
Grasscutter.getLogger().info("Set player {} home {} to initial setting", ownerUid, sceneId);
return HomeSceneItem.parseFrom(defaultItem, sceneId);
}
return null;
});
}
public void onOwnerLogin(Player player) {
if (this.player == null)
this.player = player;
player.getSession().send(new PacketHomeBasicInfoNotify(player, false));
player.getSession().send(new PacketPlayerHomeCompInfoNotify(player));
player.getSession().send(new PacketHomeComfortInfoNotify(player));
player.getSession().send(new PacketFurnitureCurModuleArrangeCountNotify());
player.getSession().send(new PacketHomeMarkPointNotify(player));
player.getSession().send(new PacketHomeAllUnlockedBgmIdListNotify(player));
}
public Player getPlayer() {
if (this.player == null)
this.player = Grasscutter.getGameServer().getPlayerByUid((int) this.ownerUid, true);
return this.player;
}
public HomeWorldLevelData getLevelData() {
return GameData.getHomeWorldLevelDataMap().get(level);
}
public boolean addUnlockedHomeBgm(int homeBgmId) {
if (!getUnlockedHomeBgmList().add(homeBgmId)) return false;
var player = this.getPlayer();
player.sendPacket(new PacketHomeNewUnlockedBgmIdListNotify(homeBgmId));
player.sendPacket(new PacketHomeAllUnlockedBgmIdListNotify(player));
save();
return true;
}
public Set<Integer> getUnlockedHomeBgmList() {
if (this.unlockedHomeBgmList == null) {
this.unlockedHomeBgmList = new HashSet<>();
}
if (this.unlockedHomeBgmList.addAll(getDefaultUnlockedHomeBgmIds())) {
save();
}
return this.unlockedHomeBgmList;
}
private Set<Integer> getDefaultUnlockedHomeBgmIds() {
return GameData.getHomeWorldBgmDataMap().int2ObjectEntrySet().stream()
.filter(e -> e.getValue().isDefaultUnlock())
.map(Int2ObjectMap.Entry::getIntKey)
.collect(Collectors.toUnmodifiableSet());
}
}
| 0 | 0.882632 | 1 | 0.882632 | game-dev | MEDIA | 0.634957 | game-dev | 0.974937 | 1 | 0.974937 |
SDraw/ml_mods_vrc | 3,039 | ml_abp/Settings.cs | namespace ml_abp
{
static class Settings
{
static MelonLoader.MelonPreferences_Entry<bool> ms_friendsEntry = null;
static bool ms_settingsUpdated = false;
static bool ms_setingsUpdatedFriends = false; // Separated because components aren't that cheap
static bool ms_allowFriends = true;
static float ms_proximityDistance = 0.25f;
static float ms_playersDistance = 5f;
static bool ms_customTargets = false;
public static void LoadSettings()
{
MelonLoader.MelonPreferences.CreateCategory("ABP", "Avatar Bones Proximity");
ms_friendsEntry = MelonLoader.MelonPreferences.CreateEntry("ABP", "AllowFriends", true, "Allow proximity check for friends");
ms_friendsEntry.OnValueChanged += OnAnyEntryUpdate;
ms_friendsEntry.OnValueChanged += OnFriendsEntryUpdate;
MelonLoader.MelonPreferences.CreateEntry("ABP", "ProximityDistance", 0.25f, "Proximity distance to bones").OnValueChanged += OnAnyEntryUpdate;
MelonLoader.MelonPreferences.CreateEntry("ABP", "PlayersDistance", 5f, "Proximity distance to players").OnValueChanged += OnAnyEntryUpdate;
MelonLoader.MelonPreferences.CreateEntry("ABP", "CustomTargets", ms_customTargets, "Use custom proximity targets (avatar reload required)").OnValueChanged += OnAnyEntryUpdate;
ReloadSettings();
}
public static void ReloadSettings()
{
ms_allowFriends = ms_friendsEntry.Value;
ms_proximityDistance = UnityEngine.Mathf.Clamp(MelonLoader.MelonPreferences.GetEntryValue<float>("ABP", "ProximityDistance"), 0.000001f, float.MaxValue);
MelonLoader.MelonPreferences.SetEntryValue("ABP", "ProximityDistance", ms_proximityDistance);
ms_playersDistance = MelonLoader.MelonPreferences.GetEntryValue<float>("ABP", "PlayersDistance");
ms_customTargets = MelonLoader.MelonPreferences.GetEntryValue<bool>("ABP", "CustomTargets");
}
static void OnAnyEntryUpdate<T>(T p_oldValue, T p_newValue) => ms_settingsUpdated = true;
public static bool IsAnyEntryUpdated()
{
bool l_result = ms_settingsUpdated;
ms_settingsUpdated = false;
return l_result;
}
static void OnFriendsEntryUpdate(bool p_oldValue, bool p_newValue) => ms_setingsUpdatedFriends = true;
public static bool IsFriendsEntryUpdated()
{
bool l_result = ms_setingsUpdatedFriends;
ms_setingsUpdatedFriends = false;
return l_result;
}
public static bool AllowFriends
{
get => ms_allowFriends;
}
public static float ProximityDistance
{
get => ms_proximityDistance;
}
public static float PlayersDistance
{
get => ms_playersDistance;
}
public static bool CustomTargets
{
get => ms_customTargets;
}
}
}
| 0 | 0.622141 | 1 | 0.622141 | game-dev | MEDIA | 0.410392 | game-dev | 0.690616 | 1 | 0.690616 |
BeiShanair/TutorialMod-1.20.1 | 4,061 | src/main/java/com/besson/tutorial/world/ModConfiguredFeatures.java | package com.besson.tutorial.world;
import com.besson.tutorial.TutorialMod;
import com.besson.tutorial.block.ModBlocks;
import net.minecraft.block.Blocks;
import net.minecraft.registry.Registerable;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.tag.BlockTags;
import net.minecraft.structure.rule.BlockMatchRuleTest;
import net.minecraft.structure.rule.RuleTest;
import net.minecraft.structure.rule.TagMatchRuleTest;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.intprovider.ConstantIntProvider;
import net.minecraft.world.gen.feature.*;
import net.minecraft.world.gen.feature.size.TwoLayersFeatureSize;
import net.minecraft.world.gen.foliage.BlobFoliagePlacer;
import net.minecraft.world.gen.stateprovider.BlockStateProvider;
import net.minecraft.world.gen.trunk.StraightTrunkPlacer;
import java.util.List;
public class ModConfiguredFeatures {
public static final RegistryKey<ConfiguredFeature<?, ?>> ICE_ETHER_TREE_KEY = of("ice_ether_tree");
public static final RegistryKey<ConfiguredFeature<?, ?>> SIMPLE_FLOWER_KEY = of("simple_flower");
public static final RegistryKey<ConfiguredFeature<?, ?>> ICE_ETHER_ORE_KEY = of("ice_ether_ore");
public static final RegistryKey<ConfiguredFeature<?, ?>> NETHER_ICE_ETHER_ORE_KEY = of("nether_ice_ether_ore");
public static final RegistryKey<ConfiguredFeature<?, ?>> END_ICE_ETHER_ORE_KEY = of("end_ice_ether_ore");
public static void bootstrap(Registerable<ConfiguredFeature<?, ?>> featureRegisterable) {
ConfiguredFeatures.register(featureRegisterable, ICE_ETHER_TREE_KEY, Feature.TREE,
new TreeFeatureConfig.Builder(
BlockStateProvider.of(ModBlocks.ICE_ETHER_LOG),
new StraightTrunkPlacer(4,2,1),
BlockStateProvider.of(ModBlocks.ICE_ETHER_LEAVES),
new BlobFoliagePlacer(ConstantIntProvider.create(3), ConstantIntProvider.create(2), 3),
new TwoLayersFeatureSize(1, 0, 2)
).build());
ConfiguredFeatures.register(featureRegisterable, SIMPLE_FLOWER_KEY, Feature.FLOWER,
new RandomPatchFeatureConfig(20, 4, 3,
PlacedFeatures.createEntry(Feature.SIMPLE_BLOCK,
new SimpleBlockFeatureConfig(BlockStateProvider.of(ModBlocks.SIMPLE_FLOWER)))));
RuleTest stoneReplace = new TagMatchRuleTest(BlockTags.STONE_ORE_REPLACEABLES);
RuleTest deepslateReplace = new TagMatchRuleTest(BlockTags.DEEPSLATE_ORE_REPLACEABLES);
RuleTest netherReplace = new TagMatchRuleTest(BlockTags.BASE_STONE_NETHER);
RuleTest endReplace = new BlockMatchRuleTest(Blocks.END_STONE);
List<OreFeatureConfig.Target> overWorldTarget = List.of(
OreFeatureConfig.createTarget(stoneReplace, ModBlocks.ICE_ETHER_ORE.getDefaultState()),
OreFeatureConfig.createTarget(deepslateReplace, ModBlocks.ICE_ETHER_ORE.getDefaultState())
);
List<OreFeatureConfig.Target> netherTarget = List.of(
OreFeatureConfig.createTarget(netherReplace, ModBlocks.ICE_ETHER_ORE.getDefaultState())
);
List<OreFeatureConfig.Target> endTarget = List.of(
OreFeatureConfig.createTarget(endReplace, ModBlocks.ICE_ETHER_ORE.getDefaultState())
);
ConfiguredFeatures.register(featureRegisterable, ICE_ETHER_ORE_KEY, Feature.ORE,
new OreFeatureConfig(overWorldTarget, 9));
ConfiguredFeatures.register(featureRegisterable, NETHER_ICE_ETHER_ORE_KEY, Feature.ORE,
new OreFeatureConfig(netherTarget, 12));
ConfiguredFeatures.register(featureRegisterable, END_ICE_ETHER_ORE_KEY, Feature.ORE,
new OreFeatureConfig(endTarget, 10));
}
public static RegistryKey<ConfiguredFeature<?, ?>> of(String id) {
return RegistryKey.of(RegistryKeys.CONFIGURED_FEATURE, new Identifier(TutorialMod.MOD_ID, id));
}
}
| 0 | 0.755901 | 1 | 0.755901 | game-dev | MEDIA | 0.99808 | game-dev | 0.851816 | 1 | 0.851816 |
pasqal-io/Pulser | 15,834 | pulser-core/pulser/parametrized/paramobj.py | # Copyright 2020 Pulser Development Team
#
# 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.
"""Contains the ParamObj and auxiliary classes for object parametrization."""
from __future__ import annotations
import inspect
import operator
import warnings
from collections.abc import Callable
from itertools import chain
from typing import TYPE_CHECKING, Any, Union, cast
import numpy as np
import pulser.math as pm
import pulser.parametrized
from pulser.exceptions.serialization import AbstractReprError
from pulser.json.abstract_repr.serializer import abstract_repr
from pulser.json.abstract_repr.signatures import (
BINARY_OPERATORS,
SIGNATURES,
UNARY_OPERATORS,
)
from pulser.json.utils import obj_to_dict
from pulser.parametrized import Parametrized
if TYPE_CHECKING:
from pulser.parametrized import Variable
# The full list of numpy ufuncs can be found at
# https://numpy.org/devdocs//reference/ufuncs.html#math-operations
# Mapping between ufunc and OpSupport method names, for those
# that don't share the same name or require a dunder method
# Note that for binary method we use the reverse method and invert
# the input order accordingly
_UFUNC_MAP = {
# Binary methods
"add": "add",
"subtract": "sub",
"multiply": "mul",
"divide": "truediv",
"true_divide": "truediv",
"floor_divide": "floordiv",
"power": "pow",
"float_power": "pow",
"remainder": "mod",
"mod": "mod",
"fmod": "mod",
# Special unary methods
"negative": "neg",
"absolute": "abs",
"fabs": "abs",
"floor": "floor",
"ceil": "ceil",
}
class OpSupport:
"""Methods for supporting operators on parametrized objects."""
def __array_ufunc__(
self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any
) -> Any:
if method != "__call__" or len(inputs) > 2:
return NotImplemented
ufunc_name = ufunc.__name__
if ufunc_name in _UFUNC_MAP:
root_name = _UFUNC_MAP[ufunc_name]
if len(inputs) == 2 and inputs[1] is self:
# Use reverse method and inputs
root_name = "r" + root_name
inputs = inputs[::-1]
method_name = f"__{root_name}__"
else:
method_name = ufunc_name
if inputs[0] is self: # Make sure self is involved
try:
# Works for both unary and binary methods
return getattr(self, method_name)(*inputs[1:], **kwargs)
except AttributeError:
pass
return NotImplemented
# Unary operators
def __neg__(self) -> ParamObj:
return ParamObj(operator.neg, self)
def __abs__(self) -> ParamObj:
return ParamObj(operator.abs, self)
def __ceil__(self) -> ParamObj:
return ParamObj(pm.ceil, self)
def __floor__(self) -> ParamObj:
return ParamObj(pm.floor, self)
def __round__(self, n: int = 0) -> ParamObj:
return cast(ParamObj, (self * 10**n).rint() / 10**n)
def rint(self) -> ParamObj:
"""Rounds the value to the nearest int."""
# Defined because np.round looks for 'rint'
return ParamObj(pm.round, self)
def sqrt(self) -> ParamObj:
"""Calculates the square root of the object."""
return ParamObj(pm.sqrt, self)
def exp(self) -> ParamObj:
"""Calculates the exponential of the object."""
return ParamObj(pm.exp, self)
def log2(self) -> ParamObj:
"""Calculates the base-2 logarithm of the object."""
return ParamObj(pm.log2, self)
def log(self) -> ParamObj:
"""Calculates the natural logarithm of the object."""
return ParamObj(pm.log, self)
def sin(self) -> ParamObj:
"""Calculates the trigonometric sine of the object."""
return ParamObj(pm.sin, self)
def cos(self) -> ParamObj:
"""Calculates the trigonometric cosine of the object."""
return ParamObj(pm.cos, self)
def tan(self) -> ParamObj:
"""Calculates the trigonometric tangent of the object."""
return ParamObj(pm.tan, self)
def tanh(self) -> ParamObj:
"""Calculates the hyperbolic tangent of the object."""
return ParamObj(pm.tanh, self)
# Binary operators
def __add__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.add, self, other)
def __radd__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.add, other, self)
def __sub__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.sub, self, other)
def __rsub__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.sub, other, self)
def __mul__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.mul, self, other)
def __rmul__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.mul, other, self)
def __truediv__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.truediv, self, other)
def __rtruediv__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.truediv, other, self)
def __floordiv__(self, other: Union[int, float], /) -> ParamObj:
return (self / other).__floor__()
def __rfloordiv__(self, other: Union[int, float], /) -> ParamObj:
return (other / self).__floor__()
def __pow__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.pow, self, other)
def __rpow__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.pow, other, self)
def __mod__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.mod, self, other)
def __rmod__(self, other: Union[int, float], /) -> ParamObj:
return ParamObj(operator.mod, other, self)
class ParamObj(Parametrized, OpSupport):
"""Holds a call to a given class.
When called, a ParamObj instance returns `cls(*args, **kwargs)`.
Args:
cls: The object to call. Usually it's a class that's
instantiated when called.
args: The args for calling `cls`.
kwargs: The kwargs for calling `cls`.
"""
def __init__(self, cls: Callable, *args: Any, **kwargs: Any) -> None:
"""Initializes a new ParamObj."""
self.cls = cls
self._variables: dict[str, Variable] = {}
if isinstance(self.cls, Parametrized):
self._variables.update(self.cls.variables)
for x in chain(args, kwargs.values()):
if isinstance(x, Parametrized):
self._variables.update(x.variables)
self.args = args
self.kwargs = kwargs
self._instance = None
self._vars_state: dict[str, int] = {}
@property
def _default_kwargs(self) -> dict[str, Any]:
"""The default values for the object's keyword arguments."""
cls_signature = inspect.signature(self.cls).parameters
return {
param: cls_signature[param].default
for param in cls_signature
if cls_signature[param].default != cls_signature[param].empty
}
@property
def variables(self) -> dict[str, Variable]:
"""Returns all involved variables."""
return self._variables
def build(self) -> Any:
"""Builds the object with its variables last assigned values."""
vars_state = {key: var._count for key, var in self._variables.items()}
if vars_state != self._vars_state:
self._vars_state = vars_state
# Builds all Parametrized arguments before feeding them to cls
args_ = [
arg.build() if isinstance(arg, Parametrized) else arg
for arg in self.args
]
kwargs_ = {
key: val.build() if isinstance(val, Parametrized) else val
for key, val in self.kwargs.items()
}
if isinstance(self.cls, ParamObj):
obj = self.cls.build()
else:
obj = self.cls
self._instance = obj(*args_, **kwargs_)
return self._instance
def _to_dict(self) -> dict[str, Any]:
def class_to_dict(cls: Callable) -> dict[str, Any]:
module = "numpy" if isinstance(cls, np.ufunc) else cls.__module__
return obj_to_dict(
self, _build=False, _name=cls.__name__, _module=module
)
args = list(self.args)
if isinstance(self.cls, Parametrized):
raise ValueError(
"Serialization of calls to parametrized objects is not "
"supported."
)
elif (
hasattr(args[0], self.cls.__name__)
and inspect.isfunction(self.cls)
and self.cls.__module__ != "pulser.math"
):
# Check for parametrized methods
if inspect.isclass(self.args[0]):
# classmethod
cls_dict = obj_to_dict(
self,
_build=False,
_name=self.cls.__name__,
_module=self.args[0].__module__,
_submodule=self.args[0].__name__,
)
args[0] = class_to_dict(self.args[0])
else:
raise NotImplementedError(
"Instance or static method "
"serialization is not supported."
)
else:
cls_dict = class_to_dict(self.cls)
return obj_to_dict(self, cls_dict, *args, **self.kwargs)
def _to_abstract_repr(self) -> dict[str, Any]:
if isinstance(self.cls, Parametrized):
raise ValueError(
"Serialization of calls to parametrized objects is not "
"supported."
)
op_name = self.cls.__name__
if (
self.args # If it is a classmethod the first arg will be the class
and hasattr(self.args[0], op_name)
and inspect.isfunction(self.cls)
and not self.cls.__module__ == "pulser.math"
):
# Check for parametrized methods
if inspect.isclass(self.args[0]):
# classmethod
cls_name = self.args[0].__name__
name = f"{cls_name}.{op_name}"
signature = SIGNATURES[
(
"Pulse"
if cls_name == "Pulse" and op_name != "ArbitraryPhase"
else name
)
]
# No existing classmethod has *args in its signature
assert (
signature.var_pos is None
), "Unexpected signature with VAR_POSITIONAL arguments."
all_args = {
**self._default_kwargs,
**dict(zip(signature.all_pos_args(), self.args[1:])),
**self.kwargs,
}
if name == "Pulse.ConstantAmplitude":
all_args["amplitude"] = abstract_repr(
"ConstantWaveform", 0, all_args["amplitude"]
)
return abstract_repr("Pulse", **all_args)
elif name == "Pulse.ConstantDetuning":
all_args["detuning"] = abstract_repr(
"ConstantWaveform", 0, all_args["detuning"]
)
return abstract_repr("Pulse", **all_args)
else:
return abstract_repr(name, **all_args)
raise NotImplementedError(
"Instance or static method serialization is not supported."
)
elif op_name in SIGNATURES:
signature = SIGNATURES[op_name]
filtered_defaults = {
key: value
for key, value in self._default_kwargs.items()
if key in signature.keyword
}
full_kwargs = {**filtered_defaults, **self.kwargs}
if signature.var_pos is not None:
# No args can be given with a keyword
return abstract_repr(op_name, *self.args, **full_kwargs)
all_args = {
**full_kwargs,
**dict(zip(signature.all_pos_args(), self.args)),
}
if op_name == "InterpolatedWaveform" and all_args["times"] is None:
if isinstance(
all_args["values"],
pulser.parametrized.Variable, # Avoids circular import
):
num_values = all_args["values"].size
else:
try:
num_values = len(all_args["values"])
except TypeError:
raise AbstractReprError(
"An InterpolatedWaveform with 'values' of unknown "
"length and unspecified 'times' can't be "
"serialized to the abstract representation. To "
"keep the same argument for 'values', provide "
"compatible 'times' explicitly."
)
all_args["times"] = np.linspace(0, 1, num=num_values)
return abstract_repr(op_name, **all_args)
elif op_name in UNARY_OPERATORS:
return dict(expression=op_name, lhs=self.args[0])
elif op_name in BINARY_OPERATORS:
return dict(
expression=op_name,
lhs=self.args[0],
rhs=self.args[1],
)
else:
raise AbstractReprError(
f"No abstract representation for '{op_name}'."
)
def __call__(self, *args: Any, **kwargs: Any) -> ParamObj:
"""Returns a new ParamObj storing a call to the current ParamObj."""
obj = ParamObj(self, *args, **kwargs)
warnings.warn(
"Calls to methods of parametrized objects are only "
"executed if they serve as arguments of other "
"parametrized objects that are themselves built. If this"
f" is not the case, the call to {obj} will not be "
"executed upon sequence building.",
stacklevel=2,
)
return obj
def __str__(self) -> str:
args = [str(a) for a in self.args]
kwargs = [f"{key}={str(value)}" for key, value in self.kwargs.items()]
if isinstance(self.cls, Parametrized):
name = str(self.cls)
elif (
self.args
and hasattr(self.args[0], self.cls.__name__)
and inspect.isfunction(self.cls)
and inspect.isclass(self.args[0])
):
name = f"{self.args[0].__name__}.{self.cls.__name__}"
args = args[1:]
else:
name = self.cls.__name__
return f"{name}({', '.join(args+kwargs)})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, ParamObj):
return False
return self.args == other.args and self.kwargs == other.kwargs
def __hash__(self) -> int:
return id(self)
| 0 | 0.809986 | 1 | 0.809986 | game-dev | MEDIA | 0.187497 | game-dev | 0.904378 | 1 | 0.904378 |
mangosfour/server | 27,617 | src/modules/SD3/scripts/northrend/ulduar/ulduar/ulduar.cpp | /* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.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 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/* ScriptData
SDName: ulduar
SD%Complete: 70%
SDComment: Teleporters are hacked until solved in core
SDCategory: Ulduar
EndScriptData */
/* ContentData
go_ulduar_teleporter
npc_brann_ulduar
npc_keeper_norgannon
event_go_ulduar_tower
npc_storm_tempered_keeper
npc_charged_sphere
npc_ulduar_keeper
EndContentData */
#include "precompiled.h"
#include "ulduar.h"
/*#####
## go_ulduar_teleporter
#####*/
/* ****
* The teleporter spells cannot be used atm, because target-type TARGET_SCRIPT_COORDINATES, NO_TARGET is not yet suitable for needed targeting. (Current core-Design)
* All teleporters are GO with entry 194569 - on them are npcs of entry 32780 spawned.
* However for reload case we would need to be able to target these npcs of not yet loaded grids (currently impossible)
* And in general we would need some "good" way of selecting appropriate target-npcs for each spell, but sorting is nearly impossible, as there are > 50 of these npcs spawned in Ulduar
* So -- TODO -- remove the TeleportTo Hacks when correct target selection for this spell is working.
*/
enum TeleporterSpells
{
SPELL_TELE_EXPEDITION_BASE_CAMP = 64014,
SPELL_TELE_FORMATION_GROUNDS = 64032,
SPELL_TELE_COLOSSAL_FORGE = 64028,
SPELL_TELE_SCRAPYARD = 64031,
SPELL_TELE_ANTECHAMBER_OF_ULDUAR = 64030,
SPELL_TELE_SHATTERED_WALKWAY = 64029,
SPELL_TELE_CONSERVATORY_OF_LIFE = 64024,
SPELL_TELE_SPARK_OF_IMAGINATION = 65061,
SPELL_TELE_PRISON_OF_YOGG = 65042,
};
// Teleporter Gossip handled by SD3 because depending on Instance Data
enum TeleporterGossipItems
{
GOSSIP_ITEM_TELE_BASE_CAMP = -3603000,
GOSSIP_ITEM_TELE_FORMATION_GROUNDS = -3603001,
GOSSIP_ITEM_TELE_COLOSSAL_FORGE = -3603002,
GOSSIP_ITEM_TELE_SCRAPYARD = -3603003,
GOSSIP_ITEM_TELE_ANTECHAMBER = -3603004,
GOSSIP_ITEM_TELE_WALKWAY = -3603005,
GOSSIP_ITEM_TELE_CONSERVATORY = -3603006,
GOSSIP_ITEM_TELE_SPARK_IMAGINATION = -3603007,
GOSSIP_ITEM_TELE_YOGG_SARON = -3603008,
};
struct go_ulduar_teleporter : public GameObjectScript
{
go_ulduar_teleporter() : GameObjectScript("go_ulduar_teleporter") {}
bool OnGossipHello(Player* pPlayer, GameObject* pGo) override
{
ScriptedInstance* pInstance = (ScriptedInstance*)pPlayer->GetInstanceData();
if (!pInstance)
{
return true;
}
// Base camp
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_BASE_CAMP, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
// Formation grounds
if (pInstance->GetData(TYPE_LEVIATHAN) != NOT_STARTED || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_FORMATION_GROUNDS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
// Colossal Forge
if (pInstance->GetData(TYPE_LEVIATHAN) == DONE || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_COLOSSAL_FORGE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
// Scrapyard
if (pInstance->GetData(TYPE_XT002) != NOT_STARTED || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_SCRAPYARD, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3);
// Antechamber
if (pInstance->GetData(TYPE_XT002) == DONE || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_ANTECHAMBER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4);
// Shattered walkway
if (pInstance->GetData(TYPE_KOLOGARN) == DONE || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_WALKWAY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5);
// Conservatory of life
if (pInstance->GetData(TYPE_AURIAYA) == DONE || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_CONSERVATORY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6);
// Spark of imagination
if (pInstance->GetData(TYPE_MIMIRON) != NOT_STARTED || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_SPARK_IMAGINATION, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7);
// Prison of Yogg-Saron
if (pInstance->GetData(TYPE_VEZAX) == DONE || pPlayer->isGameMaster())
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_TELE_YOGG_SARON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8);
pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pGo->GetGOInfo()->GetGossipMenuId(), pGo), pGo->GetObjectGuid());
return true;
}
bool OnGossipSelect(Player* pPlayer, GameObject* /*pGO*/, uint32 /*uiSender*/, uint32 uiAction) override
{
ScriptedInstance* pInstance = (ScriptedInstance*)pPlayer->GetInstanceData();
if (!pInstance)
{
return true;
}
// Additional checks for the teleporters to prevent exploiting
// -- TODO -- HACK HERE, use spells when possible!
// There needs to be displayed a msg when in Combat, it is likely that this is to be handled by core and spell can-cast check
// -- TODO -- Remove the combat check when spells are correctly working
if (pPlayer->IsInCombat())
{
return true;
}
switch (uiAction)
{
// Basecamp
case GOSSIP_ACTION_INFO_DEF:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_EXPEDITION_BASE_CAMP, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, -706.122f, -92.6024f, 429.876f, 0);
break;
// Formation Grounds
case GOSSIP_ACTION_INFO_DEF + 1:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_FORMATION_GROUNDS, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 131.248f, -35.3802f, 409.804f, 0);
break;
// Colossal Forge
case GOSSIP_ACTION_INFO_DEF + 2:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_COLOSSAL_FORGE, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 553.233f, -12.3247f, 409.679f, 0);
break;
// Scrapyard
case GOSSIP_ACTION_INFO_DEF + 3:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_SCRAPYARD, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 926.292f, -11.4635f, 418.595f, 0);
break;
// Antechamber
case GOSSIP_ACTION_INFO_DEF + 4:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_ANTECHAMBER_OF_ULDUAR, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 1498.09f, -24.246f, 420.967f, 0);
break;
// Shattered walkway
case GOSSIP_ACTION_INFO_DEF + 5:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_SHATTERED_WALKWAY, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 1859.45f, -24.1f, 448.9f, 0);
break;
// Conservatory of life
case GOSSIP_ACTION_INFO_DEF + 6:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_CONSERVATORY_OF_LIFE, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 2086.27f, -24.3134f, 421.239f, 0);
break;
// Spark of imagination
case GOSSIP_ACTION_INFO_DEF + 7:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_SPARK_OF_IMAGINATION, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 2518.16f, 2569.03f, 412.299f, 0);
break;
// Prison of Yogg-Saron
case GOSSIP_ACTION_INFO_DEF + 8:
// pPlayer->CastSpell(pPlayer, SPELL_TELE_PRISON_OF_YOGG, true, nullptr, nullptr, pGo->GetObjectGuid());
pPlayer->TeleportTo(603, 1854.82f, -11.56f, 334.175f, 4.71f);
break;
default:
return true;
}
pPlayer->CLOSE_GOSSIP_MENU();
return true;
}
};
/*######
## npc_brann_ulduar
######*/
enum
{
GOSSIP_ITEM_BEGIN_ASSAULT = -3603012,
GOSSIP_TEXT_ID_BRANN = 14369,
};
struct npc_brann_ulduar : public CreatureScript
{
npc_brann_ulduar() : CreatureScript("npc_brann_ulduar") {}
bool OnGossipHello(Player* pPlayer, Creature* pCreature) override
{
if (InstanceData* pInstance = pCreature->GetInstanceData())
{
if (pInstance->GetData(TYPE_LEVIATHAN_GAUNTLET) == NOT_STARTED && pInstance->GetData(TYPE_LEVIATHAN) == NOT_STARTED)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_BEGIN_ASSAULT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_BRANN, pCreature->GetObjectGuid());
}
return true;
}
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*sender*/, uint32 uiAction) override
{
if (uiAction == GOSSIP_ACTION_INFO_DEF + 1)
{
if (InstanceData* pInstance = pCreature->GetInstanceData())
{
// if encounter is started by Brann then hard mode is failed
pInstance->SetData(TYPE_TOWER_FREYA, FAIL);
pInstance->SetData(TYPE_TOWER_HODIR, FAIL);
pInstance->SetData(TYPE_TOWER_MIMIRON, FAIL);
pInstance->SetData(TYPE_TOWER_THORIM, FAIL);
// set gauntlet in progress; rest of the event is done by DB scripts
pInstance->SetData(TYPE_LEVIATHAN_GAUNTLET, IN_PROGRESS);
pCreature->GetMotionMaster()->MoveWaypoint();
}
pPlayer->CLOSE_GOSSIP_MENU();
}
return true;
}
};
/*######
## npc_keeper_norgannon
######*/
enum
{
GOSSIP_ITEM_ACTIVATE_SYSTEMS = -3603010,
GOSSIP_ITEM_CONFIRMED = -3603011,
GOSSIP_TEXT_ID_GREET = 14375,
GOSSIP_TEXT_ID_DEFENSES = 14496,
GOSSIP_TEXT_ID_ACTIVATED = 14497,
};
struct npc_keeper_norgannon : public CreatureScript
{
npc_keeper_norgannon() : CreatureScript("npc_keeper_norgannon") {}
bool OnGossipHello(Player* pPlayer, Creature* pCreature) override
{
if (InstanceData* pInstance = pCreature->GetInstanceData())
{
if (pInstance->GetData(TYPE_LEVIATHAN_GAUNTLET) == NOT_STARTED && pInstance->GetData(TYPE_LEVIATHAN) == NOT_STARTED && pInstance->GetData(TYPE_TOWER_HODIR) == NOT_STARTED &&
pInstance->GetData(TYPE_TOWER_FREYA) == NOT_STARTED && pInstance->GetData(TYPE_TOWER_MIMIRON) == NOT_STARTED && pInstance->GetData(TYPE_TOWER_THORIM) == NOT_STARTED)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_ACTIVATE_SYSTEMS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_GREET, pCreature->GetObjectGuid());
}
return true;
}
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*sender*/, uint32 uiAction) override
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF + 1:
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_CONFIRMED, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_DEFENSES, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
if (ScriptedInstance* pInstance = (ScriptedInstance*)pCreature->GetInstanceData())
{
// if hard mode is triggered all towers become active and encounter starts automatically
pInstance->SetData(TYPE_TOWER_FREYA, DONE);
pInstance->SetData(TYPE_TOWER_HODIR, DONE);
pInstance->SetData(TYPE_TOWER_MIMIRON, DONE);
pInstance->SetData(TYPE_TOWER_THORIM, DONE);
// set gauntlet in progress and despawn the Lorekeeper; rest of the event is done by DB scripts
pInstance->SetData(TYPE_LEVIATHAN_GAUNTLET, IN_PROGRESS);
pCreature->ForcedDespawn(10000);
if (Creature* pDellorah = pInstance->GetSingleCreatureFromStorage(NPC_EXPLORER_DELLORAH))
pDellorah->GetMotionMaster()->MoveWaypoint();
if (Creature* pBrann = pInstance->GetSingleCreatureFromStorage(NPC_BRANN_BRONZEBEARD))
pBrann->GetMotionMaster()->MoveWaypoint();
}
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_ACTIVATED, pCreature->GetObjectGuid());
break;
}
return true;
}
};
/*######
## event_go_ulduar_tower
######*/
struct event_go_ulduar_tower : public MapEventScript
{
event_go_ulduar_tower() : MapEventScript("event_go_ulduar_tower") {}
bool OnReceived(uint32 uiEventId, Object* pSource, Object* /*pTarget*/, bool /*bIsStart*/) override
{
if (pSource->GetTypeId() == TYPEID_GAMEOBJECT && ((GameObject*)pSource)->GetGoType() == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING)
{
InstanceData* pInstance = ((GameObject*)pSource)->GetInstanceData();
if (!pInstance)
{
return true;
}
// Towers can be deactivated by destroying them. Notify instance data in case they get destroyed.
switch (uiEventId)
{
case EVENT_ID_TOWER_LIFE:
pInstance->SetData(TYPE_TOWER_FREYA, FAIL);
break;
case EVENT_ID_TOWER_FLAME:
pInstance->SetData(TYPE_TOWER_MIMIRON, FAIL);
break;
case EVENT_ID_TOWER_FROST:
pInstance->SetData(TYPE_TOWER_HODIR, FAIL);
break;
case EVENT_ID_TOWER_STORMS:
pInstance->SetData(TYPE_TOWER_THORIM, FAIL);
break;
default:
return false;
}
// despawn all generators in range
std::list<Creature*> lGenerators;
GetCreatureListWithEntryInGrid(lGenerators, (GameObject*)pSource, NPC_GENERATOR_SMALL, 100.0f);
for (std::list<Creature*>::iterator itr = lGenerators.begin(); itr != lGenerators.end(); ++itr)
{
(*itr)->ForcedDespawn();
}
// allow further DB processing
return false;
}
return false;
}
};
/*######
## npc_storm_tempered_keeper
######*/
enum
{
SPELL_FORKED_LIGHTNING = 63541,
SPELL_SEPARATION_ANXIETY = 63539, // cast when a buddy is too far away
SPELL_VENGEFUL_SURGE = 63630, // cast when a buddy dies
SPELL_SUMMON_CHARGED_SPHERE = 63527, // summons npc 33715
SPELL_CHARGED_SPERE = 63537, // charged sphere spells
SPELL_SUPERCHARGED = 63528,
NPC_TEMPERED_KEEPER_1 = 33699,
NPC_TEMPERED_KEEPER_2 = 33722,
NPC_CHARGED_SPHERE = 33715, // moves to buddy keeper location
MAX_KEEPER_DISTANCE = 70,
};
struct npc_storm_tempered_keeper : public CreatureScript
{
npc_storm_tempered_keeper() : CreatureScript("npc_storm_tempered_keeper") {}
struct npc_storm_tempered_keeperAI : public ScriptedAI
{
npc_storm_tempered_keeperAI(Creature* pCreature) : ScriptedAI(pCreature) { }
uint32 m_uiCheckBuddyTimer;
uint32 m_uiLightningTimer;
uint32 m_uiSphereTimer;
ObjectGuid m_buddyGuid;
void Reset() override
{
m_uiCheckBuddyTimer = 1000;
m_uiLightningTimer = urand(5000, 10000);
m_uiSphereTimer = urand(10000, 30000);
}
void Aggro(Unit* /*pWho*/) override
{
// initialize nearby buddy
if (Creature* pKeeper = GetClosestCreatureWithEntry(m_creature, m_creature->GetEntry() == NPC_TEMPERED_KEEPER_1 ? NPC_TEMPERED_KEEPER_2 : NPC_TEMPERED_KEEPER_1, 20))
m_buddyGuid = pKeeper->GetObjectGuid();
}
void JustSummoned(Creature* pSummoned) override
{
if (pSummoned->GetEntry() == NPC_CHARGED_SPHERE)
{
pSummoned->CastSpell(pSummoned, SPELL_CHARGED_SPERE, true);
// move to buddy location and notify about buddy entry
if (Creature* pBuddy = m_creature->GetMap()->GetCreature(m_buddyGuid))
{
pSummoned->GetMotionMaster()->MoveFollow(pBuddy, 0, 0);
SendAIEvent(AI_EVENT_CUSTOM_A, m_creature, pSummoned, pBuddy->GetEntry());
}
}
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
return;
}
if (m_uiCheckBuddyTimer)
{
if (m_uiCheckBuddyTimer <= uiDiff)
{
Creature* pBuddy = m_creature->GetMap()->GetCreature(m_buddyGuid);
if (!pBuddy)
{
script_error_log("npc_storm_tempered_keeper for %s couldn't find its buddy.", m_creature->GetGuidStr().c_str());
m_uiCheckBuddyTimer = 0;
return;
}
// check if buddy is withind distance or alive
if (!pBuddy->IsWithinDistInMap(m_creature, MAX_KEEPER_DISTANCE))
{
if (DoCastSpellIfCan(m_creature, SPELL_SEPARATION_ANXIETY) == CAST_OK)
m_uiCheckBuddyTimer = 5000;
}
else if (!pBuddy->IsAlive())
{
if (DoCastSpellIfCan(m_creature, SPELL_VENGEFUL_SURGE) == CAST_OK)
m_uiCheckBuddyTimer = 0;
}
else
m_uiCheckBuddyTimer = 1000;
}
else
m_uiCheckBuddyTimer -= uiDiff;
// spawn a sphere only if the buddy is stil alive
if (m_uiSphereTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_CHARGED_SPHERE) == CAST_OK)
m_uiSphereTimer = urand(20000, 35000);
}
else
m_uiSphereTimer -= uiDiff;
}
if (m_uiLightningTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_FORKED_LIGHTNING) == CAST_OK)
m_uiLightningTimer = urand(10000, 15000);
}
else
m_uiLightningTimer -= uiDiff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* pCreature) override
{
return new npc_storm_tempered_keeperAI(pCreature);
}
};
/*######
## npc_charged_sphere
######*/
struct npc_charged_sphere : public CreatureScript
{
npc_charged_sphere() : CreatureScript("npc_charged_sphere") {}
struct npc_charged_sphereAI : public ScriptedAI
{
npc_charged_sphereAI(Creature* pCreature) : ScriptedAI(pCreature) { }
bool m_bIsCharged;
uint32 m_uiBuddyEntry;
void Reset() override
{
m_bIsCharged = false;
m_uiBuddyEntry = 0;
}
void MoveInLineOfSight(Unit* pWho) override
{
// cast supercharged if reached the buddy
if (!m_bIsCharged && pWho->GetEntry() == m_uiBuddyEntry && pWho->IsAlive() && pWho->IsWithinDistInMap(m_creature, 5.0f))
{
DoCastSpellIfCan(pWho, SPELL_SUPERCHARGED, CAST_TRIGGERED);
m_creature->ForcedDespawn(1000);
m_bIsCharged = true;
}
}
void ReceiveAIEvent(AIEventType eventType, Creature* /*pSender*/, Unit* /*pInvoker*/, uint32 uiMiscValue) override
{
// inity entry of the buddy keeper
if (eventType == AI_EVENT_CUSTOM_A)
m_uiBuddyEntry = uiMiscValue;
}
void AttackStart(Unit* /*pWho*/) override { }
void UpdateAI(const uint32 /*uiDiff*/) override { }
};
CreatureAI* GetAI(Creature* pCreature) override
{
return new npc_charged_sphereAI(pCreature);
}
};
/*######
## npc_ulduar_keeper
######*/
enum
{
SAY_KEEPER_ACTIVE = -1603012,
GOSSIP_ITEM_LEND_AID = -3603013,
GOSSIP_ITEM_KEEPER_CONFIRM = -3603014,
GOSSIP_TEXT_ID_HODIR = 14326,
GOSSIP_TEXT_ID_FREYA = 14332,
GOSSIP_TEXT_ID_THORIM = 14333,
GOSSIP_TEXT_ID_MIMIRON = 14334,
GOSSIP_TEXT_ID_KEEPER_CONFIRM = 14325,
GOSSIP_TEXT_ID_YOGG_DEFEATED = 384, // ToDo: add the right text id here!
};
struct npc_ulduar_keeper : public CreatureScript
{
npc_ulduar_keeper() : CreatureScript("npc_ulduar_keeper") {}
bool OnGossipHello(Player* pPlayer, Creature* pCreature) override
{
if (InstanceData* pInstance = pCreature->GetInstanceData())
{
if (pInstance->GetData(TYPE_YOGGSARON) == DONE)
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_YOGG_DEFEATED, pCreature->GetObjectGuid());
else
{
switch (pCreature->GetEntry())
{
case NPC_KEEPER_HODIR:
if (pInstance->GetData(TYPE_KEEPER_HODIR) != DONE)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_LEND_AID, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_HODIR, pCreature->GetObjectGuid());
break;
case NPC_KEEPER_FREYA:
if (pInstance->GetData(TYPE_KEEPER_FREYA) != DONE)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_LEND_AID, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_FREYA, pCreature->GetObjectGuid());
break;
case NPC_KEEPER_THORIM:
if (pInstance->GetData(TYPE_KEEPER_THORIM) != DONE)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_LEND_AID, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_THORIM, pCreature->GetObjectGuid());
break;
case NPC_KEEPER_MIMIRON:
if (pInstance->GetData(TYPE_KEEPER_MIMIRON) != DONE)
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_LEND_AID, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_MIMIRON, pCreature->GetObjectGuid());
break;
}
}
}
return true;
}
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*sender*/, uint32 uiAction) override
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF + 1:
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KEEPER_CONFIRM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(GOSSIP_TEXT_ID_KEEPER_CONFIRM, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
DoScriptText(SAY_KEEPER_ACTIVE, pCreature, pPlayer);
pPlayer->CLOSE_GOSSIP_MENU();
if (InstanceData* pInstance = pCreature->GetInstanceData())
{
switch (pCreature->GetEntry())
{
case NPC_KEEPER_HODIR: pInstance->SetData(TYPE_KEEPER_HODIR, DONE); break;
case NPC_KEEPER_FREYA: pInstance->SetData(TYPE_KEEPER_FREYA, DONE); break;
case NPC_KEEPER_THORIM: pInstance->SetData(TYPE_KEEPER_THORIM, DONE); break;
case NPC_KEEPER_MIMIRON: pInstance->SetData(TYPE_KEEPER_MIMIRON, DONE); break;
}
}
break;
}
return true;
}
};
void AddSC_ulduar()
{
Script* s;
s = new go_ulduar_teleporter();
s->RegisterSelf();
s = new npc_brann_ulduar();
s->RegisterSelf();
s = new npc_keeper_norgannon();
s->RegisterSelf();
s = new event_go_ulduar_tower();
s->RegisterSelf();
s = new npc_storm_tempered_keeper();
s->RegisterSelf();
s = new npc_charged_sphere();
s->RegisterSelf();
s = new npc_ulduar_keeper();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "go_ulduar_teleporter";
//pNewScript->pGossipHelloGO = &GossipHello_go_ulduar_teleporter;
//pNewScript->pGossipSelectGO = &GossipSelect_go_ulduar_teleporter;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "npc_brann_ulduar";
//pNewScript->pGossipHello = &GossipHello_npc_brann_ulduar;
//pNewScript->pGossipSelect = &GossipSelect_npc_brann_ulduar;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "npc_keeper_norgannon";
//pNewScript->pGossipHello = &GossipHello_npc_keeper_norgannon;
//pNewScript->pGossipSelect = &GossipSelect_npc_keeper_norgannon;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "event_go_ulduar_tower";
//pNewScript->pProcessEventId = &ProcessEventId_event_go_ulduar_tower;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "npc_storm_tempered_keeper";
//pNewScript->GetAI = &GetAI_npc_storm_tempered_keeper;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "npc_charged_sphere";
//pNewScript->GetAI = &GetAI_npc_charged_sphere;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "npc_ulduar_keeper";
//pNewScript->pGossipHello = &GossipHello_npc_ulduar_keeper;
//pNewScript->pGossipSelect = &GossipSelect_npc_ulduar_keeper;
//pNewScript->RegisterSelf();
}
| 0 | 0.96819 | 1 | 0.96819 | game-dev | MEDIA | 0.833618 | game-dev | 0.954134 | 1 | 0.954134 |
quiverteam/Engine | 8,127 | src/game/client/vgui_centerstringpanel.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include <stdarg.h>
#include "vguicenterprint.h"
#include "ivrenderview.h"
#include <vgui/IVgui.h>
#include "VguiMatSurface/IMatSystemSurface.h"
#include <vgui_controls/Label.h>
#include <vgui_controls/Controls.h>
#include <vgui/ISurface.h>
#include <vgui/IScheme.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef TF_CLIENT_DLL
static ConVar scr_centertime( "scr_centertime", "5" );
#else
static ConVar scr_centertime( "scr_centertime", "2" );
#endif
//-----------------------------------------------------------------------------
// Purpose: Implements Center String printing
//-----------------------------------------------------------------------------
class CCenterStringLabel : public vgui::Label
{
DECLARE_CLASS_SIMPLE( CCenterStringLabel, vgui::Label );
public:
CCenterStringLabel( vgui::VPANEL parent );
virtual ~CCenterStringLabel( void );
// vgui::Panel
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
virtual void OnTick( void );
virtual bool ShouldDraw( void );
// CVGuiCenterPrint
virtual void SetTextColor( int r, int g, int b, int a );
virtual void Print( char *text );
virtual void Print( wchar_t *text );
virtual void ColorPrint( int r, int g, int b, int a, char *text );
virtual void ColorPrint( int r, int g, int b, int a, wchar_t *text );
virtual void Clear( void );
protected:
MESSAGE_FUNC_INT_INT( OnScreenSizeChanged, "OnScreenSizeChanged", oldwide, oldtall );
private:
void ComputeSize( void );
vgui::HFont m_hFont;
float m_flCentertimeOff;
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : *parent -
//-----------------------------------------------------------------------------
CCenterStringLabel::CCenterStringLabel( vgui::VPANEL parent ) :
BaseClass( NULL, "CCenterStringLabel", " " )
{
SetParent( parent );
ComputeSize();
SetVisible( false );
SetCursor( null );
SetKeyBoardInputEnabled( false );
SetMouseInputEnabled( false );
SetContentAlignment( vgui::Label::a_center );
m_hFont = 0;
SetFgColor( Color( 255, 255, 255, 255 ) );
SetPaintBackgroundEnabled( false );
m_flCentertimeOff = 0.0;
vgui::ivgui()->AddTickSignal( GetVPanel(), 100 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCenterStringLabel::~CCenterStringLabel( void )
{
}
//-----------------------------------------------------------------------------
// Purpose: Updates panel to handle the new screen size
//-----------------------------------------------------------------------------
void CCenterStringLabel::OnScreenSizeChanged(int iOldWide, int iOldTall)
{
BaseClass::OnScreenSizeChanged(iOldWide, iOldTall);
ComputeSize();
}
//-----------------------------------------------------------------------------
// Purpose: Computes panel's desired size and position
//-----------------------------------------------------------------------------
void CCenterStringLabel::ComputeSize( void )
{
int w, h;
w = ScreenWidth();
h = ScreenHeight();
int iHeight = (int)(h * 0.3);
SetSize( w, iHeight );
SetPos( 0, ( h * 0.35 ) - ( iHeight / 2 ) );
}
void CCenterStringLabel::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
// Use a large font
m_hFont = pScheme->GetFont( "Trebuchet24" );
assert( m_hFont );
SetFont( m_hFont );
int w, h;
w = ScreenWidth();
h = ScreenHeight();
int iHeight = (int)(h * 0.3);
SetSize( w, iHeight );
SetPos( 0, ( h * 0.35 ) - ( iHeight / 2 ) );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : r -
// g -
// b -
// a -
//-----------------------------------------------------------------------------
void CCenterStringLabel::SetTextColor( int r, int g, int b, int a )
{
SetFgColor( Color( r, g, b, a ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::Print( char *text )
{
SetText( text );
m_flCentertimeOff = scr_centertime.GetFloat() + gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::Print( wchar_t *text )
{
SetText( text );
m_flCentertimeOff = scr_centertime.GetFloat() + gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::ColorPrint( int r, int g, int b, int a, char *text )
{
SetTextColor( r, g, b, a );
Print( text );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::ColorPrint( int r, int g, int b, int a, wchar_t *text )
{
SetTextColor( r, g, b, a );
Print( text );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::Clear( void )
{
m_flCentertimeOff = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCenterStringLabel::OnTick( void )
{
SetVisible( ShouldDraw() );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
// FIXME, this has dependencies on the engine that should go away
//-----------------------------------------------------------------------------
bool CCenterStringLabel::ShouldDraw( void )
{
if ( engine->IsDrawingLoadingImage() )
{
return false;
}
if ( m_flCentertimeOff <= gpGlobals->curtime )
{
// not time to turn off the message yet
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output :
//-----------------------------------------------------------------------------
CCenterPrint::CCenterPrint( void )
{
vguiCenterString = NULL;
}
void CCenterPrint::SetTextColor( int r, int g, int b, int a )
{
if ( vguiCenterString )
{
vguiCenterString->SetTextColor( r, g, b, a );
}
}
void CCenterPrint::Print( char *text )
{
if ( vguiCenterString )
{
vguiCenterString->ColorPrint( 255, 255, 255, 255, text );
}
}
void CCenterPrint::Print( wchar_t *text )
{
if ( vguiCenterString )
{
vguiCenterString->ColorPrint( 255, 255, 255, 255, text );
}
}
void CCenterPrint::ColorPrint( int r, int g, int b, int a, char *text )
{
if ( vguiCenterString )
{
vguiCenterString->ColorPrint( r, g, b, a, text );
}
}
void CCenterPrint::ColorPrint( int r, int g, int b, int a, wchar_t *text )
{
if ( vguiCenterString )
{
vguiCenterString->ColorPrint( r, g, b, a, text );
}
}
void CCenterPrint::Clear( void )
{
if ( vguiCenterString )
{
vguiCenterString->Clear();
}
}
void CCenterPrint::Create( vgui::VPANEL parent )
{
if ( vguiCenterString )
{
Destroy();
}
vguiCenterString = new CCenterStringLabel( parent );
}
void CCenterPrint::Destroy( void )
{
if ( vguiCenterString )
{
vguiCenterString->SetParent( (vgui::Panel *)NULL );
delete vguiCenterString;
vguiCenterString = NULL;
}
}
static CCenterPrint g_CenterString;
CCenterPrint *internalCenterPrint = &g_CenterString;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CCenterPrint, ICenterPrint, VCENTERPRINT_INTERFACE_VERSION, g_CenterString ); | 0 | 0.829571 | 1 | 0.829571 | game-dev | MEDIA | 0.629392 | game-dev | 0.602903 | 1 | 0.602903 |
FirePh0enix/so_long | 3,076 | src/hud.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* hud.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ledelbec <ledelbec@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/02/08 14:25:32 by ledelbec #+# #+# */
/* Updated: 2024/02/29 16:19:28 by ledelbec ### ########.fr */
/* */
/* ************************************************************************** */
#include "gui.h"
#include "so_long.h"
#include "render/render.h"
static void _draw_movements(t_game *game)
{
ft_sprintf(game->buffer, "Moves %d", game->moves);
rdr_add_text(game->rdr, game->buffer, (t_vec2){10, 10},
(t_add_text){992000, 5, game->small_font, 0x0});
ft_printf("%s\n", game->buffer);
}
static void _draw_collects(t_game *game)
{
rdr_add_sprite(game->rdr, game->money_spawn[6], (t_vec2){-40, -15},
(t_add_sprite){99200, 5, false, false});
ft_sprintf(game->buffer, "%d out of %d", game->collectibles,
game->collectibles_count);
rdr_add_text(game->rdr, game->buffer, (t_vec2){50, 50},
(t_add_text){992000, 5, game->small_font, 0x0});
}
static void _draw_health_bar(t_game *game, int health, bool p2)
{
int y;
unsigned int color;
int i;
ft_bzero(game->buffer, 30);
i = 0;
while (i < health)
game->buffer[i++] = 'A';
y = 90;
if (p2)
y = 120;
color = 0xFFFF0000;
if (p2)
color = 0xFFFF00FF;
if (!p2)
rdr_add_text(game->rdr, "P1 ", (t_vec2){0, y}, (t_add_text){
992000, 5, game->small_font, color});
else
rdr_add_text(game->rdr, "P2 ", (t_vec2){0, y}, (t_add_text){
992000, 5, game->small_font, color});
rdr_add_text(game->rdr, game->buffer, (t_vec2){25, y}, (t_add_text){
992000, 5, game->symbols_font, color});
}
void draw_hud(t_game *game)
{
const char *msg1 = "Collect all the gold !";
const char *msg2 = "Go back to your gold mine !";
const int x = WIN_WIDTH / 2 - SCALED_SIZE * 5;
const int size = 14;
char *msg;
if (game->collectibles_count == game->collectibles)
msg = (char *) msg2;
else
msg = (char *) msg1;
draw_ribbon(game, (t_vec2i){WIN_WIDTH / 2 - SCALED_SIZE * (size / 2), 0},
size);
draw_banner_h(game, (t_vec2i){-64, -48}, (t_vec2i){5, 4});
rdr_add_text(game->rdr, (void *)msg, (t_vec2){
text_center_x(game->font, (void *)msg, x - 150, size * SCALED_SIZE),
text_center_y(game->font, (void *)msg, 0, SCALED_SIZE) - 8},
(t_add_text){992000, 5, game->font, 0x0});
_draw_movements(game);
_draw_collects(game);
_draw_health_bar(game, game->player->health,
((t_player *)game->player->extension)->is_p2);
if (game->player2)
_draw_health_bar(game, game->player2->health, true);
}
| 0 | 0.846332 | 1 | 0.846332 | game-dev | MEDIA | 0.82573 | game-dev | 0.759973 | 1 | 0.759973 |
CraftTweaker/CraftTweaker-Documentation | 2,380 | docs_exported/1.17/crafttweaker/docs/forge/api/event/entity/player/ItemFishedEvent.md | # ItemFishedEvent
This event is fired every time the player fishes up an item. It can be used
to add or remove drops, change the durability damage, do other effects, and
even prevent the fishing by canceling the event.
The event is cancelable.
If the event is canceled, will cause the player to receive no items at all
The event does not have a result.
## Importing the class
It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import at the very top of the file.
```zenscript
import crafttweaker.api.event.entity.player.ItemFishedEvent;
```
## Extending PlayerEvent
ItemFishedEvent extends [PlayerEvent](/forge/api/event/entity/player/PlayerEvent). That means all methods available in [PlayerEvent](/forge/api/event/entity/player/PlayerEvent) are also available in ItemFishedEvent
## Methods
:::group{name=damageRodBy}
Sets the amount of durability damage to inflict on the fishing rod.
Return Type: void
```zenscript
// ItemFishedEvent.damageRodBy(damage as int) as void
event.damageRodBy(5);
```
| Parameter | Type | Description |
|-----------|------|-------------|
| damage | int | The amount of durability damage. |
:::
:::group{name=getDrops}
Gets the list of items being fished up by the player.
Returns: The list of items being fished up by the player.
Return Type: stdlib.List<[ItemStack](/vanilla/api/item/ItemStack)>
```zenscript
// ItemFishedEvent.getDrops() as stdlib.List<ItemStack>
event.getDrops();
```
:::
:::group{name=getItemDamage}
Gets the amount of durability damage to inflict on the fishing rod.
Returns: The amount of durability damage to inflict on the fishing rod.
Return Type: int
```zenscript
// ItemFishedEvent.getItemDamage() as int
event.getItemDamage();
```
:::
## Properties
| Name | Type | Has Getter | Has Setter | Description |
|------|------|------------|------------|-------------|
| damageRodBy | [ItemFishedEvent](/forge/api/event/entity/player/ItemFishedEvent) | false | true | Sets the amount of durability damage to inflict on the fishing rod. |
| drops | stdlib.List<[ItemStack](/vanilla/api/item/ItemStack)> | true | false | Gets the list of items being fished up by the player. |
| itemDamage | int | true | false | Gets the amount of durability damage to inflict on the fishing rod. |
| 0 | 0.84003 | 1 | 0.84003 | game-dev | MEDIA | 0.98725 | game-dev | 0.747465 | 1 | 0.747465 |
codand/Unity3DPortals | 24,084 | Assets/Tayx/Graphy - Ultimate Stats Monitor/Scripts/Editor/GraphyDebuggerEditor.cs | /* ---------------------------------------
* Author: Martin Pane (martintayx@gmail.com) (@tayx94)
* Collaborators: Lars Aalbertsen (@Rockylars)
* Project: Graphy - Ultimate Stats Monitor
* Date: 02-Jan-18
* Studio: Tayx
*
* This project is released under the MIT license.
* Attribution is not required, but it is always welcomed!
* -------------------------------------*/
using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
namespace Tayx.Graphy
{
[CustomEditor(typeof(GraphyDebugger))]
internal class GraphyDebuggerEditor : Editor
{
/* ----- TODO: ----------------------------
* Add summaries to the variables.
* Add summaries to the functions.
* Finish spacing on "OnInspectorGUI".
* Add sections to "OnInspectorGUI".
* Fix the use of Space to be consistent with "GraphyManagerEditor".
* --------------------------------------*/
#region Variables -> Private
private GraphyDebugger m_target;
private int m_newDebugPacketListSize = 0;
private int m_previouslySelectedDebugPacketIndex = 0;
private int m_currentlySelectedDebugPacketIndex = 0;
private int m_selectedDebugPacketCondition = 0;
private GUISkin m_skin;
private GUIStyle m_headerStyle1;
private GUIStyle m_headerStyle2;
private Texture2D m_logoTexture;
#endregion
#region Methods -> Unity Callbacks
private void OnEnable()
{
m_target = (GraphyDebugger) target;
}
#endregion
#region Methods -> Public Override
public override void OnInspectorGUI()
{
if (m_target == null && target == null)
{
base.OnInspectorGUI();
return;
}
LoadGuiStyles();
float defaultLabelWidth = EditorGUIUtility.labelWidth;
float defaultFieldWidth = EditorGUIUtility.fieldWidth;
//===== CONTENT REGION ========================================================================
GUILayout.Space(20);
#region Section -> Logo
if (m_logoTexture != null)
{
GUILayout.Label
(
image: m_logoTexture,
style: new GUIStyle(GUI.skin.GetStyle("Label"))
{
alignment = TextAnchor.UpperCenter
}
);
GUILayout.Space(10);
}
else
{
EditorGUILayout.LabelField
(
label: "[ GRAPHY - DEBUGGER ]",
style: m_headerStyle1
);
}
#endregion
GUILayout.Space(5); //Extra pixels added when the logo is used.
#region Section -> Settings
SerializedObject serObj = serializedObject;
SerializedProperty debugPacketList = serObj.FindProperty("m_debugPackets"); // Find the List in our script and create a refrence of it
//Update our list
serObj.Update();
EditorGUILayout.LabelField("Current [Debug Packets] list size: " + debugPacketList.arraySize);
EditorGUIUtility.fieldWidth = 32;
EditorGUILayout.BeginHorizontal();
m_newDebugPacketListSize = EditorGUILayout.IntField
(
label: "Define a new list size",
value: m_newDebugPacketListSize
);
if (GUILayout.Button("Resize List"))
{
if (EditorUtility.DisplayDialog
(
title:
"Resize List",
message:
"Are you sure you want to resize the entire List?\n\n" +
"Current List Size -> " +
debugPacketList.arraySize +
"\n" +
"New List Size -> " +
m_newDebugPacketListSize +
"\n" +
"This will add default entries if the value is greater than the list size, or erase the bottom values until the new size specified.",
ok:
"Resize",
cancel:
"Cancel")
)
{
m_currentlySelectedDebugPacketIndex = 0;
if (m_newDebugPacketListSize != debugPacketList.arraySize)
{
while (m_newDebugPacketListSize > debugPacketList.arraySize)
{
debugPacketList.InsertArrayElementAtIndex(debugPacketList.arraySize);
SetDefaultDebugPacketValues(debugPacketList);
}
while (m_newDebugPacketListSize < debugPacketList.arraySize)
{
debugPacketList.DeleteArrayElementAtIndex(debugPacketList.arraySize - 1);
}
}
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("NOT RECOMMENDED (Only use for first initialization)", EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.Space();
EditorGUILayout.Space();
if (debugPacketList.arraySize < 1)
{
m_previouslySelectedDebugPacketIndex = 0;
m_currentlySelectedDebugPacketIndex = 0;
m_selectedDebugPacketCondition = 0;
serializedObject.ApplyModifiedProperties();
return;
}
m_headerStyle2.contentOffset = Vector2.down * 3f;
EditorGUILayout.LabelField("Selected debug packet:");
EditorGUILayout.BeginHorizontal();
List<string> debugPacketNames = new List<string>();
for (int i = 0; i < debugPacketList.arraySize; i++)
{
SerializedProperty listItem = debugPacketList.GetArrayElementAtIndex(i);
// NOTE: If the Popup detects two equal strings, it just paints 1, that's why I always add the "i"
char checkMark = listItem.FindPropertyRelative("Active").boolValue ? '\u2714' : '\u2718';
debugPacketNames.Add
(
(i + 1) +
" (" +
checkMark +
") " +
" - ID: " +
listItem.FindPropertyRelative("Id").intValue +
" (Conditions: " +
listItem.FindPropertyRelative("DebugConditions").arraySize +
")"
);
}
m_currentlySelectedDebugPacketIndex = EditorGUILayout.Popup(m_currentlySelectedDebugPacketIndex, debugPacketNames.ToArray());
if (m_currentlySelectedDebugPacketIndex != m_previouslySelectedDebugPacketIndex)
{
m_selectedDebugPacketCondition = 0;
m_previouslySelectedDebugPacketIndex = m_currentlySelectedDebugPacketIndex;
}
Color defaultGUIColor = GUI.color;
GUI.color = new Color(0.7f, 1f, 0.0f, 1f);
//Or add a new item to the List<> with a button
if (GUILayout.Button("Add", GUILayout.Width(60)))
{
debugPacketList.InsertArrayElementAtIndex(debugPacketList.arraySize);
SetDefaultDebugPacketValues(debugPacketList);
}
GUI.color = new Color(1f, 0.7f, 0.0f, 1f);
//Remove this index from the List
if (GUILayout.Button("Remove", GUILayout.Width(60)))
{
debugPacketList.DeleteArrayElementAtIndex(m_currentlySelectedDebugPacketIndex);
if (m_currentlySelectedDebugPacketIndex > 0)
{
m_currentlySelectedDebugPacketIndex--;
}
if (debugPacketList.arraySize < 1)
{
serializedObject.ApplyModifiedProperties();
return;
}
}
GUI.color = defaultGUIColor;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
//Display our list to the inspector window
SerializedProperty listItemSelected = debugPacketList.GetArrayElementAtIndex(m_currentlySelectedDebugPacketIndex);
SerializedProperty Active = listItemSelected.FindPropertyRelative("Active");
SerializedProperty Id = listItemSelected.FindPropertyRelative("Id");
SerializedProperty ExecuteOnce = listItemSelected.FindPropertyRelative("ExecuteOnce");
SerializedProperty InitSleepTime = listItemSelected.FindPropertyRelative("InitSleepTime");
SerializedProperty ExecuteSleepTime = listItemSelected.FindPropertyRelative("ExecuteSleepTime");
SerializedProperty ConditionEvaluation = listItemSelected.FindPropertyRelative("ConditionEvaluation");
SerializedProperty DebugConditions = listItemSelected.FindPropertyRelative("DebugConditions");
SerializedProperty MessageType = listItemSelected.FindPropertyRelative("MessageType");
SerializedProperty Message = listItemSelected.FindPropertyRelative("Message");
SerializedProperty TakeScreenshot = listItemSelected.FindPropertyRelative("TakeScreenshot");
SerializedProperty ScreenshotFileName = listItemSelected.FindPropertyRelative("ScreenshotFileName");
SerializedProperty DebugBreak = listItemSelected.FindPropertyRelative("DebugBreak");
SerializedProperty UnityEvents = listItemSelected.FindPropertyRelative("UnityEvents");
#endregion
EditorGUILayout.LabelField
(
label:
"[ PACKET ] - ID: " +
Id.intValue +
" (Conditions: " +
DebugConditions.arraySize +
")",
style: m_headerStyle2
);
EditorGUIUtility.labelWidth = 150;
EditorGUIUtility.fieldWidth = 35;
Active.boolValue = EditorGUILayout.Toggle
(
new GUIContent
(
text: "Active",
tooltip: "If false, it will not be checked"
),
value: Active.boolValue
);
Id.intValue = EditorGUILayout.IntField
(
new GUIContent
(
text: "ID",
tooltip: "Optional Id. It's used to get or remove DebugPackets in runtime"
),
value: Id.intValue
);
ExecuteOnce.boolValue = EditorGUILayout.Toggle
(
new GUIContent
(
text: "Execute once",
tooltip: "If true, once the actions are executed, this DebugPacket will delete itself"
),
value: ExecuteOnce.boolValue
);
InitSleepTime.floatValue = EditorGUILayout.FloatField
(
new GUIContent
(
text: "Init sleep time",
tooltip: "Time to wait before checking if conditions are met (use this to avoid low fps drops triggering the conditions when loading the game)"
),
value: InitSleepTime.floatValue
);
ExecuteSleepTime.floatValue = EditorGUILayout.FloatField
(
new GUIContent
(
text: "Sleep time after execute",
tooltip: "Time to wait before checking if conditions are met again (once they have already been met and if ExecuteOnce is false)"
),
value: ExecuteSleepTime.floatValue
);
EditorGUIUtility.labelWidth = defaultLabelWidth;
EditorGUIUtility.fieldWidth = defaultFieldWidth;
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.LabelField("[ CONDITIONS ] (" + DebugConditions.arraySize + ")", m_headerStyle2);
EditorGUILayout.PropertyField
(
ConditionEvaluation,
new GUIContent("Condition evaluation")
);
EditorGUILayout.Space();
if (DebugConditions.arraySize < 1)
{
DebugConditions.InsertArrayElementAtIndex(DebugConditions.arraySize);
m_selectedDebugPacketCondition = 0;
}
EditorGUILayout.BeginHorizontal();
List<string> debugPacketConditionNames = new List<string>();
for (int i = 0; i < DebugConditions.arraySize; i++)
{
SerializedProperty listItem = DebugConditions.GetArrayElementAtIndex(i);
// NOTE: If the Popup detects two equal strings, it just paints 1, that's why I always add the "i"
string conditionName = (i + 1).ToString() + " - ";
conditionName += GetComparerStringFromDebugVariable((GraphyDebugger.DebugVariable)listItem.FindPropertyRelative("Variable").intValue) + " ";
conditionName += GetComparerStringFromDebugComparer((GraphyDebugger.DebugComparer)listItem.FindPropertyRelative("Comparer").intValue) + " ";
conditionName += listItem.FindPropertyRelative("Value").floatValue.ToString();
debugPacketConditionNames.Add(conditionName);
}
m_selectedDebugPacketCondition = EditorGUILayout.Popup(m_selectedDebugPacketCondition, debugPacketConditionNames.ToArray());
GUI.color = new Color(0.7f, 1f, 0.0f, 1f);
if (GUILayout.Button("Add", GUILayout.Width(60)))
{
DebugConditions.InsertArrayElementAtIndex(DebugConditions.arraySize);
}
if (DebugConditions.arraySize > 1)
{
GUI.color = new Color(1f, 0.7f, 0.0f, 1f);
}
else
{
GUI.color = new Color(1f, 0.7f, 0.0f, 0.5f);
}
//Remove this index from the List
if (GUILayout.Button("Remove", GUILayout.Width(60)))
{
if (DebugConditions.arraySize > 1)
{
DebugConditions.DeleteArrayElementAtIndex(m_selectedDebugPacketCondition);
if (m_selectedDebugPacketCondition > 0)
{
m_selectedDebugPacketCondition--;
}
}
}
GUI.color = defaultGUIColor;
EditorGUILayout.EndHorizontal();
SerializedProperty conditionListItemSelected = DebugConditions.GetArrayElementAtIndex(m_selectedDebugPacketCondition);
SerializedProperty Variable = conditionListItemSelected.FindPropertyRelative("Variable");
SerializedProperty Comparer = conditionListItemSelected.FindPropertyRelative("Comparer");
SerializedProperty Value = conditionListItemSelected.FindPropertyRelative("Value");
EditorGUILayout.PropertyField
(
Variable,
new GUIContent("Variable")
);
EditorGUILayout.PropertyField
(
Comparer,
new GUIContent("Comparer")
);
EditorGUILayout.PropertyField
(
Value,
new GUIContent("Value")
);
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.LabelField("[ ACTIONS ]", m_headerStyle2);
EditorGUIUtility.labelWidth = 140;
EditorGUIUtility.fieldWidth = 35;
EditorGUILayout.PropertyField
(
MessageType,
new GUIContent("Message type")
);
EditorGUILayout.PropertyField(Message);
TakeScreenshot.boolValue = EditorGUILayout.Toggle
(
new GUIContent
(
text: "Take screenshot",
tooltip: "If true, it takes a screenshot and stores it. The location where the image is written to can include a directory/folder list. With no directory/folder list the image will be written into the Project folder. On mobile platforms the filename is appended to the persistent data path."
),
value: TakeScreenshot.boolValue
);
if (TakeScreenshot.boolValue)
{
EditorGUILayout.PropertyField
(
ScreenshotFileName,
new GUIContent
(
text: "Screenshot file name",
tooltip: "Avoid this characters: * . \" / \\ [ ] : ; | = , \n\nIt will have the date appended at the end to avoid overwriting."
)
);
}
DebugBreak.boolValue = EditorGUILayout.Toggle
(
new GUIContent
(
text: "Debug Break",
tooltip: "If true, it pauses the editor"
),
DebugBreak.boolValue
);
EditorGUILayout.PropertyField(UnityEvents);
EditorGUIUtility.labelWidth = defaultLabelWidth;
EditorGUIUtility.fieldWidth = defaultFieldWidth;
serializedObject.ApplyModifiedProperties();
}
#endregion
#region Methods -> Private
private void LoadGuiStyles()
{
string path = GetMonoScriptFilePath(this);
path = path.Split(new string[] { "Assets" }, StringSplitOptions.None)[1]
.Split(new string[] { "Tayx" }, StringSplitOptions.None)[0];
m_logoTexture = AssetDatabase.LoadAssetAtPath<Texture2D>
(
"Assets" +
path +
"Tayx/Graphy - Ultimate Stats Monitor/Textures/Debugger_Logo_" +
(EditorGUIUtility.isProSkin ? "White.png" : "Dark.png")
);
m_skin = AssetDatabase.LoadAssetAtPath<GUISkin>
(
"Assets" +
path +
"Tayx/Graphy - Ultimate Stats Monitor/GUI/Graphy.guiskin"
);
if (m_skin != null)
{
m_headerStyle1 = m_skin.GetStyle("Header1");
m_headerStyle2 = m_skin.GetStyle("Header2");
SetGuiStyleFontColor
(
guiStyle: m_headerStyle2,
color: EditorGUIUtility.isProSkin ? Color.white : Color.black
);
}
else
{
m_headerStyle1 = EditorStyles.boldLabel;
m_headerStyle2 = EditorStyles.boldLabel;
}
}
private void SetGuiStyleFontColor(GUIStyle guiStyle, Color color)
{
guiStyle.normal .textColor = color;
guiStyle.hover .textColor = color;
guiStyle.active .textColor = color;
guiStyle.focused .textColor = color;
guiStyle.onNormal .textColor = color;
guiStyle.onHover .textColor = color;
guiStyle.onActive .textColor = color;
guiStyle.onFocused .textColor = color;
}
private string GetMonoScriptFilePath(ScriptableObject scriptableObject)
{
MonoScript ms = MonoScript.FromScriptableObject(scriptableObject);
string filePath = AssetDatabase.GetAssetPath(ms);
FileInfo fi = new FileInfo(filePath);
if (fi.Directory != null)
{
filePath = fi.Directory.ToString();
return filePath.Replace
(
oldChar: '\\',
newChar: '/'
);
}
return null;
}
private void SetDefaultDebugPacketValues(SerializedProperty debugPacketSerializedProperty)
{
GraphyDebugger.DebugPacket debugPacket = new GraphyDebugger.DebugPacket();
debugPacketSerializedProperty.GetArrayElementAtIndex(debugPacketSerializedProperty.arraySize - 1)
.FindPropertyRelative("Active")
.boolValue = debugPacket.Active;
debugPacketSerializedProperty.GetArrayElementAtIndex(debugPacketSerializedProperty.arraySize - 1)
.FindPropertyRelative("Id")
.intValue = debugPacketSerializedProperty.arraySize;
debugPacketSerializedProperty.GetArrayElementAtIndex(debugPacketSerializedProperty.arraySize - 1)
.FindPropertyRelative("ExecuteOnce")
.boolValue = debugPacket.ExecuteOnce;
debugPacketSerializedProperty.GetArrayElementAtIndex(debugPacketSerializedProperty.arraySize - 1)
.FindPropertyRelative("InitSleepTime")
.floatValue = debugPacket.InitSleepTime;
debugPacketSerializedProperty.GetArrayElementAtIndex(debugPacketSerializedProperty.arraySize - 1)
.FindPropertyRelative("ExecuteSleepTime")
.floatValue = debugPacket.ExecuteSleepTime;
}
private string GetComparerStringFromDebugVariable(GraphyDebugger.DebugVariable debugVariable)
{
switch (debugVariable)
{
case GraphyDebugger.DebugVariable.Fps:
return "FPS Current";
case GraphyDebugger.DebugVariable.Fps_Min:
return "FPS Min";
case GraphyDebugger.DebugVariable.Fps_Max:
return "FPS Max";
case GraphyDebugger.DebugVariable.Fps_Avg:
return "FPS Avg";
case GraphyDebugger.DebugVariable.Ram_Allocated:
return "Ram Allocated";
case GraphyDebugger.DebugVariable.Ram_Reserved:
return "Ram Reserved";
case GraphyDebugger.DebugVariable.Ram_Mono:
return "Ram Mono";
case GraphyDebugger.DebugVariable.Audio_DB:
return "Audio DB";
default:
return null;
}
}
private string GetComparerStringFromDebugComparer(GraphyDebugger.DebugComparer debugComparer)
{
switch (debugComparer)
{
case GraphyDebugger.DebugComparer.Less_than:
return "<";
case GraphyDebugger.DebugComparer.Equals_or_less_than:
return "<=";
case GraphyDebugger.DebugComparer.Equals:
return "==";
case GraphyDebugger.DebugComparer.Equals_or_greater_than:
return ">=";
case GraphyDebugger.DebugComparer.Greater_than:
return ">";
default:
return null;
}
}
#endregion
}
} | 0 | 0.897393 | 1 | 0.897393 | game-dev | MEDIA | 0.814596 | game-dev | 0.974697 | 1 | 0.974697 |
reshadhstu/Unity-CoreToolkit | 7,308 | Editor/Helpers/SceneSwitcher.cs | using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UIElements;
using System.Reflection;
using System.Linq;
using System.IO;
using UnityEngine.SceneManagement;
namespace CoreToolkit.Editor.Helpers
{
[InitializeOnLoad]
public static class SceneSwitcher
{
private static string[] _sceneNames = Array.Empty<string>();
private static int _selectedIndex;
private static string _lastActiveScene = "";
private static VisualElement _toolbarUI;
private static float _positionOffset = 180f; // Move closer to the Play button
private static float _dropdownBoxHeight = 20f; // Dropdown button height
private static bool FetchAllScenes
{
get => EditorPrefs.GetBool("SceneSwitcher_FetchAllScenes", false);
set => EditorPrefs.SetBool("SceneSwitcher_FetchAllScenes", value);
}
static SceneSwitcher()
{
RefreshSceneList();
SelectCurrentScene(); // Automatically select the open scene
// Hook into the scene change events
EditorSceneManager.activeSceneChangedInEditMode += (prev, current) => UpdateSceneSelection();
EditorApplication.playModeStateChanged += OnPlayModeChanged;
EditorApplication.delayCall += AddToolbarUI;
}
private static void AddToolbarUI()
{
var toolbarType = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.Toolbar");
if (toolbarType == null) return;
var toolbars = Resources.FindObjectsOfTypeAll(toolbarType);
if (toolbars.Length == 0) return;
var toolbar = toolbars[0];
var rootField = toolbarType.GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance);
if (rootField == null) return;
var root = rootField.GetValue(toolbar) as VisualElement;
if (root == null) return;
var leftContainer = root.Q("ToolbarZoneLeftAlign");
if (leftContainer == null) return;
// Remove the old UI if it exists to prevent duplication
if (_toolbarUI != null)
{
leftContainer.Remove(_toolbarUI);
}
_toolbarUI = new IMGUIContainer(OnGUI);
_toolbarUI.style.marginLeft = _positionOffset;
leftContainer.Add(_toolbarUI);
}
private static void OnGUI()
{
CheckAndRefreshScenes();
if (_selectedIndex >= _sceneNames.Length)
_selectedIndex = 0;
bool isPlaying = EditorApplication.isPlaying; // Check if in Play Mode
GUILayout.BeginHorizontal();
// Fetch all scenes toggle button (Disabled in Play Mode)
EditorGUI.BeginDisabledGroup(isPlaying);
bool newFetchAllScenes = GUILayout.Toggle(FetchAllScenes, "All Scenes", "Button", GUILayout.Height(_dropdownBoxHeight));
if (newFetchAllScenes != FetchAllScenes)
{
FetchAllScenes = newFetchAllScenes;
RefreshSceneList();
SelectCurrentScene();
}
EditorGUI.EndDisabledGroup();
// Scene dropdown with the currently selected scene displayed (Disabled in Play Mode)
EditorGUI.BeginDisabledGroup(isPlaying);
GUIStyle popupStyle = new GUIStyle(EditorStyles.popup)
{
fixedHeight = _dropdownBoxHeight
};
int newIndex = EditorGUILayout.Popup(_selectedIndex, _sceneNames, popupStyle, GUILayout.Width(150), GUILayout.Height(_dropdownBoxHeight));
if (newIndex != _selectedIndex)
{
_selectedIndex = newIndex;
LoadScene(_sceneNames[_selectedIndex]);
}
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
}
private static void RefreshSceneList()
{
if (FetchAllScenes)
{
_sceneNames = Directory.GetFiles("Assets", "*.unity", SearchOption.AllDirectories)
.Select(Path.GetFileNameWithoutExtension)
.ToArray();
}
else
{
_sceneNames = EditorBuildSettings.scenes
.Where(scene => scene.enabled)
.Select(scene => Path.GetFileNameWithoutExtension(scene.path))
.ToArray();
}
}
private static void CheckAndRefreshScenes()
{
string[] currentScenes;
if (FetchAllScenes)
{
currentScenes = Directory.GetFiles("Assets", "*.unity", SearchOption.AllDirectories)
.Select(Path.GetFileNameWithoutExtension)
.ToArray();
}
else
{
currentScenes = EditorBuildSettings.scenes
.Where(scene => scene.enabled)
.Select(scene => Path.GetFileNameWithoutExtension(scene.path))
.ToArray();
}
if (!currentScenes.SequenceEqual(_sceneNames))
{
_sceneNames = currentScenes;
SelectCurrentScene();
}
}
static void SelectCurrentScene()
{
string currentScene = Path.GetFileNameWithoutExtension(SceneManager.GetActiveScene().path);
int index = System.Array.IndexOf(_sceneNames, currentScene);
if (index != -1)
{
_selectedIndex = index;
_lastActiveScene = currentScene;
}
}
private static void UpdateSceneSelection()
{
string currentScene = Path.GetFileNameWithoutExtension(SceneManager.GetActiveScene().path);
if (currentScene != _lastActiveScene)
{
_lastActiveScene = currentScene;
SelectCurrentScene();
}
}
private static void LoadScene(string sceneName)
{
string scenePath;
if (FetchAllScenes)
{
scenePath = Directory.GetFiles("Assets", "*.unity", SearchOption.AllDirectories)
.FirstOrDefault(path => Path.GetFileNameWithoutExtension(path) == sceneName);
}
else
{
scenePath = EditorBuildSettings.scenes
.FirstOrDefault(scene => scene.enabled && scene.path.Contains(sceneName))?.path;
}
if (!string.IsNullOrEmpty(scenePath))
{
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
EditorSceneManager.OpenScene(scenePath);
}
}
else
{
Debug.LogError("Scene not found: " + sceneName);
}
}
private static void OnPlayModeChanged(PlayModeStateChange state)
{
if (state is PlayModeStateChange.EnteredPlayMode or PlayModeStateChange.ExitingPlayMode)
{
EditorApplication.delayCall += AddToolbarUI;
}
}
}
} | 0 | 0.940597 | 1 | 0.940597 | game-dev | MEDIA | 0.725091 | game-dev | 0.981182 | 1 | 0.981182 |
the3dfxdude/7kaa | 1,980 | include/OISOAREA.h | /*
* Seven Kingdoms: Ancient Adversaries
*
* Copyright 1997,1998 Enlight Software Ltd.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
//Filename : OISOAREA.CPP
//Description : Object to determine an isolated area
//Owner : Alex
#ifndef __OISOAREA_H
#define __OISOAREA_H
//--------- define cross_dir ---------//
enum { CROSS_LINE_SAME_DIR=1,
CROSS_LINE_DIFF_DIR,
};
//--------- defne struct AreaInfo ---------//
struct AreaInfo
{
short x_loc;
short y_loc;
short distance;
char with_data;
};
//----------- Define class IsolateArea -----------//
class IsolateArea
{
public:
IsolateArea();
~IsolateArea();
void init();
void deinit();
void reset_area_info(AreaInfo *infoPtr);
char cal_direction(short sx, short sy, short dx, short dy);
int detect_isolate_area(short xLoc1, short yLoc1, short xLoc2, short yLoc2);
void process_move_around_boundary(char& dir, short& xLoc, short& yLoc);
int to_regions_line_left(char dir, int withVerticalCheck=0);
int is_isolate_area();
private:
AreaInfo same_region;
AreaInfo diff_region;
char regions_line_dir;
short regions_line_x_loc1;
short regions_line_y_loc1;
short regions_line_x_loc2;
short regions_line_y_loc2;
short region_check_x_offset;
short region_check_y_offset;
protected:
};
extern IsolateArea isolate_area;
//-----------------------------------------//
#endif
| 0 | 0.843022 | 1 | 0.843022 | game-dev | MEDIA | 0.428696 | game-dev | 0.619077 | 1 | 0.619077 |
geopaparazzi/libjsqlite-spatialite-android | 5,468 | libjsqlite-spatialite-android/spatialite-android-library/jni/gdal-2.0.0/frmts/pcidsk/sdk/core/metadataset_p.cpp | /******************************************************************************
*
* Purpose: Implementation of the MetadataSet class. This is a container
* for a set of metadata, and used by the file, channel and segment
* classes to manage metadata for themselves. It is not public
* to SDK users.
*
******************************************************************************
* Copyright (c) 2009
* PCI Geomatics, 50 West Wilmot Street, Richmond Hill, Ont, Canada
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "pcidsk_exception.h"
#include "core/metadataset.h"
#include "segment/metadatasegment.h"
#include <string>
using namespace PCIDSK;
/************************************************************************/
/* MetadataSet() */
/************************************************************************/
MetadataSet::MetadataSet()
{
this->file = NULL;
id = -1;
loaded = false;
}
/************************************************************************/
/* ~MetadataSet() */
/************************************************************************/
MetadataSet::~MetadataSet()
{
}
/************************************************************************/
/* Initialize() */
/************************************************************************/
void MetadataSet::Initialize( PCIDSKFile *file, const std::string& group, int id )
{
this->file = file;
this->group = group;
this->id = id;
}
/************************************************************************/
/* Load() */
/************************************************************************/
void MetadataSet::Load()
{
if( loaded )
return;
// This legitimately occurs in some situations, such for overview channel
// objects.
if( file == NULL )
{
loaded = true;
return;
}
PCIDSKSegment *seg = file->GetSegment( SEG_SYS , "METADATA");
if( seg == NULL )
{
loaded = true;
return;
}
MetadataSegment *md_seg = dynamic_cast<MetadataSegment *>( seg );
md_seg->FetchGroupMetadata( group.c_str(), id, md_set );
loaded = true;
}
/************************************************************************/
/* GetMetadataValue() */
/************************************************************************/
std::string MetadataSet::GetMetadataValue( const std::string& key )
{
if( !loaded )
Load();
if( md_set.count(key) == 0 )
return "";
else
return md_set[key];
}
/************************************************************************/
/* SetMetadataValue() */
/************************************************************************/
void MetadataSet::SetMetadataValue( const std::string& key, const std::string& value )
{
if( !loaded )
Load();
if( file == NULL )
{
ThrowPCIDSKException( "Attempt to set metadata on an unassociated MetadataSet, likely an overview channel." );
}
md_set[key] = value;
PCIDSKSegment *seg = file->GetSegment( SEG_SYS , "METADATA");
if( seg == NULL )
{
file->CreateSegment( "METADATA",
"Please do not modify this metadata segment.",
SEG_SYS, 0 );
seg = file->GetSegment( SEG_SYS , "METADATA");
}
MetadataSegment *md_seg = dynamic_cast<MetadataSegment *>( seg );
md_seg->SetGroupMetadataValue( group.c_str(), id, key, value );
}
/************************************************************************/
/* GetMetadataKeys() */
/************************************************************************/
std::vector<std::string> MetadataSet::GetMetadataKeys()
{
if( !loaded )
Load();
std::vector<std::string> keys;
std::map<std::string,std::string>::iterator it;
for( it = md_set.begin(); it != md_set.end(); it++ )
{
keys.push_back( (*it).first );
}
return keys;
}
| 0 | 0.672201 | 1 | 0.672201 | game-dev | MEDIA | 0.294954 | game-dev | 0.606998 | 1 | 0.606998 |
spirthack/CSGOSimple | 13,300 | CSGOSimple/features/visuals.cpp | #include <algorithm>
#include "visuals.hpp"
#include "../options.hpp"
#include "../helpers/math.hpp"
#include "../helpers/utils.hpp"
RECT GetBBox(C_BaseEntity* ent)
{
RECT rect{};
auto collideable = ent->GetCollideable();
if (!collideable)
return rect;
auto min = collideable->OBBMins();
auto max = collideable->OBBMaxs();
const matrix3x4_t& trans = ent->m_rgflCoordinateFrame();
Vector points[] = {
Vector(min.x, min.y, min.z),
Vector(min.x, max.y, min.z),
Vector(max.x, max.y, min.z),
Vector(max.x, min.y, min.z),
Vector(max.x, max.y, max.z),
Vector(min.x, max.y, max.z),
Vector(min.x, min.y, max.z),
Vector(max.x, min.y, max.z)
};
Vector pointsTransformed[8];
for (int i = 0; i < 8; i++) {
Math::VectorTransform(points[i], trans, pointsTransformed[i]);
}
Vector screen_points[8] = {};
for (int i = 0; i < 8; i++) {
if (!Math::WorldToScreen(pointsTransformed[i], screen_points[i]))
return rect;
}
auto left = screen_points[0].x;
auto top = screen_points[0].y;
auto right = screen_points[0].x;
auto bottom = screen_points[0].y;
for (int i = 1; i < 8; i++) {
if (left > screen_points[i].x)
left = screen_points[i].x;
if (top < screen_points[i].y)
top = screen_points[i].y;
if (right < screen_points[i].x)
right = screen_points[i].x;
if (bottom > screen_points[i].y)
bottom = screen_points[i].y;
}
return RECT{ (long)left, (long)top, (long)right, (long)bottom };
}
Visuals::Visuals()
{
InitializeCriticalSection(&cs);
}
Visuals::~Visuals() {
DeleteCriticalSection(&cs);
}
//--------------------------------------------------------------------------------
void Visuals::Render() {
}
//--------------------------------------------------------------------------------
bool Visuals::Player::Begin(C_BasePlayer* pl)
{
if (pl->IsDormant() || !pl->IsAlive())
return false;
ctx.pl = pl;
ctx.is_enemy = g_LocalPlayer->m_iTeamNum() != pl->m_iTeamNum();
ctx.is_visible = g_LocalPlayer->CanSeePlayer(pl, HITBOX_CHEST);
if (!ctx.is_enemy && g_Options.esp_enemies_only)
return false;
ctx.clr = ctx.is_enemy ? (ctx.is_visible ? g_Options.color_esp_enemy_visible : g_Options.color_esp_enemy_occluded) : (ctx.is_visible ? g_Options.color_esp_ally_visible : g_Options.color_esp_ally_occluded);
auto head = pl->GetHitboxPos(HITBOX_HEAD);
auto origin = pl->m_vecOrigin();
head.z += 15;
if (!Math::WorldToScreen(head, ctx.head_pos) ||
!Math::WorldToScreen(origin, ctx.feet_pos))
return false;
auto h = fabs(ctx.head_pos.y - ctx.feet_pos.y);
auto w = h / 1.65f;
ctx.bbox.left = static_cast<long>(ctx.feet_pos.x - w * 0.5f);
ctx.bbox.right = static_cast<long>(ctx.bbox.left + w);
ctx.bbox.bottom = static_cast<long>(ctx.feet_pos.y);
ctx.bbox.top = static_cast<long>(ctx.head_pos.y);
return true;
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderBox() {
Render::Get().RenderBoxByType(ctx.bbox.left, ctx.bbox.top, ctx.bbox.right, ctx.bbox.bottom, ctx.clr, 1);
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderName()
{
player_info_t info = ctx.pl->GetPlayerInfo();
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, info.szName);
Render::Get().RenderText(info.szName, ctx.feet_pos.x - sz.x / 2, ctx.head_pos.y - sz.y, 14.f, ctx.clr);
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderHealth()
{
auto hp = ctx.pl->m_iHealth();
float box_h = (float)fabs(ctx.bbox.bottom - ctx.bbox.top);
//float off = (box_h / 6.f) + 5;
float off = 8;
int height = (box_h * hp) / 100;
int green = int(hp * 2.55f);
int red = 255 - green;
int x = ctx.bbox.left - off;
int y = ctx.bbox.top;
int w = 4;
int h = box_h;
Render::Get().RenderBox(x, y, x + w, y + h, Color::Black, 1.f, true);
Render::Get().RenderBox(x + 1, y + 1, x + w - 1, y + height - 2, Color(red, green, 0, 255), 1.f, true);
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderArmour()
{
auto armour = ctx.pl->m_ArmorValue();
float box_h = (float)fabs(ctx.bbox.bottom - ctx.bbox.top);
//float off = (box_h / 6.f) + 5;
float off = 4;
int height = (((box_h * armour) / 100));
int x = ctx.bbox.right + off;
int y = ctx.bbox.top;
int w = 4;
int h = box_h;
Render::Get().RenderBox(x, y, x + w, y + h, Color::Black, 1.f, true);
Render::Get().RenderBox(x + 1, y + 1, x + w - 1, y + height - 2, Color(0, 50, 255, 255), 1.f, true);
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderWeaponName()
{
auto weapon = ctx.pl->m_hActiveWeapon().Get();
if (!weapon) return;
if (!weapon->GetCSWeaponData()) return;
auto text = weapon->GetCSWeaponData()->szWeaponName + 7;
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, text);
Render::Get().RenderText(text, ctx.feet_pos.x, ctx.feet_pos.y, 14.f, ctx.clr, true,
g_pDefaultFont);
}
//--------------------------------------------------------------------------------
void Visuals::Player::RenderSnapline()
{
int screen_w, screen_h;
g_EngineClient->GetScreenSize(screen_w, screen_h);
Render::Get().RenderLine(screen_w / 2.f, (float)screen_h,
ctx.feet_pos.x, ctx.feet_pos.y, ctx.clr);
}
//--------------------------------------------------------------------------------
void Visuals::RenderCrosshair()
{
int w, h;
g_EngineClient->GetScreenSize(w, h);
int cx = w / 2;
int cy = h / 2;
Render::Get().RenderLine(cx - 25, cy, cx + 25, cy, g_Options.color_esp_crosshair);
Render::Get().RenderLine(cx, cy - 25, cx, cy + 25, g_Options.color_esp_crosshair);
}
//--------------------------------------------------------------------------------
void Visuals::RenderWeapon(C_BaseCombatWeapon* ent)
{
auto clean_item_name = [](const char* name) -> const char* {
if (name[0] == 'C')
name++;
auto start = strstr(name, "Weapon");
if (start != nullptr)
name = start + 6;
return name;
};
// We don't want to Render weapons that are being held
if (ent->m_hOwnerEntity().IsValid())
return;
auto bbox = GetBBox(ent);
if (bbox.right == 0 || bbox.bottom == 0)
return;
Render::Get().RenderBox(bbox, g_Options.color_esp_weapons);
auto name = clean_item_name(ent->GetClientClass()->m_pNetworkName);
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, name);
int w = bbox.right - bbox.left;
Render::Get().RenderText(name, ImVec2((bbox.left + w * 0.5f) - sz.x * 0.5f, bbox.bottom + 1), 14.f, g_Options.color_esp_weapons);
}
//--------------------------------------------------------------------------------
void Visuals::RenderDefuseKit(C_BaseEntity* ent)
{
if (ent->m_hOwnerEntity().IsValid())
return;
auto bbox = GetBBox(ent);
if (bbox.right == 0 || bbox.bottom == 0)
return;
Render::Get().RenderBox(bbox, g_Options.color_esp_defuse);
auto name = "Defuse Kit";
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, name);
int w = bbox.right - bbox.left;
Render::Get().RenderText(name, ImVec2((bbox.left + w * 0.5f) - sz.x * 0.5f, bbox.bottom + 1), 14.f, g_Options.color_esp_defuse);
}
//--------------------------------------------------------------------------------
void Visuals::RenderPlantedC4(C_BaseEntity* ent)
{
auto bbox = GetBBox(ent);
if (bbox.right == 0 || bbox.bottom == 0)
return;
Render::Get().RenderBox(bbox, g_Options.color_esp_c4);
int bombTimer = std::ceil(ent->m_flC4Blow() - g_GlobalVars->curtime);
std::string timer = std::to_string(bombTimer);
auto name = (bombTimer < 0.f) ? "Bomb" : timer;
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, name.c_str());
int w = bbox.right - bbox.left;
Render::Get().RenderText(name, ImVec2((bbox.left + w * 0.5f) - sz.x * 0.5f, bbox.bottom + 1), 14.f, g_Options.color_esp_c4);
}
//--------------------------------------------------------------------------------
void Visuals::RenderItemEsp(C_BaseEntity* ent)
{
std::string itemstr = "Undefined";
const model_t * itemModel = ent->GetModel();
if (!itemModel)
return;
studiohdr_t * hdr = g_MdlInfo->GetStudiomodel(itemModel);
if (!hdr)
return;
itemstr = hdr->szName;
if (ent->GetClientClass()->m_ClassID == ClassId_CBumpMine)
itemstr = "";
else if (itemstr.find("case_pistol") != std::string::npos)
itemstr = "Pistol Case";
else if (itemstr.find("case_light_weapon") != std::string::npos)
itemstr = "Light Case";
else if (itemstr.find("case_heavy_weapon") != std::string::npos)
itemstr = "Heavy Case";
else if (itemstr.find("case_explosive") != std::string::npos)
itemstr = "Explosive Case";
else if (itemstr.find("case_tools") != std::string::npos)
itemstr = "Tools Case";
else if (itemstr.find("random") != std::string::npos)
itemstr = "Airdrop";
else if (itemstr.find("dz_armor_helmet") != std::string::npos)
itemstr = "Full Armor";
else if (itemstr.find("dz_helmet") != std::string::npos)
itemstr = "Helmet";
else if (itemstr.find("dz_armor") != std::string::npos)
itemstr = "Armor";
else if (itemstr.find("upgrade_tablet") != std::string::npos)
itemstr = "Tablet Upgrade";
else if (itemstr.find("briefcase") != std::string::npos)
itemstr = "Briefcase";
else if (itemstr.find("parachutepack") != std::string::npos)
itemstr = "Parachute";
else if (itemstr.find("dufflebag") != std::string::npos)
itemstr = "Cash Dufflebag";
else if (itemstr.find("ammobox") != std::string::npos)
itemstr = "Ammobox";
else if (itemstr.find("dronegun") != std::string::npos)
itemstr = "Turrel";
else if (itemstr.find("exojump") != std::string::npos)
itemstr = "Exojump";
else if (itemstr.find("healthshot") != std::string::npos)
itemstr = "Healthshot";
else {
/*May be you will search some missing items..*/
/*static std::vector<std::string> unk_loot;
if (std::find(unk_loot.begin(), unk_loot.end(), itemstr) == unk_loot.end()) {
Utils::ConsolePrint(itemstr.c_str());
unk_loot.push_back(itemstr);
}*/
return;
}
auto bbox = GetBBox(ent);
if (bbox.right == 0 || bbox.bottom == 0)
return;
auto sz = g_pDefaultFont->CalcTextSizeA(14.f, FLT_MAX, 0.0f, itemstr.c_str());
int w = bbox.right - bbox.left;
//Render::Get().RenderBox(bbox, g_Options.color_esp_item);
Render::Get().RenderText(itemstr, ImVec2((bbox.left + w * 0.5f) - sz.x * 0.5f, bbox.bottom + 1), 14.f, g_Options.color_esp_item);
}
//--------------------------------------------------------------------------------
void Visuals::ThirdPerson() {
if (!g_LocalPlayer)
return;
if (g_Options.misc_thirdperson && g_LocalPlayer->IsAlive())
{
if (!g_Input->m_fCameraInThirdPerson)
{
g_Input->m_fCameraInThirdPerson = true;
}
float dist = g_Options.misc_thirdperson_dist;
QAngle *view = g_LocalPlayer->GetVAngles();
trace_t tr;
Ray_t ray;
Vector desiredCamOffset = Vector(cos(DEG2RAD(view->yaw)) * dist,
sin(DEG2RAD(view->yaw)) * dist,
sin(DEG2RAD(-view->pitch)) * dist
);
//cast a ray from the Current camera Origin to the Desired 3rd person Camera origin
ray.Init(g_LocalPlayer->GetEyePos(), (g_LocalPlayer->GetEyePos() - desiredCamOffset));
CTraceFilter traceFilter;
traceFilter.pSkip = g_LocalPlayer;
g_EngineTrace->TraceRay(ray, MASK_SHOT, &traceFilter, &tr);
Vector diff = g_LocalPlayer->GetEyePos() - tr.endpos;
float distance2D = sqrt(abs(diff.x * diff.x) + abs(diff.y * diff.y));// Pythagorean
bool horOK = distance2D > (dist - 2.0f);
bool vertOK = (abs(diff.z) - abs(desiredCamOffset.z) < 3.0f);
float cameraDistance;
if (horOK && vertOK) // If we are clear of obstacles
{
cameraDistance = dist; // go ahead and set the distance to the setting
}
else
{
if (vertOK) // if the Vertical Axis is OK
{
cameraDistance = distance2D * 0.95f;
}
else// otherwise we need to move closer to not go into the floor/ceiling
{
cameraDistance = abs(diff.z) * 0.95f;
}
}
g_Input->m_fCameraInThirdPerson = true;
g_Input->m_vecCameraOffset.z = cameraDistance;
}
else
{
g_Input->m_fCameraInThirdPerson = false;
}
}
void Visuals::AddToDrawList() {
for (auto i = 1; i <= g_EntityList->GetHighestEntityIndex(); ++i) {
auto entity = C_BaseEntity::GetEntityByIndex(i);
if (!entity)
continue;
if (entity == g_LocalPlayer && !g_Input->m_fCameraInThirdPerson)
continue;
if (i <= g_GlobalVars->maxClients) {
auto player = Player();
if (player.Begin((C_BasePlayer*)entity)) {
if (g_Options.esp_player_snaplines) player.RenderSnapline();
if (g_Options.esp_player_boxes) player.RenderBox();
if (g_Options.esp_player_weapons) player.RenderWeaponName();
if (g_Options.esp_player_names) player.RenderName();
if (g_Options.esp_player_health) player.RenderHealth();
if (g_Options.esp_player_armour) player.RenderArmour();
}
}
else if (g_Options.esp_dropped_weapons && entity->IsWeapon())
RenderWeapon(static_cast<C_BaseCombatWeapon*>(entity));
else if (g_Options.esp_dropped_weapons && entity->IsDefuseKit())
RenderDefuseKit(entity);
else if (entity->IsPlantedC4() && g_Options.esp_planted_c4)
RenderPlantedC4(entity);
else if (entity->IsLoot() && g_Options.esp_items)
RenderItemEsp(entity);
}
if (g_Options.esp_crosshair)
RenderCrosshair();
}
| 0 | 0.925144 | 1 | 0.925144 | game-dev | MEDIA | 0.623419 | game-dev,graphics-rendering | 0.969226 | 1 | 0.969226 |
5zig-reborn/The-5zig-Mod | 6,015 | mod/src/main/java/eu/the5zig/mod/gui/GuiProfile.java | /*
* Copyright (c) 2019-2020 5zig Reborn
* Copyright (c) 2015-2019 5zig
*
* This file is part of The 5zig Mod
* The 5zig Mod 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.
*
* The 5zig Mod 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 The 5zig Mod. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.the5zig.mod.gui;
import com.google.common.collect.Lists;
import eu.the5zig.mod.I18n;
import eu.the5zig.mod.MinecraftFactory;
import eu.the5zig.mod.The5zigMod;
import eu.the5zig.mod.chat.entity.Rank;
import eu.the5zig.mod.gui.elements.*;
import eu.the5zig.mod.render.Base64Renderer;
import eu.the5zig.util.Utils;
import eu.the5zig.util.minecraft.ChatColor;
import java.util.List;
/**
* Created by 5zig.
* All rights reserved © 2015
*/
public class GuiProfile extends GuiOptions implements CenteredTextfieldCallback {
private static final Base64Renderer base64Renderer = new Base64Renderer();
private List<Row> rows = Lists.newArrayList();
public GuiProfile(Gui lastScreen) {
super(lastScreen);
}
@Override
protected void drawScreen(int mouseX, int mouseY, float partialTicks) {
if ((base64Renderer.getBase64String() == null || !base64Renderer.getBase64String().equals(
The5zigMod.getSkinManager().getBase64EncodedSkin(The5zigMod.getDataManager().getUniqueId()))) && The5zigMod.getSkinManager().getBase64EncodedSkin(
The5zigMod.getDataManager().getUniqueId()) != null)
base64Renderer.setBase64String(The5zigMod.getSkinManager().getBase64EncodedSkin(The5zigMod.getDataManager().getUniqueId()),
"player_skin/" + The5zigMod.getDataManager().getUniqueId());
base64Renderer.renderImage(getWidth() / 2 - 155, 40, 88, 88);
}
@Override
public void initGui() {
addButton(The5zigMod.getVars().createButton(200, getWidth() / 2 - 100, getHeight() / 6 + 170, 200, 20, MinecraftFactory.getVars().translate("gui.done")));
rows.clear();
int maxWidth = getWidth() / 2 + 155 - (getWidth() / 2 - 155 + 16 + 88) - 10;
rows.add(new BasicRow(ChatColor.UNDERLINE + I18n.translate("profile.title"), maxWidth) {
@Override
public int getLineHeight() {
return 14;
}
});
rows.add(new BasicRow(String.format("%s%s: %s#%s", ChatColor.YELLOW, I18n.translate("profile.id"), ChatColor.RESET, The5zigMod.getDataManager().getProfile().getId()), maxWidth));
rows.add(new BasicRow(String.format("%s%s: %s", ChatColor.YELLOW, I18n.translate("profile.name"), The5zigMod.getDataManager().getColoredName()), maxWidth));
rows.add(new BasicRow(String.format("%s%s: %s", ChatColor.YELLOW, I18n.translate("profile.first_login_time"), ChatColor.RESET + Utils.convertToDate(
The5zigMod.getDataManager().getProfile().getFirstTime()).replace("Today", I18n.translate("profile.today")).replace("Yesterday", I18n.translate("profile.yesterday"))),
maxWidth));
rows.add(new BasicRow(String.format("%s%s: %s", ChatColor.YELLOW, I18n.translate("profile.rank"),
Rank.buildList(The5zigMod.getDataManager().getProfile().getRank())), maxWidth));
int x = getWidth() / 2 - 155 + 16 + 88 + The5zigMod.getVars().getStringWidth(ChatColor.YELLOW + I18n.translate("profile.message") + ":") + 10;
rows.add(new ButtonRow(
The5zigMod.getVars().createStringButton(9, x, 88 + 40, The5zigMod.getVars().getStringWidth(I18n.translate("profile.edit")) + 2, 9, I18n.translate("profile.edit")), null) {
@Override
public void draw(int x, int y) {
The5zigMod.getVars().drawString(ChatColor.YELLOW + I18n.translate("profile.message") + ":", x + 2, y + 2);
}
@Override
public int getLineHeight() {
return 12;
}
});
rows.add(new BasicRow(The5zigMod.getDataManager().getProfile().getProfileMessage(), maxWidth));
IGuiList statusMessage = The5zigMod.getVars().createGuiList(null, getWidth(), getHeight(), 40, 40 + 110, getWidth() / 2 - 155 + 16 + 88, getWidth() / 2 + 155, rows);
statusMessage.setBottomPadding(4);
statusMessage.setRowWidth(400);
statusMessage.setLeftbound(true);
statusMessage.setDrawSelection(false);
statusMessage.setScrollX(getWidth() / 2 + 155 - 5);
addGuiList(statusMessage);
addButton(The5zigMod.getVars().createButton(1, getWidth() / 2 - 155, getHeight() / 6 + 120, 150, 20, I18n.translate("profile.settings.view")));
addButton(The5zigMod.getVars().createButton(2, getWidth() / 2 + 5, getHeight() / 6 + 120, 150, 20, I18n.translate("chat.settings")));
addButton(The5zigMod.getVars().createButton(3, getWidth() / 2 - 155, getHeight() / 6 + 144, 150, 20, I18n.translate("profile.blocked_contacts")));
addButton(The5zigMod.getVars().createButton(4, getWidth() / 2 + 5, getHeight() / 6 + 144, 150, 20, I18n.translate("profile.show_statistics")));
}
@Override
protected void actionPerformed(IButton button) {
if (button.getId() == 1) {
The5zigMod.getVars().displayScreen(new GuiSettings(this, "profile_settings"));
}
if (button.getId() == 2) {
The5zigMod.getVars().displayScreen(new GuiSettings(this, "chat_settings"));
}
if (button.getId() == 3) {
The5zigMod.getVars().displayScreen(new GuiBlockedUsers(this));
}
if (button.getId() == 4) {
The5zigMod.getVars().displayScreen(new GuiNetworkStatistics(this));
}
if (button.getId() == 9) {
The5zigMod.getVars().displayScreen(new GuiCenteredTextfield(this, this, 255));
}
}
@Override
public void onDone(String text) {
The5zigMod.getDataManager().getProfile().setProfileMessage(text);
}
@Override
public String title() {
return I18n.translate("profile.enter_new_profile_message");
}
@Override
public String getTitleKey() {
return "profile.title";
}
}
| 0 | 0.828277 | 1 | 0.828277 | game-dev | MEDIA | 0.762742 | game-dev | 0.952711 | 1 | 0.952711 |
UBCx-Software-Engineering/screencastmario | 2,084 | src/items/Item.ts | import {Matter} from '../matter/Matter';
import {Level} from '../engine/Level';
import {ItemFigure} from './ItemFigure';
import {Figure} from '../figures/Figure';
import {
basepath,
Direction,
MarioState,
SizeState,
GroundBlocking,
CollisionType,
DeathMode,
MushroomMode,
images,
setup
} from '../engine/constants'
export class Item extends Matter {
isBouncing: boolean;
bounceFrames: number;
bounceStep: number;
bounceDir: number;
bounceCount: number;
activated: boolean;
isBlocking: boolean;
constructor(x: number, y: number, isBlocking: boolean, level: Level) {
super(x, y, isBlocking ? GroundBlocking.all : GroundBlocking.none, level);
this.isBouncing = false;
this.bounceCount = 0;
this.bounceFrames = Math.floor(50 / setup.interval);
this.bounceStep = Math.ceil(10 / this.bounceFrames);
this.bounceDir = 1;
this.isBlocking = isBlocking;
this.activated = false;
this.addToany(level);
}
addToany(level: Level) {
level.items.push(this);
}
activate(from: Figure) {
this.activated = true;
}
bounce() {
this.isBouncing = true;
for (var i = this.level.figures.length; i--;) {
var fig = this.level.figures[i];
if (fig.y === this.y + 32 && fig.x >= this.x - 16 && fig.x <= this.x + 16) {
if (fig instanceof ItemFigure)
fig.setVelocity(fig.vx, setup.bounce);
else
fig.die();
}
}
}
playFrame() {
if (this.isBouncing) {
this.view.css({'bottom': (this.bounceDir > 0 ? '+' : '-') + '=' + this.bounceStep + 'px'});
this.bounceCount += this.bounceDir;
if (this.bounceCount === this.bounceFrames)
this.bounceDir = -1;
else if (this.bounceCount === 0) {
this.bounceDir = 1;
this.isBouncing = false;
}
}
super.playFrame();
}
}
| 0 | 0.839307 | 1 | 0.839307 | game-dev | MEDIA | 0.943175 | game-dev | 0.880703 | 1 | 0.880703 |
google/lullaby | 11,455 | redux/redux/engines/animation/processor/spline_processor.cc | /*
Copyright 2017-2022 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "redux/engines/animation/processor/spline_processor.h"
#include "redux/engines/animation/common.h"
namespace redux {
inline float DurationToSplineTime(absl::Duration duration) {
return static_cast<float>(absl::ToDoubleMilliseconds(duration));
}
inline absl::Duration SplineTimeToDuration(float time) {
return absl::Milliseconds(time);
}
inline SplinePlayback AsSplinePlayback(const AnimationPlayback& anim) {
SplinePlayback spline;
spline.playback_rate = anim.playback_rate;
spline.blend_x = DurationToSplineTime(anim.blend_time);
spline.start_x = DurationToSplineTime(anim.start_time);
spline.y_offset = anim.value_offset;
spline.y_scale = anim.value_scale;
spline.repeat = anim.repeat;
return spline;
}
SplineMotivator SplineProcessor::AllocateMotivator(int dimensions) {
SplineMotivator motivator;
AllocateMotivatorIndices(&motivator, dimensions);
return motivator;
}
void SplineProcessor::SetSplines(Motivator::Index index, int dimensions,
const CompactSpline* splines,
const AnimationPlayback& playback) {
// Return the local splines to the spline pool. We use external splines now.
for (int i = index; i < index + dimensions; ++i) {
FreeSplineForIndex(i);
}
// Initialize spline to follow way points.
// Snaps the current value and velocity to the way point's start value
// and velocity.
interpolator_.SetSplines(index, dimensions, splines,
AsSplinePlayback(playback));
}
void SplineProcessor::SetTargets(Motivator::Index index, int dimensions,
const float* values, const float* velocities,
absl::Duration time) {
for (int i = 0; i < dimensions; ++i) {
CreateSplineToTarget(index + i, values[i], velocities[i], time);
}
}
void SplineProcessor::AdvanceFrame(absl::Duration delta_time) {
Defragment();
auto spline_time = DurationToSplineTime(delta_time);
interpolator_.AdvanceFrame(spline_time);
}
// Accessors to allow the user to get and set simluation values.
const float* SplineProcessor::Values(Motivator::Index index) const {
return interpolator_.Ys(index);
}
void SplineProcessor::Velocities(Motivator::Index index, int dimensions,
float* out) const {
interpolator_.Derivatives(index, dimensions, out);
}
void SplineProcessor::Directions(Motivator::Index index, int dimensions,
float* out) const {
interpolator_.DerivativesWithoutPlayback(index, dimensions, out);
}
void SplineProcessor::TargetValues(Motivator::Index index, int dimensions,
float* out) const {
interpolator_.EndYs(index, dimensions, out);
}
void SplineProcessor::TargetVelocities(Motivator::Index index, int dimensions,
float* out) const {
interpolator_.EndDerivatives(index, dimensions, out);
}
void SplineProcessor::Differences(Motivator::Index index, int dimensions,
float* out) const {
interpolator_.YDifferencesToEnd(index, dimensions, out);
}
absl::Duration SplineProcessor::TimeRemaining(Motivator::Index index,
int dimensions) const {
float greatest = std::numeric_limits<float>::min();
for (int i = 0; i < dimensions; ++i) {
const float spline_time =
interpolator_.EndX(index + i) - interpolator_.X(index + i);
greatest = std::max(greatest, spline_time);
}
return SplineTimeToDuration(greatest);
}
absl::Duration SplineProcessor::SplineTime(Motivator::Index index) const {
return SplineTimeToDuration(interpolator_.X(index));
}
void SplineProcessor::Splines(Motivator::Index index, int dimensions,
const CompactSpline** splines) const {
interpolator_.Splines(index, dimensions, splines);
}
void SplineProcessor::SetSplineTime(Motivator::Index index, int dimensions,
absl::Duration time) {
interpolator_.SetXs(index, dimensions, DurationToSplineTime(time));
}
void SplineProcessor::SetSplinePlaybackRate(Motivator::Index index,
int dimensions,
float playback_rate) {
interpolator_.SetPlaybackRates(index, dimensions, playback_rate);
}
void SplineProcessor::SetSplineRepeating(Motivator::Index index, int dimensions,
bool repeat) {
interpolator_.SetRepeating(index, dimensions, repeat);
}
bool SplineProcessor::Settled(Motivator::Index index, int dimensions,
float max_difference, float max_velocity) const {
for (int i = 0; i < dimensions; ++i) {
float difference = 0.f;
interpolator_.YDifferencesToEnd(index + i, 1, &difference);
if (std::fabs(difference) > max_difference) {
return false;
}
float velocity = 0.f;
interpolator_.Derivatives(index + i, 1, &velocity);
if (std::fabs(velocity) > max_velocity) {
return false;
}
}
return true;
}
void SplineProcessor::CreateSplineToTarget(Motivator::Index index, float value,
float velocity,
absl::Duration time) {
// If the first node specifies time=0 or there is no valid data in the
// interpolator, we want to override the current values with the values
// specified in the first node.
const bool override_current =
time == absl::ZeroDuration() || !interpolator_.Valid(index);
// TODO(b/65298927): It seems that the animation pipeline can produce data
// that is out of range. Instead of just using |value| directly, if
// the interpolator is doing modular arithmetic, normalize the y value to
// the modulator's range.
const Interval& modular_range = interpolator_.ModularRange(index);
const float node_y =
modular_range.Size() > -0.f
? NormalizeWildValueWithinInterval(modular_range, value)
: value;
const float start_y =
override_current ? node_y : interpolator_.NormalizedY(index);
float velocity_at_index = 0.f;
if (!override_current) {
Velocities(index, 1, &velocity_at_index);
}
const float start_derivative =
override_current ? velocity : velocity_at_index;
CompactSpline* spline = data_[index].get();
if (spline == nullptr) {
// The default number of nodes is enough.
data_[index] = AllocateSpline(CompactSpline::kDefaultMaxNodes);
spline = data_[index].get();
}
Interval y_range;
if (interpolator_.ModularArithmetic(index)) {
// For modular splines, we need to expand the spline's y-range to match
// the number of nodes in the spline. It's possible for the spline to jump
// up the entire range every node, so the range has to be broad enough
// to hold it all.
//
// Note that we only normalize the first value of the spline, and
// subsequent values are allowed to curve out of the normalized range.
y_range = interpolator_.ModularRange(index).Scaled(1.f);
} else {
// Add some buffer to the y-range to allow for intermediate nodes
// that go above or below the supplied nodes.
static constexpr float kYRangeBufferPercent = 1.2f;
// Calculate the union of the y ranges in the target, then expand it a
// little to allow for intermediate nodes that jump slightly beyond the
// union's range.
y_range = Interval(std::min(value, start_y), std::max(value, start_y));
y_range = y_range.Scaled(kYRangeBufferPercent);
}
const float spline_time = DurationToSplineTime(time);
const float x_granularity = CompactSpline::RecommendXGranularity(spline_time);
spline->Init(y_range, x_granularity);
spline->AddNode(0.0f, start_y, start_derivative);
float y = value;
if (!override_current) {
// Use modular arithmetic for ranged values.
if (modular_range.Size() > 0.f) {
const float target_y = NormalizeWildValueWithinInterval(modular_range, y);
const float x = target_y - start_y;
const float length = modular_range.Size();
const float adjustment = x <= modular_range.min ? length
: x > modular_range.max ? -length
: 0.f;
y = start_y + x + adjustment;
}
spline->AddNode(spline_time, y, velocity, kAddWithoutModification);
}
// Point the interpolator at the spline we just created. Always start our
// spline at time 0.
interpolator_.SetSplines(index, 1, spline, SplinePlayback());
}
bool SplineProcessor::SupportsCloning() { return true; }
void SplineProcessor::CloneIndices(Motivator::Index dst, Motivator::Index src,
int dimensions, AnimationEngine* engine) {
interpolator_.CopyIndices(
dst, src, dimensions,
[this](Motivator::Index index, const CompactSpline* src_spline) {
CompactSplinePtr dest_spline = AllocateSpline(src_spline->max_nodes());
*dest_spline = *src_spline;
data_[index] = std::move(dest_spline);
return data_[index].get();
});
}
void SplineProcessor::ResetIndices(Motivator::Index index, int dimensions) {
// Clear reference to this spline.
interpolator_.ClearSplines(index, dimensions);
// Return splines to the pool of splines.
for (Motivator::Index i = index; i < index + dimensions; ++i) {
FreeSplineForIndex(i);
}
}
void SplineProcessor::MoveIndices(Motivator::Index old_index,
Motivator::Index new_index, int dimensions) {
for (int i = 0; i < dimensions; ++i) {
using std::swap;
swap(data_[new_index + i], data_[old_index + i]);
data_[old_index + i].reset();
}
interpolator_.MoveIndices(old_index, new_index, dimensions);
}
void SplineProcessor::SetNumIndices(Motivator::Index num_indices) {
data_.resize(num_indices);
interpolator_.SetNumIndices(num_indices);
}
CompactSplinePtr SplineProcessor::AllocateSpline(CompactSplineIndex max_nodes) {
// Return a spline from the pool. Eventually we'll reach a high water mark
// and we will stop allocating new splines. The returned spline must have
// enough nodes.
for (size_t i = 0; i < spline_pool_.size(); ++i) {
if (spline_pool_[i]->max_nodes() >= max_nodes) {
using std::swap;
swap(spline_pool_[i], spline_pool_.back());
CompactSplinePtr spline = std::move(spline_pool_.back());
spline_pool_.pop_back();
return spline;
}
}
// Create a spline with enough nodes otherwise.
return CompactSpline::Create(max_nodes);
}
void SplineProcessor::FreeSplineForIndex(Motivator::Index index) {
if (data_[index]) {
using std::swap;
spline_pool_.emplace_back();
swap(data_[index], spline_pool_.back());
}
}
} // namespace redux
| 0 | 0.917486 | 1 | 0.917486 | game-dev | MEDIA | 0.801574 | game-dev | 0.93802 | 1 | 0.93802 |
Bithack/principia | 1,536 | lib/Box2D/Dynamics/b2ContactManager.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_CONTACT_MANAGER_H
#define B2_CONTACT_MANAGER_H
#include <Box2D/Collision/b2BroadPhase.h>
class b2Contact;
class b2ContactFilter;
class b2ContactListener;
class b2BlockAllocator;
// Delegate of b2World.
class b2ContactManager
{
public:
b2ContactManager();
// Broad-phase callback.
void AddPair(void* proxyUserDataA, void* proxyUserDataB);
void FindNewContacts();
void Destroy(b2Contact* c);
void Collide();
b2BroadPhase m_broadPhase;
b2Contact* m_contactList;
int32 m_contactCount;
b2ContactFilter* m_contactFilter;
b2ContactListener* m_contactListener;
b2BlockAllocator* m_allocator;
};
#endif
| 0 | 0.71159 | 1 | 0.71159 | game-dev | MEDIA | 0.133959 | game-dev | 0.502331 | 1 | 0.502331 |
baileyholl/Ars-Nouveau | 3,783 | src/main/java/com/hollingsworth/arsnouveau/common/datagen/OneOffRecipesProvider.java | package com.hollingsworth.arsnouveau.common.datagen;
import com.hollingsworth.arsnouveau.common.crafting.recipes.BookUpgradeRecipe;
import com.hollingsworth.arsnouveau.common.crafting.recipes.PotionFlaskRecipe;
import com.hollingsworth.arsnouveau.setup.registry.ItemsRegistry;
import com.mojang.serialization.JsonOps;
import net.minecraft.core.NonNullList;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.CraftingBookCategory;
import net.minecraft.world.item.crafting.Ingredient;
import net.neoforged.neoforge.common.Tags;
import java.nio.file.Path;
import java.util.List;
public class OneOffRecipesProvider extends SimpleDataProvider {
public OneOffRecipesProvider(DataGenerator generatorIn) {
super(generatorIn);
}
@Override
public void collectJsons(CachedOutput pOutput) {
var flasks = new Item[]{
ItemsRegistry.POTION_FLASK.get(),
ItemsRegistry.POTION_FLASK_EXTEND_TIME.get(),
ItemsRegistry.POTION_FLASK_AMPLIFY.get()
};
for (int i = 0; i < flasks.length; i++) {
var flaskRecipe = new PotionFlaskRecipe("", flasks[i].getDefaultInstance(), flasks[i].getDefaultInstance());
saveStable(pOutput, PotionFlaskRecipe.CODEC.encodeStart(JsonOps.INSTANCE, flaskRecipe).getOrThrow(), getRecipePath(output, "fill_potion_flask_" + i));
}
BookUpgradeRecipe apprentice = new BookUpgradeRecipe("", CraftingBookCategory.MISC, ItemsRegistry.APPRENTICE_SPELLBOOK.get().getDefaultInstance(),
NonNullList.copyOf(List.of(
Ingredient.of(ItemsRegistry.NOVICE_SPELLBOOK.get().getDefaultInstance()),
Ingredient.of(Tags.Items.OBSIDIANS),
Ingredient.of(Tags.Items.GEMS_DIAMOND),
Ingredient.of(Tags.Items.GEMS_DIAMOND),
Ingredient.of(Tags.Items.GEMS_DIAMOND),
Ingredient.of(Items.QUARTZ_BLOCK),
Ingredient.of(Items.QUARTZ_BLOCK),
Ingredient.of(Tags.Items.RODS_BLAZE),
Ingredient.of(Tags.Items.RODS_BLAZE)
)));
BookUpgradeRecipe archmage = new BookUpgradeRecipe("", CraftingBookCategory.MISC, ItemsRegistry.ARCHMAGE_SPELLBOOK.get().getDefaultInstance(),
NonNullList.copyOf(List.of(
Ingredient.of(ItemsRegistry.APPRENTICE_SPELLBOOK.get().getDefaultInstance()),
Ingredient.of(Tags.Items.ENDER_PEARLS),
Ingredient.of(Tags.Items.ENDER_PEARLS),
Ingredient.of(Tags.Items.ENDER_PEARLS),
Ingredient.of(Tags.Items.GEMS_EMERALD),
Ingredient.of(Tags.Items.GEMS_EMERALD),
Ingredient.of(Items.TOTEM_OF_UNDYING),
Ingredient.of(Items.NETHER_STAR),
Ingredient.of(ItemsRegistry.WILDEN_TRIBUTE)
)));
saveStable(pOutput, BookUpgradeRecipe.CODEC.encodeStart(JsonOps.INSTANCE, apprentice).getOrThrow(), getRecipePath(output, "apprentice_book_upgrade"));
saveStable(pOutput, BookUpgradeRecipe.CODEC.encodeStart(JsonOps.INSTANCE, archmage).getOrThrow(), getRecipePath(output, "archmage_book_upgrade"));
}
protected static Path getRecipePath(Path path, String id) {
return path.resolve("data/ars_nouveau/recipe/" + id + ".json");
}
/**
* Gets a name for this provider, to use in logging.
*/
@Override
public String getName() {
return "Grab bag Datagen";
}
}
| 0 | 0.893165 | 1 | 0.893165 | game-dev | MEDIA | 0.994691 | game-dev | 0.908802 | 1 | 0.908802 |
OpenRCT2/OpenRCT2 | 4,777 | src/openrct2/entity/EntityList.h | /*****************************************************************************
* Copyright (c) 2014-2025 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include "../GameState.h"
#include "../rct12/RCT12.h"
#include "../world/Location.hpp"
#include "EntityBase.h"
#include "EntityRegistry.h"
#include <list>
#include <vector>
namespace OpenRCT2
{
template<typename T>
class EntityTileIterator
{
private:
std::vector<EntityId>::const_iterator iter;
std::vector<EntityId>::const_iterator end;
T* Entity = nullptr;
public:
EntityTileIterator(std::vector<EntityId>::const_iterator _iter, std::vector<EntityId>::const_iterator _end)
: iter(_iter)
, end(_end)
{
++(*this);
}
EntityTileIterator& operator++()
{
Entity = nullptr;
// TODO: don't use global game state!
auto& gameState = getGameState();
while (iter != end && Entity == nullptr)
{
Entity = gameState.entities.TryGetEntity<T>(*iter++);
}
return *this;
}
EntityTileIterator operator++(int)
{
EntityTileIterator retval = *this;
++(*this);
return *iter;
}
bool operator==(EntityTileIterator other) const
{
return Entity == other.Entity;
}
bool operator!=(EntityTileIterator other) const
{
return !(*this == other);
}
T* operator*()
{
return Entity;
}
// iterator traits
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = const T*;
using reference = const T&;
using iterator_category = std::forward_iterator_tag;
};
template<typename T = EntityBase>
class EntityTileList
{
private:
const std::vector<EntityId>& vec;
public:
EntityTileList(const CoordsXY& loc)
: vec(getGameState().entities.GetEntityTileList(loc))
{
}
EntityTileIterator<T> begin()
{
return EntityTileIterator<T>(std::begin(vec), std::end(vec));
}
EntityTileIterator<T> end()
{
return EntityTileIterator<T>(std::end(vec), std::end(vec));
}
};
template<typename T>
class EntityListIterator
{
private:
std::list<EntityId>::const_iterator iter;
std::list<EntityId>::const_iterator end;
T* Entity = nullptr;
public:
EntityListIterator(std::list<EntityId>::const_iterator _iter, std::list<EntityId>::const_iterator _end)
: iter(_iter)
, end(_end)
{
++(*this);
}
EntityListIterator& operator++()
{
Entity = nullptr;
// TODO: don't use global game state!
auto& gameState = getGameState();
while (iter != end && Entity == nullptr)
{
Entity = gameState.entities.TryGetEntity<T>(*iter++);
}
return *this;
}
EntityListIterator operator++(int)
{
EntityListIterator retval = *this;
++(*this);
return *iter;
}
bool operator==(EntityListIterator other) const
{
return Entity == other.Entity;
}
bool operator!=(EntityListIterator other) const
{
return !(*this == other);
}
T* operator*()
{
return Entity;
}
// iterator traits
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = const T*;
using reference = const T&;
using iterator_category = std::forward_iterator_tag;
};
template<typename T = EntityBase>
class EntityList
{
private:
using EntityListIterator_t = EntityListIterator<T>;
const std::list<EntityId>& vec;
public:
EntityList()
: vec(getGameState().entities.GetEntityList(T::cEntityType))
{
}
EntityListIterator_t begin() const
{
return EntityListIterator_t(std::cbegin(vec), std::cend(vec));
}
EntityListIterator_t end() const
{
return EntityListIterator_t(std::cend(vec), std::cend(vec));
}
};
} // namespace OpenRCT2
| 0 | 0.848862 | 1 | 0.848862 | game-dev | MEDIA | 0.789546 | game-dev | 0.874204 | 1 | 0.874204 |
Frodo45127/rpfm | 14,330 | rpfm_lib/src/files/cs2_parsed/versions/v12.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2024 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed under the MIT license, which can be found here:
// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
//---------------------------------------------------------------------------//
use crate::error::Result;
use crate::binary::{ReadBytes, WriteBytes};
use super::*;
//---------------------------------------------------------------------------//
// Implementation of Cs2Parsed
//---------------------------------------------------------------------------//
impl Cs2Parsed {
pub fn read_v12<R: ReadBytes>(&mut self, data: &mut R) -> Result<()> {
self.bounding_box = Cube::decode(data, &None)?;
self.ui_flag.name = data.read_sized_string_u16()?;
self.ui_flag.transform = Transform4x4::decode(data, &None)?;
self.int_1 = data.read_i32()?;
// Pieces
for _ in 0..data.read_u32()? {
let mut piece = Piece::default();
// Tech node.
piece.name = data.read_sized_string_u16()?;
piece.node_name = data.read_sized_string_u16()?;
piece.node_transform = Transform4x4::decode(data, &None)?;
piece.int_3 = data.read_i32()?;
for _ in 0..data.read_u32()? {
let mut destruct = Destruct::default();
destruct.name = data.read_sized_string_u16()?;
destruct.index = data.read_u32()?;
destruct.collision_3d.read_v13(data)?;
destruct.windows = data.read_i32()?;
destruct.doors = data.read_i32()?;
// Gates.
for _ in 0..data.read_i32()? {
let mut collision_1 = Collision3d::default();
let mut collision_2 = Collision3d::default();
collision_1.read_v13(data)?;
collision_2.read_v13(data)?;
destruct.gates.push(Gate {
collision_1,
collision_2,
uk_1: data.read_u32()?,
uk_2: data.read_u32()?,
});
}
// Collision outlines?
for _ in 0..data.read_u32()? {
destruct.collision_outlines.push(CollisionOutline {
name: data.read_sized_string_u16()?,
vertices: Outline3d::decode(data, &None)?,
uk_1: data.read_u32()?,
});
}
// Pipes.
for _ in 0..data.read_u32()? {
destruct.pipes.push(Pipe {
name: data.read_sized_string_u16()?,
line: Outline3d::decode(data, &None)?,
line_type: PipeType::try_from(data.read_i32()?)?,
});
}
// This is the weird orange line in terry?
for _ in 0..data.read_u32()? {
let mut thingies = vec![];
for _ in 0..data.read_u32()? {
thingies.push(OrangeThingy {
vertex: Point2d::decode(data, &None)?,
vertex_type: data.read_u32()?,
});
}
destruct.orange_thingies.push(thingies);
}
// Platforms.
for _ in 0..data.read_u32()? {
destruct.platforms.push(Platform {
normal: Point3d::decode(data, &None)?,
vertices: Outline3d::decode(data, &None)?,
flag_1: data.read_bool()?,
flag_2: data.read_bool()?,
flag_3: data.read_bool()?,
});
}
destruct.uk_2 = data.read_i32()?;
destruct.bounding_box = Cube::decode(data, &None)?;
destruct.cannon_emitters = data.read_i32()?;
for _ in 0..data.read_u32()? {
destruct.arrow_emitters.push(ProjectileEmitter {
name: data.read_sized_string_u16()?,
transform: Transform4x4::decode(data, &None)?,
});
}
destruct.docking_points = data.read_i32()?;
for _ in 0..data.read_u32()? {
destruct.soft_collisions.push(SoftCollisions {
name: data.read_sized_string_u16()?,
transform: Transform4x4::decode(data, &None)?,
uk_1: data.read_i16()?,
point_1: Point2d::decode(data, &None)?,
});
}
destruct.uk_7 = data.read_i32()?;
// Destructible pillars.
for _ in 0..data.read_u32()? {
destruct.file_refs.push(FileRef {
key: data.read_sized_string_u16()?,
name: data.read_sized_string_u16()?,
transform: Transform4x4::decode(data, &None)?,
uk_1: data.read_i16()?
});
}
// EF lines.
for _ in 0..data.read_u32()? {
destruct.ef_lines.push(EFLine {
name: data.read_sized_string_u16()?,
action: EFLineType::try_from(data.read_i32()?)?,
start: Point3d::decode(data, &None)?,
end: Point3d::decode(data, &None)?,
direction: Point3d::decode(data, &None)?,
parent_index: data.read_u32()?
});
}
// Docking lines.
for _ in 0..data.read_u32()? {
destruct.docking_lines.push(DockingLine {
key: data.read_sized_string_u16()?,
start: Point2d::decode(data, &None)?,
end: Point2d::decode(data, &None)?,
direction: Point2d::decode(data, &None)?,
});
}
for _ in 0..data.read_u32()? {
destruct.action_vfx.push(Vfx {
key: data.read_sized_string_u16()?,
matrix_1: Transform4x4::decode(data, &None)?,
});
}
for _ in 0..data.read_u32()? {
destruct.action_vfx_attachments.push(Vfx {
key: data.read_sized_string_u16()?,
matrix_1: Transform4x4::decode(data, &None)?,
});
}
for _ in 0..data.read_u32()? {
let mut vec = vec![];
for _ in 0..data.read_u32()? {
vec.push(data.read_i16()?);
}
destruct.bin_data.push(vec);
}
for _ in 0..data.read_u32()? {
let mut vec = vec![];
for _ in 0..data.read_u32()? {
vec.push(data.read_i16()?);
}
destruct.bin_data_2.push(vec.clone());
}
piece.destructs.push(destruct);
}
piece.f_6 = data.read_f32()?;
self.pieces.push(piece);
}
Ok(())
}
pub fn write_v12<W: WriteBytes>(&mut self, buffer: &mut W) -> Result<()> {
self.bounding_box.encode(buffer, &None)?;
buffer.write_sized_string_u16(&self.ui_flag.name)?;
self.ui_flag.transform.encode(buffer, &None)?;
buffer.write_i32(self.int_1)?;
buffer.write_u32(self.pieces.len() as u32)?;
for piece in &mut self.pieces {
buffer.write_sized_string_u16(&piece.name)?;
buffer.write_sized_string_u16(&piece.node_name)?;
piece.node_transform.encode(buffer, &None)?;
buffer.write_i32(piece.int_3)?;
buffer.write_u32(piece.destructs.len() as u32)?;
for destruct in &mut piece.destructs {
buffer.write_sized_string_u16(&destruct.name)?;
buffer.write_u32(destruct.index)?;
destruct.collision_3d.write_v13(buffer)?;
buffer.write_i32(destruct.windows)?;
buffer.write_i32(destruct.doors)?;
buffer.write_u32(destruct.gates.len() as u32)?;
for gate in &mut destruct.gates {
gate.collision_1.write_v13(buffer)?;
gate.collision_2.write_v13(buffer)?;
buffer.write_u32(gate.uk_1)?;
buffer.write_u32(gate.uk_2)?;
}
buffer.write_u32(destruct.collision_outlines.len() as u32)?;
for outline in &mut destruct.collision_outlines {
buffer.write_sized_string_u16(&outline.name)?;
outline.vertices.encode(buffer, &None)?;
buffer.write_u32(outline.uk_1)?;
}
buffer.write_u32(destruct.pipes.len() as u32)?;
for pipe in &mut destruct.pipes {
buffer.write_sized_string_u16(&pipe.name)?;
pipe.line.encode(buffer, &None)?;
buffer.write_i32(pipe.line_type.into())?;
}
buffer.write_u32(destruct.orange_thingies.len() as u32)?;
for orange_thingies in &mut destruct.orange_thingies {
buffer.write_u32(orange_thingies.len() as u32)?;
for orange_thingy in orange_thingies {
orange_thingy.vertex.encode(buffer, &None)?;
buffer.write_u32(orange_thingy.vertex_type)?;
}
}
buffer.write_u32(destruct.platforms.len() as u32)?;
for platform in &mut destruct.platforms {
platform.normal.encode(buffer, &None)?;
platform.vertices.encode(buffer, &None)?;
buffer.write_bool(platform.flag_1)?;
buffer.write_bool(platform.flag_2)?;
buffer.write_bool(platform.flag_3)?;
}
buffer.write_i32(destruct.uk_2)?;
destruct.bounding_box.encode(buffer, &None)?;
buffer.write_i32(destruct.cannon_emitters)?;
buffer.write_u32(destruct.arrow_emitters.len() as u32)?;
for emitter in &mut destruct.arrow_emitters {
buffer.write_sized_string_u16(&emitter.name)?;
emitter.transform.encode(buffer, &None)?;
}
buffer.write_i32(destruct.docking_points)?;
buffer.write_u32(destruct.soft_collisions.len() as u32)?;
for soft_collision in &mut destruct.soft_collisions {
buffer.write_sized_string_u16(&soft_collision.name)?;
soft_collision.transform.encode(buffer, &None)?;
buffer.write_i16(soft_collision.uk_1)?;
soft_collision.point_1.encode(buffer, &None)?;
}
buffer.write_i32(destruct.uk_7)?;
buffer.write_u32(destruct.file_refs.len() as u32)?;
for file_ref in &mut destruct.file_refs {
buffer.write_sized_string_u16(&file_ref.key)?;
buffer.write_sized_string_u16(&file_ref.name)?;
file_ref.transform.encode(buffer, &None)?;
buffer.write_i16(file_ref.uk_1)?;
}
buffer.write_u32(destruct.ef_lines.len() as u32)?;
for ef_line in &mut destruct.ef_lines {
buffer.write_sized_string_u16(&ef_line.name)?;
buffer.write_i32(ef_line.action.into())?;
ef_line.start.encode(buffer, &None)?;
ef_line.end.encode(buffer, &None)?;
ef_line.direction.encode(buffer, &None)?;
buffer.write_u32(ef_line.parent_index)?;
}
buffer.write_u32(destruct.docking_lines.len() as u32)?;
for docking_line in &mut destruct.docking_lines {
buffer.write_sized_string_u16(&docking_line.key)?;
docking_line.start.encode(buffer, &None)?;
docking_line.end.encode(buffer, &None)?;
docking_line.direction.encode(buffer, &None)?;
}
buffer.write_u32(destruct.action_vfx.len() as u32)?;
for vfx in &mut destruct.action_vfx {
buffer.write_sized_string_u16(&vfx.key)?;
vfx.matrix_1.encode(buffer, &None)?;
}
buffer.write_u32(destruct.action_vfx_attachments.len() as u32)?;
for vfx in &mut destruct.action_vfx_attachments {
buffer.write_sized_string_u16(&vfx.key)?;
vfx.matrix_1.encode(buffer, &None)?;
}
buffer.write_u32(destruct.bin_data.len() as u32)?;
for bin_data in &destruct.bin_data {
buffer.write_u32(bin_data.len() as u32)?;
for bin_data in bin_data {
buffer.write_i16(*bin_data)?;
}
}
buffer.write_u32(destruct.bin_data_2.len() as u32)?;
for bin_data in &destruct.bin_data_2 {
buffer.write_u32(bin_data.len() as u32)?;
for bin_data in bin_data {
buffer.write_i16(*bin_data)?;
}
}
}
buffer.write_f32(piece.f_6)?;
}
Ok(())
}
}
| 0 | 0.747261 | 1 | 0.747261 | game-dev | MEDIA | 0.279591 | game-dev | 0.702167 | 1 | 0.702167 |
b1inkie/dst-api | 4,871 | scripts_619045/widgets/loadingwidget.lua | local Widget = require "widgets/widget"
local Text = require "widgets/text"
local TEMPLATES = require "widgets/templates"
local images =
IsSpecialEventActive(SPECIAL_EVENTS.HALLOWED_NIGHTS) and {
-- {atlas="images/bg_spiral_fill_halloween1.xml", tex="bg_image1.tex"},
-- {atlas="images/bg_spiral_fill_halloween2.xml", tex="bg_image2.tex"},
-- {atlas="images/bg_spiral_fill_halloween3.xml", tex="bg_image3.tex"},
{atlas="images/bg_spiral_fill_halloween4.xml", tex="bg_image4.tex"},
{atlas="images/bg_spiral_fill_halloween5.xml", tex="bg_image5.tex"},
}
or IsSpecialEventActive(SPECIAL_EVENTS.WINTERS_FEAST) and {
{atlas="images/bg_spiral_fill_christmas1.xml", tex="bg_image1.tex"},
{atlas="images/bg_spiral_fill_christmas2.xml", tex="bg_image2.tex"},
}
or IsSpecialEventActive(SPECIAL_EVENTS.YOTG) and {
{atlas="images/bg_spiral_fill_yotg1.xml", tex="bg_image1.tex"},
{atlas="images/bg_spiral_fill_yotg2.xml", tex="bg_image2.tex"},
}
or {
{atlas="images/bg_spiral_fill1.xml", tex="bg_image1.tex"},
{atlas="images/bg_spiral_fill2.xml", tex="bg_image2.tex"},
{atlas="images/bg_spiral_fill3.xml", tex="bg_image3.tex"},
{atlas="images/bg_spiral_fill4.xml", tex="bg_image4.tex"},
{atlas="images/bg_spiral_fill5.xml", tex="bg_image5.tex"},
{atlas="images/bg_spiral_fill6.xml", tex="bg_image6.tex"},
{atlas="images/bg_spiral_fill7.xml", tex="bg_image7.tex"},
{atlas="images/bg_spiral_fill8.xml", tex="bg_image8.tex"},
}
local LoadingWidget = Class(Widget, function(self, imageRand)
Widget._ctor(self, "LoadingWidget")
self.forceShowNextFrame = false
self.is_enabled = false
self.image_random = imageRand or math.random(#images)
self:Hide()
self.bg = self:AddChild(TEMPLATES.BackgroundSpiral())
-- classic
self.root_classic = self:AddChild(Widget("classic_root"))
self.root_classic:Hide()
local vignette = self.root_classic:AddChild(TEMPLATES.BackgroundVignette())
local atlas = images[self.image_random].atlas
local tex = images[self.image_random].tex
local image = self.root_classic:AddChild(Image(atlas, tex))
image:SetScaleMode(SCALEMODE_FILLSCREEN)
image:SetVAnchor(ANCHOR_MIDDLE)
image:SetHAnchor(ANCHOR_MIDDLE)
self.active_image = image
self.vig = vignette
-- common
local local_loading_widget = self:AddChild(Text(UIFONT, 40))
local_loading_widget:SetPosition(115, 60)
local_loading_widget:SetRegionSize(130, 44)
local_loading_widget:SetHAlign(ANCHOR_LEFT)
local_loading_widget:SetVAlign(ANCHOR_BOTTOM)
local_loading_widget:SetString(STRINGS.UI.NOTIFICATION.LOADING)
self.loading_widget = local_loading_widget
self.cached_string = ""
self.elipse_state = 0
self.cached_fade_level = 0.0
self.step_time = GetStaticTime()
end)
function LoadingWidget:ShowNextFrame()
self.forceShowNextFrame = true
end
function LoadingWidget:SetEnabled(enabled)
self.is_enabled = enabled
if enabled then
self.root_classic:Show()
self:Show()
self:StartUpdating()
else
self:Hide()
self:StopUpdating()
end
end
function LoadingWidget:KeepAlive(auto_increment)
if self.is_enabled then
if TheFrontEnd and auto_increment == false then
self.cached_fade_level = TheFrontEnd:GetFadeLevel()
else
self.cached_fade_level = 1.0
end
local fade_sq = self.cached_fade_level * self.cached_fade_level
self.loading_widget:SetColour(243/255, 244/255, 243/255, fade_sq)
self.bg:SetTint(FRONTEND_PORTAL_COLOUR[1], FRONTEND_PORTAL_COLOUR[2], FRONTEND_PORTAL_COLOUR[3], fade_sq)
self.active_image:SetTint(1, 1, 1, fade_sq)
self.vig:SetTint(1, 1, 1, fade_sq)
local time = GetStaticTime()
local time_delta = time - self.step_time
local NEXT_STATE = 1.0
if time_delta > NEXT_STATE or auto_increment then
if self.elipse_state == 0 then
self.loading_widget:SetString(STRINGS.UI.NOTIFICATION.LOADING..".")
self.elipse_state = self.elipse_state + 1
elseif self.elipse_state == 1 then
self.loading_widget:SetString(STRINGS.UI.NOTIFICATION.LOADING.."..")
self.elipse_state = self.elipse_state + 1
else
self.loading_widget:SetString(STRINGS.UI.NOTIFICATION.LOADING.."...")
self.elipse_state = 0
end
self.step_time = time
end
if 0.01 > self.cached_fade_level then
self.is_enabled = false
self:Hide()
self:StopUpdating()
end
end
end
function LoadingWidget:OnUpdate()
self:KeepAlive(self.forceShowNextFrame)
self.forceShowNextFrame = false
end
return LoadingWidget
| 0 | 0.81969 | 1 | 0.81969 | game-dev | MEDIA | 0.767587 | game-dev | 0.898369 | 1 | 0.898369 |
jmrapp1/TerraLegion | 1,873 | core/src/com/jmrapp/terralegion/game/world/block/impl/PlantBlock.java | package com.jmrapp.terralegion.game.world.block.impl;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.jmrapp.terralegion.engine.views.drawables.Drawable;
import com.jmrapp.terralegion.engine.views.drawables.ResourceManager;
import com.jmrapp.terralegion.game.world.block.Block;
import com.jmrapp.terralegion.game.world.block.BlockType;
import com.jmrapp.terralegion.game.world.chunk.Chunk;
import com.jmrapp.terralegion.game.world.chunk.ChunkManager;
/**
* Plant blocks are automatically destroyed if the block under them no longer exists
*
* Created by jordanb84 on 8/5/16.
*/
public class PlantBlock extends Block{
private ChunkManager chunkManager;
public PlantBlock(BlockType type, Drawable drawable, float lightBlockingAmount, boolean collides, boolean transparent, float initHealth, float resistance){
super(type, drawable, lightBlockingAmount, collides, transparent, initHealth, resistance);
}
@Override
public void render(OrthographicCamera camera, SpriteBatch sb, float x, float y, float lightValue){
super.render(camera, sb, x, y, lightValue);
Vector2 tilePosition = new Vector2(chunkManager.pixelToTilePosition(x), chunkManager.pixelToTilePosition(y));
Vector2 belowTilePosition = new Vector2(tilePosition.x, tilePosition.y - 1);
if(chunkManager.getBlockFromTilePos((int) belowTilePosition.x, (int) belowTilePosition.y) == BlockType.AIR){
chunkManager.setBlock(BlockType.AIR, (int) tilePosition.x, (int) tilePosition.y, true);
}
}
@Override
public void onPlace(ChunkManager chunkManager, Chunk chunk, int chunkTileX, int chunkTileY) {
super.onPlace(chunkManager, chunk, chunkTileX, chunkTileY);
this.chunkManager = chunkManager;
}
} | 0 | 0.618278 | 1 | 0.618278 | game-dev | MEDIA | 0.939925 | game-dev | 0.917791 | 1 | 0.917791 |
cocos-creator/cocos-tutorial-duang-sheep | 7,840 | obsolete-docs/en/step-5.md | title: Tutorial - Game Loop
categories: tutorial
permalinks: tutorial/duang-sheep/step5
---
## Goal
- Adding collision detect between sheep and pipes
- When sheep hit a pipe, pop up a game over menu
- Click the restart button in game over menu to restart game
## Steps
### Add Collision Detection for Pipes
Open`PipeGroupManager` script for editing. Add a function called `collisionDetection`. Also add a property `pipeGroupList` to manage all existing `PipeGroup` entities.
Add the following code to `PipeGroupManager` script:
**PipeGroupManager.js: `.....` are the parts stay unchanged.**
```js
var PipeGroupManager = Fire.Class({
extends: Fire.Component,
constructor: function () {
.....
},
// Properties
properties: {
.....
// a list to manage all existing pipes
pipeGroupList: {
get: function () {
return this.entity.getChildren();
},
hideInInspector: true
}
},
.....
// create pipe group entity
createPipeGroupEntity: function () {
var pipeGroup = Fire.instantiate(this.srcPipeGroup);
pipeGroup.parent = this.entity;
pipeGroup.transform.position = this.initPipeGroupPos;
pipeGroup.active = true;
},
// collision detection iterating each pipe group in the list
collisionDetection: function (sheepRect) {
for (var i = 0; i < this.pipeGroupList.length; ++i) {
// top pipe
var pipeGroupEntity = this.pipeGroupList[i];
var pipe = pipeGroupEntity.find('topPipe');
var pipeRender = pipe.getComponent(Fire.SpriteRenderer)
var pipeRect = pipeRender.getWorldBounds();
if (Fire.Intersection.rectRect(sheepRect, pipeRect)) {
return true;
}
// bottom pipe
pipe = pipeGroupEntity.find('bottomPipe');
pipeRender = pipe.getComponent(Fire.SpriteRenderer);
pipeRect = pipeRender.getWorldBounds();
if (Fire.Intersection.rectRect(sheepRect, pipeRect)) {
return true;
}
}
return false;
},
.....
});
```
### Add Collision Detection for Sheep
Now let's update`Sheep` script. We will add a `renderer` variable to fetch sheep's collider information.
We will update `Sheep` script like this:
**Sheep.js: `.....` are parts stay unchanged**
```js
// sheep states
var State = Fire.defineEnum({...});
var Sheep = Fire.Class({
extends: Fire.Component,
constructor: function () {
.....
// this variable will store the reference for sheep's SpriteRenderer
this.renderer = null;
.....
},
// properties
properties: {....},
// initialization
onLoad: function () {
.....
// sheep's Sprite Renderer will be used as collider
this.renderer = this.getComponent(Fire.SpriteRenderer);
.....
},
.....
});
Sheep.State = State;
```
### Create Game Over Menu
We will mock up a very simple menu using assets in `sprite/ui` folder.
First create a `GameOver` entity in `Hierarchy` view. Then drag the following image assets from `sprite/ui` folder in `Assets` onto `GameOver`, to create its children automatically:
- `gameoverbg`
- `text_game_over`
- `button_play`
We will use their names as they are. The complete menu should look like this:
**GameOver Setup**

Select `GameOver` entity, find the show/hide checkbox at top left of `Inspector` view:
Uncheck it to hide `GameOver` entity in `Game` view.
### GameOver Restart Button
Create a `GameOverMenu` script. It will add click event for restart button(`button_play` entity). Once clicked game will be restarted.
**GameOverMenu.js**
```js
var GameOverMenu = Fire.Class({
extends: Fire.Component,
constructor: function () {
// restart game event
this.resetGameEvent;
},
// properties
properties: {
// reference to restart button
btn_play: {
default: null,
type: Fire.Entity
}
},
// restart game by reloading scene
resetGameEvent: function () {
Fire.Engine.loadScene('Game');
},
// when game starts, do button event registering
start: function () {
// register click event for restart button
this.btn_play.on('mousedown', this.resetGameEvent);
},
// menu destroyed
onDestroy: function () {
// unregister click event
this.btn_play.off('mousedown', this.resetGameEvent);
}
});
```
Drag `GameOverMenu` script onto `GameOver` entity in `Hierarchy` view. Then drag `GameOver/button_play` entity onto `GameOverMenu` component's `Btn Play` property.
### Finish the Game Loop
Now we are all set with collisions and menus. Let's create a script named `GameManager` and connect all the assets and script to finish the game loop.
**GameManager.js**
```js
var Sheep = require('Sheep');
var ScrollPicture = require('ScrollPicture');
var PipeGroupManager = require('PipeGroupManager');
var GameState = Fire.defineEnum({
Run : -1,
Over: -1
});
var GameManager = Fire.Class({
extends: Fire.Component,
constructor: function () {
// current game state
this.gameState = GameState.Run
},
// property
properties: {
// Sheep component reference
sheep: {
default: null,
type: Sheep
},
// background reference
background: {
default: null,
type: ScrollPicture
},
// ground reference
ground: {
default: null,
type: ScrollPicture
},
// PipeGroupManager component reference
pipeGroupMgr: {
default: null,
type: PipeGroupManager
},
// GameOverMenu component reference
gameOverMenu: {
default: null,
type: Fire.Entity
}
},
// when game starts, set state to Run
start: function () {
this.gameState = GameState.Run;
},
// update game state
update: function () {
switch (this.gameState) {
case GameState.Run:
// Get bounding box from sheep's renderer, for collision detection
var sheepRect = this.sheep.renderer.getWorldBounds();
var gameOver = this.pipeGroupMgr.collisionDetection(sheepRect);
// If collisionDetection returns true, we know sheep hits pipe
if (gameOver) {
// set new state for game and sheep, use enabled property to switch off scrolling of backgrounds
this.gameState = GameState.Over;
this.sheep.state = Sheep.State.Dead;
this.ground.enabled = false;
this.background.enabled = false;
for (var i = 0; i < this.pipeGroupMgr.pipeGroupList.length; ++i) {
var pipeGroup = this.pipeGroupMgr.pipeGroupList[i].getComponent('PipeGroup');
pipeGroup.enabled = false;
}
this.pipeGroupMgr.enabled = false;
// turn on the active property of GameOverMenu to show it
this.gameOverMenu.active = true;
}
break;
default :
break;
}
}
});
```
**Final Setup**

----
**NOTE:** [ Step - 5 Project Snapshot for Complete Game Loop](https://github.com/fireball-x/tutorial/commits/step-5)
| 0 | 0.841781 | 1 | 0.841781 | game-dev | MEDIA | 0.852 | game-dev | 0.770478 | 1 | 0.770478 |
xiaoye97/VTS_XYPlugin | 2,708 | VTS_XYPluginUI/Assets/Plugins/CW/LeanTransition/Required/Methods/Transform/LeanTransformPosition_xy.cs | using TARGET = UnityEngine.Transform;
namespace Lean.Transition.Method
{
/// <summary>This component allows you to transition the Transform's position.xy value.</summary>
[UnityEngine.HelpURL(LeanTransition.HelpUrlPrefix + "LeanTransformPosition_xy")]
[UnityEngine.AddComponentMenu(LeanTransition.MethodsMenuPrefix + "Transform/Transform.position.xy" + LeanTransition.MethodsMenuSuffix + "(LeanTransformPosition_xy)")]
public class LeanTransformPosition_xy : LeanMethodWithStateAndTarget
{
public override System.Type GetTargetType()
{
return typeof(TARGET);
}
public override void Register()
{
PreviousState = Register(GetAliasedTarget(Data.Target), Data.Value, Data.Duration, Data.Ease);
}
public static LeanState Register(TARGET target, UnityEngine.Vector2 value, float duration, LeanEase ease = LeanEase.Smooth)
{
var state = LeanTransition.SpawnWithTarget(State.Pool, target);
state.Value = value;
state.Ease = ease;
return LeanTransition.Register(state, duration);
}
[System.Serializable]
public class State : LeanStateWithTarget<TARGET>
{
[UnityEngine.Tooltip("The position value will transition to this.")]
public UnityEngine.Vector2 Value;
[UnityEngine.Tooltip("This allows you to control how the transition will look.")]
public LeanEase Ease = LeanEase.Smooth;
[System.NonSerialized] private UnityEngine.Vector2 oldValue;
public override int CanFill
{
get
{
return Target != null && (Target.position.x != Value.x || Target.position.y != Value.y) ? 1 : 0;
}
}
public override void FillWithTarget()
{
var vector = Target.position;
Value.x = vector.x;
Value.y = vector.y;
}
public override void BeginWithTarget()
{
var vector = Target.position;
oldValue.x = vector.x;
oldValue.y = vector.y;
}
public override void UpdateWithTarget(float progress)
{
var vector = Target.position;
var smooth = Smooth(Ease, progress);
vector.x = UnityEngine.Mathf.LerpUnclamped(oldValue.x, Value.x, smooth);
vector.y = UnityEngine.Mathf.LerpUnclamped(oldValue.y, Value.y, smooth);
Target.position = vector;
}
public static System.Collections.Generic.Stack<State> Pool = new System.Collections.Generic.Stack<State>(); public override void Despawn() { Pool.Push(this); }
}
public State Data;
}
}
namespace Lean.Transition
{
public static partial class LeanExtensions
{
public static TARGET positionTransition_xy(this TARGET target, UnityEngine.Vector2 value, float duration, LeanEase ease = LeanEase.Smooth)
{
Method.LeanTransformPosition_xy.Register(target, value, duration, ease); return target;
}
}
} | 0 | 0.901422 | 1 | 0.901422 | game-dev | MEDIA | 0.799067 | game-dev | 0.969261 | 1 | 0.969261 |
dimsa/ShadowEngine | 5,820 | SOEngine/Parts/Collider/SoBox2D/uSoBox2DColliderObj.pas | unit uSoBox2DColliderObj;
interface
uses
UPhysics2D, UPhysics2DTypes, uSoTypes, uGeometryClasses,
uSoColliderObject, uSoObject, uSoBox2DUtils, uColliderDefinition, uRawShapeBox2DConverter,
uSoPosition;
type
TSoBox2DColliderObj = class(TSoColliderObj)
{ private type
TSoPositionFriend = class(TSoPosition);}
private
FBodyDef: Tb2BodyDef;
FBody: TB2Body;
FWorld: Tb2World;
FLastScale: TPointF;
FOriginalShapes: TList<Tb2Shape>;
function B2TransformFromSubject: Tb2Transform;
procedure OnPositionChanged(ASender: TObject; APosition: TPosition);
function BodyTypeToBox2DBodyType(const ABodyType: TBodyType): Tb2BodyType;
procedure Scale(const AScale: TPointF);
protected
property Body: Tb2Body read FBody;
public
procedure RefreshSubjectPosition; override;
function IsContainsPoint(const AX, AY: Single): Boolean; overload; override;
function IsContainsPoint(const APoint: TPointF): Boolean; overload; override;
procedure ApplyForce(const AX, AY: Single; const ACenterX: Single = 0; const ACenterY: Single = 0); override;
constructor Create(const ASubject: TSoObject; const AWorld: Tb2World; const AColliderDef: TColliderDefinition);
destructor Destroy; override;
end;
implementation
{ TSoBox2DColliderObj }
procedure TSoBox2DColliderObj.ApplyForce(const AX, AY, ACenterX,
ACenterY: Single);
var
vVecForce, vVecCenterOfForce: TVector2;
begin
vVecForce.x := AX;
vVecForce.y := AY;
vVecCenterOfForce.x := ACenterX;
vVecCenterOfForce.y := ACenterY;
FBody.ApplyForce(vVecForce, vVecCenterOfForce);
end;
function TSoBox2DColliderObj.B2TransformFromSubject: Tb2Transform;
begin
with Result do begin
p.x := FSubject.Position.X;
p.y := FSubject.Position.Y;
end;
end;
function TSoBox2DColliderObj.BodyTypeToBox2DBodyType(const ABodyType: TBodyType): Tb2BodyType;
begin
case ABodyType of
btStatic: Exit(Tb2BodyType.b2_staticBody);
btKinematic: Exit(Tb2BodyType.b2_kinematicBody);
btDynamic: Exit(Tb2BodyType.b2_dynamicBody);
end;
raise Exception.Create('Not supported body type');
end;
constructor TSoBox2DColliderObj.Create(const ASubject: TSoObject; const AWorld: Tb2World; const AColliderDef: TColliderDefinition);
var
i: Integer;
vFixture: Tb2FixtureDef;
vShape: Tb2Shape;
vVec: TVector2;
begin
inherited Create(ASubject);
FOriginalShapes := TList<Tb2Shape>.Create;
FLastScale := ASubject.Position.ScalePoint;
ASubject.Position.AbsolutePositionChanged.Add(OnPositionChanged);
FWorld := AWorld;
FBodyDef := Tb2BodyDef.Create;
FBodyDef.bodyType := BodyTypeToBox2DBodyType(AColliderDef.BodyType);
FBody := FWorld.CreateBody(FBodyDef, False);
for i := 0 to AColliderDef.Shape.Count - 1 do
begin
vFixture := Tb2FixtureDef.Create;
vShape := TRawShapeBox2DShapeConverter.ConvertTo(AColliderDef.Shape[i]);
vFixture.shape := vShape;
vFixture.density := AColliderDef.Density;
vFixture.friction := AColliderDef.Friction;
vFixture.restitution := AColliderDef.Restitution;
vFixture.isSensor := AColliderDef.IsSensor;
FBody.CreateFixture(vFixture);
FOriginalShapes.Add(TRawShapeBox2DShapeConverter.ConvertTo(AColliderDef.Shape[i]))
end;
FOriginalShapes.Reverse;
end;
destructor TSoBox2DColliderObj.Destroy;
var
i: Integer;
begin
FBody.Free;
for i := 0 to FOriginalShapes.Count - 1 do
FOriginalShapes[i].Free;
FOriginalShapes.Free;
FSubject.Position.AbsolutePositionChanged.Remove(OnPositionChanged);
inherited;
end;
function TSoBox2DColliderObj.IsContainsPoint(const AX, AY: Single): Boolean;
begin
Result := IsContainsPoint(TPointF.Create(AX, AY));
end;
function TSoBox2DColliderObj.IsContainsPoint(const APoint: TPointF): Boolean;
var
vFix: Tb2Fixture;
begin
vFix := FBody.GetFixtureList;
while vFix <> nil do begin
if vFix.GetShape.TestPoint(B2TransformFromSubject, Vector2FromPoint(APoint)) then
Exit(True);
vFix := vFix.GetNext;
end;
Result := False;
end;
procedure TSoBox2DColliderObj.OnPositionChanged(ASender: TObject; APosition: TPosition);
var
vVector: TVector2;
begin
vVector.x := APosition.X;
vVector.y := APosition.Y;
FBody.SetTransform(vVector, APosition.Rotate);
Scale(APosition.Scale);
end;
procedure TSoBox2DColliderObj.RefreshSubjectPosition;
begin
inherited;
FSubject.Position.SetPositionSilent(FBody.GetPosition.x, FBody.GetPosition.y, FBody.GetAngle);
end;
procedure TSoBox2DColliderObj.Scale(const AScale: TPointF);
var
vFix: Tb2Fixture;
i, j: Integer;
begin
if AScale = FLastScale then
Exit;
FLastScale := AScale;
vFix := FBody.GetFixtureList;
i := 0;
while vFix <> nil do begin
case vFix.GetShape.GetType of
e_circleShape:
begin
Tb2CircleShape(vFix.GetShape).m_radius := FOriginalShapes[i].m_radius * AScale.X;
Tb2CircleShape(vFix.GetShape).m_p.x := Tb2CircleShape(FOriginalShapes[i]).m_p.x * AScale.X;
Tb2CircleShape(vFix.GetShape).m_p.y := Tb2CircleShape(FOriginalShapes[i]).m_p.y * AScale.Y;
end;
e_polygonShape: begin
Tb2PolygonShape(vFix.GetShape).m_centroid :=
Vector2FromPoint(
Tb2PolygonShape(FOriginalShapes[i]).m_centroid.x * AScale.X,
Tb2PolygonShape(FOriginalShapes[i]).m_centroid.y * AScale.Y
);
for j := 0 to Tb2PolygonShape(vFix.GetShape).m_count - 1 do
begin
Tb2PolygonShape(vFix.GetShape).m_vertices[j].x := Tb2PolygonShape(FOriginalShapes[i]).m_vertices[j].x * AScale.X;
Tb2PolygonShape(vFix.GetShape).m_vertices[j].y := Tb2PolygonShape(FOriginalShapes[i]).m_vertices[j].y * AScale.Y;
end;
end;
e_edgeShape, e_chainShape: raise Exception.Create('Can not scale this type');
end;
vFix := vFix.GetNext;
i := i + 1;
end;
end;
end.
| 0 | 0.907398 | 1 | 0.907398 | game-dev | MEDIA | 0.809802 | game-dev | 0.96824 | 1 | 0.96824 |
metadriverse/metaurban | 6,502 | metaurban/orca_algo/src/agent.cpp | #include "agent.h"
Agent::Agent() {
id = -1;
start = Point();
goal = Point();
planner = nullptr;
options = nullptr;
map = nullptr;
Neighbours = std::vector<std::pair<float, Agent *>>();
NeighboursObst = std::vector<std::pair<float, ObstacleSegment>>();
ORCALines = std::vector<Line>();
position = Point();
prefV = Point();
newV = Point();
currV = Point();
param = AgentParam();
invTimeBoundaryObst = 0;
invTimeBoundary = 0;
collisions = 0;
collisionsObst = 0;
maxSqObstDist = 0;
speedSaveBuffer = std::list<float>(SPEED_BUFF_SIZE, 1.0f);
meanSavedSpeed = 1.0f;
}
Agent::Agent(const int &id, const Point &start, const Point &goal, const Map &map, const environment_options &options,
AgentParam param) {
this->id = id;
this->start = start;
this->goal = goal;
this->map = ↦
this->options = &options;
this->param = param;
Neighbours = std::vector<std::pair<float, Agent *>>();
Neighbours.reserve((unsigned int) param.agentsMaxNum);
NeighboursObst = std::vector<std::pair<float, ObstacleSegment>>();
ORCALines = std::vector<Line>();
ORCALines.reserve((unsigned int) param.agentsMaxNum);
position = start;
prefV = Point();
newV = Point();
currV = Point();
invTimeBoundaryObst = 1 / param.timeBoundaryObst;
invTimeBoundary = 1 / param.timeBoundary;
collisions = 0;
collisionsObst = 0;
float maxObstDist = param.maxSpeed;
maxSqObstDist = maxObstDist * maxObstDist;
//maxSqObstDist = std::pow((param.sightRadius + param.radius), 2.0f);
// maxSqObstDist = std::pow((param.maxSpeed * param.timeBoundaryObst + param.radius), 2.0f);
speedSaveBuffer = std::list<float>(SPEED_BUFF_SIZE, param.maxSpeed);
meanSavedSpeed = 1.0f;
}
Agent::Agent(const Agent &obj) {
this->id = obj.id;
this->start = obj.start;
this->goal = obj.goal;
this->map = obj.map;
this->options = obj.options;
this->param = obj.param;
if (obj.planner != nullptr) {
this->planner = obj.planner->Clone();
}
Neighbours = obj.Neighbours;
NeighboursObst = obj.NeighboursObst;
ORCALines = obj.ORCALines;
position = obj.position;
prefV = obj.prefV;
newV = obj.newV;
currV = obj.currV;
invTimeBoundaryObst = obj.invTimeBoundaryObst;
invTimeBoundary = obj.invTimeBoundary;
collisions = obj.collisions;
collisionsObst = obj.collisionsObst;
maxSqObstDist = obj.maxSqObstDist;
speedSaveBuffer = obj.speedSaveBuffer;
meanSavedSpeed = obj.meanSavedSpeed;
}
Agent::~Agent() {
if (planner != nullptr) {
delete planner;
planner = nullptr;
}
options = nullptr;
map = nullptr;
Neighbours.clear();
}
bool Agent::isFinished() {
return ((this->position - this->goal).EuclideanNorm() < options->delta);
}
bool Agent::operator==(const Agent &another) const {
return this->id == another.id;
}
bool Agent::operator!=(const Agent &another) const {
return this->id != another.id;
}
void Agent::AddNeighbour(Agent &neighbour, float distSq) {
float sightSq = param.sightRadius * param.sightRadius;
if (distSq >= sightSq) {
return;
}
int i = 0;
auto tmpit = Neighbours.begin();
while (tmpit != Neighbours.end() && i < param.agentsMaxNum && Neighbours[i].first < distSq) {
i++;
tmpit++;
}
if (i < param.agentsMaxNum) {
Neighbours.insert(tmpit, std::pair<float, Agent *>(distSq, &neighbour));
}
}
void Agent::SetPosition(const Point &pos) {
position = pos;
}
Point Agent::GetPosition() const {
return position;
}
void Agent::UpdateNeighbourObst() {
NeighboursObst.clear();
std::vector<std::vector<ObstacleSegment>> tmpObstacles = map->GetObstacles();
float distSq = 0;
for (int i = 0; i < tmpObstacles.size(); i++) {
for (int j = 0; j < tmpObstacles[i].size(); j++) {
distSq = Utils::SqPointSegDistance(static_cast<Point>(tmpObstacles[i][j].left),
static_cast<Point>(tmpObstacles[i][j].right), position);
if (distSq < maxSqObstDist) {
NeighboursObst.push_back({distSq, tmpObstacles[i][j]});
}
}
}
std::sort(NeighboursObst.begin(), NeighboursObst.end(), Utils::Less<ObstacleSegment>);
}
Point Agent::GetVelocity() const {
return currV;
}
std::pair<unsigned int, unsigned int> Agent::GetCollision() const {
return {collisions, collisionsObst};
}
bool Agent::InitPath() {
return planner->CreateGlobalPath();
}
int Agent::GetID() const {
return id;
}
float Agent::GetRadius() const {
return param.radius;
}
Agent &Agent::operator=(const Agent &obj) {
if (this != &obj) {
start = obj.start;
goal = obj.goal;
id = obj.id;
position = obj.position;
prefV = obj.prefV;
newV = obj.newV;
currV = obj.currV;
param = obj.param;
invTimeBoundaryObst = obj.invTimeBoundaryObst;
invTimeBoundary = obj.invTimeBoundary;
maxSqObstDist = obj.maxSqObstDist;
collisions = obj.collisions;
collisionsObst = obj.collisionsObst;
ORCALines = obj.ORCALines;
NeighboursObst = obj.NeighboursObst;
Neighbours = obj.Neighbours;
options = obj.options;
map = obj.map;
speedSaveBuffer = obj.speedSaveBuffer;
meanSavedSpeed = obj.meanSavedSpeed;
if (planner != nullptr) {
delete planner;
planner = nullptr;
}
planner = (obj.planner == nullptr) ? nullptr : obj.planner->Clone();
}
return *this;
}
Point Agent::GetNext() const {
return nextForLog;
}
bool Agent::CommonPointMAPFTrigger(float distToTargetPoint) {
return (Neighbours.size() >= options->MAPFNum) && (distToTargetPoint < param.sightRadius);
}
//bool Agent::MeanSpeedMAPFTrigger()
//{
// float mean = 0.0f;
//
// if(options->MAPFNum > Neighbours.size()) return false;
//
// for(size_t nCount = 0; nCount < options->MAPFNum; nCount++)
// {
// mean += Neighbours[nCount].second->GetVelocity().EuclideanNorm();
// }
// mean /= static_cast<float>(options->MAPFNum);
//
// return (mean < SMALL_SPEED);
//}
bool Agent::NeighbourGroupMeanSpeedMAPFTrigger() {
size_t nNum = (options->MAPFNum > Neighbours.size()) ? Neighbours.size() : options->MAPFNum;
if (!nNum) return false;
// Kahan summation algorithm
float sum = 0.0f;
float c = 0.0f;
float y, t;
for (size_t nCount = 0; nCount < nNum; nCount++) {
y = Neighbours[nCount].second->meanSavedSpeed - c;
t = sum + y;
c = (t - sum) - y;
sum = t;
}
float mean = sum / nNum;
return (mean < SMALL_SPEED);
}
bool Agent::SingleNeighbourMeanSpeedMAPFTrigger() {
if (!Neighbours.size()) return false;
if (this->meanSavedSpeed < SMALL_SPEED) {
for (size_t nCount = 0; nCount < Neighbours.size(); nCount++) {
if (Neighbours[nCount].second->meanSavedSpeed < SMALL_SPEED) return true;
}
}
return false;
} | 0 | 0.922095 | 1 | 0.922095 | game-dev | MEDIA | 0.650972 | game-dev | 0.959411 | 1 | 0.959411 |
williewillus/Botania | 1,088 | src/api/java/buildcraft/api/gates/IGateExpansion.java | /** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.gates;
import java.util.List;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public interface IGateExpansion {
String getUniqueIdentifier();
String getDisplayName();
GateExpansionController makeController(TileEntity pipeTile);
@SideOnly(Side.CLIENT)
void textureStitch(TextureMap map);
@SideOnly(Side.CLIENT)
IGateStaticRenderState getRenderState();
public interface IGateStaticRenderState {
List<BakedQuad> bake(VertexFormat format);
}
}
| 0 | 0.745502 | 1 | 0.745502 | game-dev | MEDIA | 0.964946 | game-dev | 0.690999 | 1 | 0.690999 |
DruidMech/UE4-CPP-Shooter-Series | 4,545 | Source Code Per Lesson/Section 16 - Khaimera/319 Explosive Agro Enemy/ShooterAnimInstance.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimInstance.h"
#include "WeaponType.h"
#include "ShooterAnimInstance.generated.h"
UENUM(BlueprintType)
enum class EOffsetState : uint8
{
EOS_Aiming UMETA(DisplayName = "Aiming"),
EOS_Hip UMETA(DisplayName = "Hip"),
EOS_Reloading UMETA(DisplayName = "Reloading"),
EOS_InAir UMETA(DisplayName = "InAir"),
EOS_MAX UMETA(DisplayName = "DefaultMAX")
};
/**
*
*/
UCLASS()
class SHOOTER_API UShooterAnimInstance : public UAnimInstance
{
GENERATED_BODY()
public:
UShooterAnimInstance();
UFUNCTION(BlueprintCallable)
void UpdateAnimationProperties(float DeltaTime);
virtual void NativeInitializeAnimation() override;
protected:
/** Handle turning in place variables */
void TurnInPlace();
/** Handle calculations for leaning while running */
void Lean(float DeltaTime);
private:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
class AShooterCharacter* ShooterCharacter;
/** The speed of the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
float Speed;
/** Whether or not the character is in the air */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
bool bIsInAir;
/** Whether or not the character is moving */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
bool bIsAccelerating;
/** Offset yaw used for strafing */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float MovementOffsetYaw;
/** Offset yaw the frame before we stopped moving */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true"))
float LastMovementOffsetYaw;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
bool bAiming;
/** Yaw of the Character this frame; Only updated when standing still and not in air */
float TIPCharacterYaw;
/** Yaw of the Character the previous frame; Only updated when standing still and not in air */
float TIPCharacterYawLastFrame;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Turn In Place", meta = (AllowPrivateAccess = "true"))
float RootYawOffset;
/** Rotation curve value this frame */
float RotationCurve;
/** Rotation curve value last frame */
float RotationCurveLastFrame;
/** The pitch of the aim rotaiton, used for Aim Offset */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Turn In Place", meta = (AllowPrivateAccess = "true"))
float Pitch;
/** True when reloading, used to prevent Aim Offset while reloading */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Turn In Place", meta = (AllowPrivateAccess = "true"))
bool bReloading;
/** Offset state; used to determine which Aim Offset to use */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Turn In Place", meta = (AllowPrivateAccess = "true"))
EOffsetState OffsetState;
/** Character Yaw this frame */
FRotator CharacterRotation;
/** Character Yaw last frame */
FRotator CharacterRotationLastFrame;
/** Yaw delta used for leaning in the running blendspace */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Lean, meta = (AllowPrivateAccess = "true"))
float YawDelta;
/** True when crouching */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Crouching, meta = (AllowPrivateAccess = "true"))
bool bCrouching;
/** True when equipping */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Crouching, meta = (AllowPrivateAccess = "true"))
bool bEquipping;
/** Change the recoil weight based on turning in place and aiming */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
float RecoilWeight;
/** True when turning in place */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
bool bTurningInPlace;
/** Weapon type for the currently equipped weapon */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
EWeaponType EquippedWeaponType;
/** True when not reloading or equipping */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true"))
bool bShouldUseFABRIK;
};
| 0 | 0.95977 | 1 | 0.95977 | game-dev | MEDIA | 0.882434 | game-dev | 0.734201 | 1 | 0.734201 |
holycake/mhsj | 1,294 | d/ourhome/honglou/dreamland/xiaowu.c |
//xiaowu.c 寻李逍遥
inherit ROOM;
int do_open(string arg);
void create()
{
set("short", "小茅屋");
set("long", @LONG
这是一个简陋的小茅屋,东面墙上挂着一柄宝剑,想来主人当年也是叱咤风云。
西面墙上贴着一首诗:
仙灵岛上别洞天,池中孤莲伴月眠。
一朝风雨落水面,愿君拾得惜相怜。
LONG
);
set("exits", ([
"out" : __DIR__"shangu2",
]));
set("objects", ([
__DIR__"npc/servent" : 1,
]));
setup();
}
void init()
{
add_action("do_open","open");
}
int do_open(string arg)
{
object who=this_player();
object ob;
if(who->is_busy()) return notify_fail("你正忙着呢!\n");
if(!arg || arg != "密道")
return notify_fail("你要打开什么?\n");
if( (int) who->query("force_factor") >= 100 )
{
write("打开了西面的一扇暗门。\n");
if( !query("exits/west") ) {
set("exits/west", __DIR__"xiaowu2");
call_out("close_path", 5);
}
return 1;
}
else
{
write("试着推了推墙,但没有什么动静。\n");
return 1;
}
}
int valid_leave(object me, string dir)
{
object ob;
int i;
if( dir == "west" && ob=present("servent", this_object()))
{
message_vision("$N对$n喝道:想进去?宰了我再说!!\n", ob,me);
ob->kill_ob(me);
return notify_fail("快逃!\n");
}
else
return 1;
}
void close_path()
{
if( !query("exits/west") ) return;
message("vision","暗门又喀嚓一声关上了。\n",this_object() );
delete("exits/west");
}
| 0 | 0.79013 | 1 | 0.79013 | game-dev | MEDIA | 0.551563 | game-dev,cli-devtools | 0.746405 | 1 | 0.746405 |
LiteLDev/LeviLamina | 1,949 | src-server/mc/entity/systems/WindChargeFallDamageSystem.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/deps/ecs/Optional.h"
#include "mc/deps/ecs/strict/EntityModifier.h"
#include "mc/deps/ecs/strict/Include.h"
// auto generated forward declare list
// clang-format off
class StrictEntityContext;
struct ActorDataFlagComponent;
struct ActorMovementTickNeededComponent;
struct AutoClimbTravelFlagComponent;
struct FallDistanceComponent;
struct GlidingTravelFlagComponent;
struct HasTeleportedFlagComponent;
struct LavaTravelFlagComponent;
struct LevitateTravelFlagComponent;
struct OnGroundFlagComponent;
struct PassengerComponent;
struct PlayerComponent;
struct StateVectorComponent;
struct WasInWaterFlagComponent;
struct WindChargeKnockbackComponent;
// clang-format on
namespace WindChargeFallDamageSystem {
// functions
// NOLINTBEGIN
MCNAPI void _tickWindChargeFallDamageSystem(
::entt::type_list<::Include<::ActorMovementTickNeededComponent, ::FallDistanceComponent>>,
::StrictEntityContext const& entity,
::StateVectorComponent const& svc,
::WindChargeKnockbackComponent& windChargeKnockback,
::Optional<::PlayerComponent const> playerComponent,
::Optional<::WasInWaterFlagComponent const> wasInWater,
::Optional<::OnGroundFlagComponent const> onGround,
::Optional<::LevitateTravelFlagComponent const> isLevitating,
::Optional<::AutoClimbTravelFlagComponent const> isClimbing,
::Optional<::GlidingTravelFlagComponent const> isGliding,
::Optional<::LavaTravelFlagComponent const> isInLava,
::Optional<::PassengerComponent const> isPassenger,
::Optional<::HasTeleportedFlagComponent const> didTeleport,
::Optional<::ActorDataFlagComponent const> actorDataFlag,
::EntityModifier<::WindChargeKnockbackComponent> modifier
);
// NOLINTEND
} // namespace WindChargeFallDamageSystem
| 0 | 0.774156 | 1 | 0.774156 | game-dev | MEDIA | 0.714892 | game-dev | 0.59959 | 1 | 0.59959 |
skyjake/Doomsday-Engine | 5,254 | doomsday/external/fluidsynth/src/utils/fluid_hash.h | /* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02110-1301, USA.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* Adapted for FluidSynth use by Josh Green <jgreen@users.sourceforge.net>
* September 8, 2009 from glib 2.18.4
*
* - Self contained (no dependencies on glib)
* - changed names to fluid_hashtable_...
*/
#ifndef _FLUID_HASH_H
#define _FLUID_HASH_H
#include "fluidsynth_priv.h"
#include "fluid_list.h"
#include "fluid_sys.h"
/* Extracted from gtypes.h */
typedef void (*fluid_destroy_notify_t)(void *data);
typedef unsigned int (*fluid_hash_func_t)(const void *key);
typedef int (*fluid_equal_func_t)(const void *a, const void *b);
/* End gtypes.h extraction */
typedef int (*fluid_hr_func_t)(void *key, void *value, void *user_data);
typedef struct _fluid_hashtable_iter_t fluid_hashtable_iter_t;
typedef struct _fluid_hashnode_t fluid_hashnode_t;
struct _fluid_hashnode_t
{
void *key;
void *value;
fluid_hashnode_t *next;
unsigned int key_hash;
};
struct _fluid_hashtable_t
{
int size;
int nnodes;
fluid_hashnode_t **nodes;
fluid_hash_func_t hash_func;
fluid_equal_func_t key_equal_func;
volatile int ref_count;
fluid_destroy_notify_t key_destroy_func;
fluid_destroy_notify_t value_destroy_func;
fluid_rec_mutex_t mutex; // Optionally used in other modules (fluid_settings.c for example)
};
struct _fluid_hashtable_iter_t
{
/*< private >*/
void * dummy1;
void * dummy2;
void * dummy3;
int dummy4;
int dummy5; // Bool
void * dummy6;
};
fluid_hashtable_t* new_fluid_hashtable (fluid_hash_func_t hash_func,
fluid_equal_func_t key_equal_func);
fluid_hashtable_t* new_fluid_hashtable_full (fluid_hash_func_t hash_func,
fluid_equal_func_t key_equal_func,
fluid_destroy_notify_t key_destroy_func,
fluid_destroy_notify_t value_destroy_func);
void delete_fluid_hashtable(fluid_hashtable_t *hashtable);
void fluid_hashtable_iter_init (fluid_hashtable_iter_t *iter, fluid_hashtable_t *hashtable);
int fluid_hashtable_iter_next (fluid_hashtable_iter_t *iter, void **key, void **value);
fluid_hashtable_t *fluid_hashtable_iter_get_hash_table (fluid_hashtable_iter_t *iter);
void fluid_hashtable_iter_remove (fluid_hashtable_iter_t *iter);
void fluid_hashtable_iter_steal (fluid_hashtable_iter_t *iter);
fluid_hashtable_t* fluid_hashtable_ref (fluid_hashtable_t *hashtable);
void fluid_hashtable_unref (fluid_hashtable_t *hashtable);
void *fluid_hashtable_lookup (fluid_hashtable_t *hashtable, const void *key);
int fluid_hashtable_lookup_extended (fluid_hashtable_t *hashtable, const void *lookup_key,
void **orig_key, void **value);
void fluid_hashtable_insert (fluid_hashtable_t *hashtable, void *key, void *value);
void fluid_hashtable_replace (fluid_hashtable_t *hashtable, void *key, void *value);
int fluid_hashtable_remove (fluid_hashtable_t *hashtable, const void *key);
int fluid_hashtable_steal (fluid_hashtable_t *hashtable, const void *key);
void fluid_hashtable_remove_all (fluid_hashtable_t *hashtable);
void fluid_hashtable_steal_all (fluid_hashtable_t *hashtable);
unsigned int fluid_hashtable_foreach_steal (fluid_hashtable_t *hashtable,
fluid_hr_func_t func, void *user_data);
void fluid_hashtable_foreach (fluid_hashtable_t *hashtable, fluid_hr_func_t func,
void *user_data);
void *fluid_hashtable_find (fluid_hashtable_t *hashtable, fluid_hr_func_t predicate,
void *user_data);
unsigned int fluid_hashtable_size (fluid_hashtable_t *hashtable);
fluid_list_t *fluid_hashtable_get_keys (fluid_hashtable_t *hashtable);
fluid_list_t *fluid_hashtable_get_values (fluid_hashtable_t *hashtable);
int fluid_str_equal (const void *v1, const void *v2);
unsigned int fluid_str_hash (const void *v);
int fluid_direct_equal (const void *v1, const void *v2);
unsigned int fluid_direct_hash (const void *v);
int fluid_int_equal (const void *v1, const void *v2);
unsigned int fluid_int_hash (const void *v);
#endif /* _FLUID_HASH_H */
| 0 | 0.785325 | 1 | 0.785325 | game-dev | MEDIA | 0.441856 | game-dev | 0.631685 | 1 | 0.631685 |
RadicalCSG/Chisel.Prototype | 6,696 | Packages/com.chisel.unity.editor/Chisel/Editor/SceneView/SceneHandles/SceneHandles.Edge1D.cs | using UnityEditor;
using UnityEngine;
using Chisel.Core;
namespace Chisel.Editors
{
public sealed partial class SceneHandles
{
internal static int s_Edge1DHash = "Edge1DHash".GetHashCode();
public static Vector3[] Edge1DHandle(Axis axis, Vector3[] points, Vector3 from, Vector3 to, Vector3 direction, float snappingStep, float handleSize, CapFunction capFunction, bool selectLockingAxisOnClick = false)
{
var id = GUIUtility.GetControlID (s_Edge1DHash, FocusType.Keyboard);
return Edge1DHandle(id, axis, points, from, to, direction, snappingStep, handleSize, capFunction, selectLockingAxisOnClick);
}
public static Vector3[] Edge1DHandle(int id, Axis axis, Vector3[] points, Vector3 from, Vector3 to, Vector3 direction, float snappingStep, float handleSize, CapFunction capFunction, bool selectLockingAxisOnClick = false)
{
var evt = Event.current;
switch (evt.GetTypeForControl(id))
{
case EventType.Layout:
{
if (SceneHandles.InCameraOrbitMode)
break;
UnityEditor.HandleUtility.AddControl(id, UnityEditor.HandleUtility.DistanceToLine(from, to) * 2.0f);
break;
}
case EventType.Repaint:
{
DrawLine(from, to);
break;
}
}
var position = (from + to) * 0.5f;
var result = Slider1D.Do(id, axis, points, position, direction, snappingStep, handleSize, capFunction, selectLockingAxisOnClick);
return result;
}
public static float Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, float snappingStep, float handleSize, CapFunction capFunction)
{
var id = GUIUtility.GetControlID (s_Edge1DHash, FocusType.Keyboard);
return Edge1DHandleOffset(id, axis, from, to, snappingStep, handleSize, capFunction);
}
public static float Edge1DHandleOffset(int id, Axis axis, Vector3 from, Vector3 to, float snappingStep, float handleSize, CapFunction capFunction)
{
var position = (from + to) * 0.5f;
var direction = (Vector3)Matrix4x4.identity.GetColumn((int)axis);
return Edge1DHandleOffset(id, axis, from, to, position, direction, snappingStep, handleSize, capFunction)[(int)axis];
}
public static float Edge1DHandle(Axis axis, Vector3 from, Vector3 to, float snappingStep = 0, float handleSize = 0)
{
return Edge1DHandle(axis, from, to, snappingStep, handleSize, Chisel.Editors.SceneHandles.OutlinedDotHandleCap);
}
public static float Edge1DHandle(Axis axis, Vector3 from, Vector3 to, float snappingStep, float handleSize, CapFunction capFunction)
{
var id = GUIUtility.GetControlID(s_Edge1DHash, FocusType.Keyboard);
var position = (from + to) * 0.5f;
var direction = (Vector3)Matrix4x4.identity.GetColumn((int)axis);
return Edge1DHandleOffset(id, axis, from, to, position, direction, snappingStep, handleSize, capFunction)[(int)axis] + position[(int)axis];
}
public static float Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, float snappingStep = 0, float handleSize = 0)
{
return Edge1DHandleOffset(axis, from, to, snappingStep, handleSize, Chisel.Editors.SceneHandles.OutlinedDotHandleCap);
}
public static float Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, CapFunction capFunction)
{
return Edge1DHandleOffset(axis, from, to, 0, 0, capFunction);
}
public static float Edge1DHandleOffset(int id, Axis axis, Vector3 from, Vector3 to, CapFunction capFunction)
{
return Edge1DHandleOffset(id, axis, from, to, 0, 0, capFunction);
}
// TODO: improve this
public static Vector3 Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, Vector3 direction, float snappingStep= 0 , float handleSize = 0)
{
var position = (from + to) * 0.5f;
var id = GUIUtility.GetControlID(s_Edge1DHash, FocusType.Keyboard);
return Edge1DHandleOffset(id, axis, from, to, position, direction, snappingStep, handleSize, Chisel.Editors.SceneHandles.OutlinedDotHandleCap);
}
public static Vector3 Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, Vector3 direction, float snappingStep, float handleSize, CapFunction capFunction)
{
var position = (from + to) * 0.5f;
var id = GUIUtility.GetControlID(s_Edge1DHash, FocusType.Keyboard);
return Edge1DHandleOffset(id, axis, from, to, position, direction, snappingStep, handleSize, capFunction);
}
public static Vector3 Edge1DHandleOffset(Axis axis, Vector3 from, Vector3 to, Vector3 position, Vector3 direction, float snappingStep, float handleSize, CapFunction capFunction)
{
var id = GUIUtility.GetControlID(s_Edge1DHash, FocusType.Keyboard);
return Edge1DHandleOffset(id, axis, from, to, position, direction, snappingStep, handleSize, capFunction);
}
public static Vector3 Edge1DHandleOffset(int id, Axis axis, Vector3 from, Vector3 to, Vector3 position, Vector3 direction, float snappingStep, float handleSize, CapFunction capFunction)
{
if (snappingStep == 0)
snappingStep = Snapping.MoveSnappingSteps[(int)axis];
if (handleSize == 0)
handleSize = UnityEditor.HandleUtility.GetHandleSize(position) * 0.05f;
var evt = Event.current;
switch (evt.GetTypeForControl(id))
{
case EventType.Layout:
{
if (SceneHandles.InCameraOrbitMode)
break;
UnityEditor.HandleUtility.AddControl(id, UnityEditor.HandleUtility.DistanceToLine(from, to));
break;
}
case EventType.Repaint:
{
SetCursor(id, from, to);
linePoints[0] = from;
linePoints[1] = to;
SceneHandles.DrawAAPolyLine(3.0f, linePoints);
break;
}
}
var points = new Vector3[] { from, to };
var result = Slider1DHandle(id, axis, points, position, direction, snappingStep, handleSize, capFunction);
return result[0] - from;
}
}
}
| 0 | 0.84018 | 1 | 0.84018 | game-dev | MEDIA | 0.769236 | game-dev | 0.965382 | 1 | 0.965382 |
ServUO/ServUO | 16,748 | Scripts/Items/Containers/Mahjong/MahjongPlayers.cs | using System;
using System.Collections;
namespace Server.Engines.Mahjong
{
public class MahjongPlayers
{
private readonly MahjongGame m_Game;
private readonly Mobile[] m_Players;
private readonly bool[] m_InGame;
private readonly bool[] m_PublicHand;
private readonly int[] m_Scores;
private readonly ArrayList m_Spectators;
private int m_DealerPosition;
public MahjongPlayers(MahjongGame game, int maxPlayers, int baseScore)
{
this.m_Game = game;
this.m_Spectators = new ArrayList();
this.m_Players = new Mobile[maxPlayers];
this.m_InGame = new bool[maxPlayers];
this.m_PublicHand = new bool[maxPlayers];
this.m_Scores = new int[maxPlayers];
for (int i = 0; i < this.m_Scores.Length; i++)
this.m_Scores[i] = baseScore;
}
public MahjongPlayers(MahjongGame game, GenericReader reader)
{
this.m_Game = game;
this.m_Spectators = new ArrayList();
int version = reader.ReadInt();
int seats = reader.ReadInt();
this.m_Players = new Mobile[seats];
this.m_InGame = new bool[seats];
this.m_PublicHand = new bool[seats];
this.m_Scores = new int[seats];
for (int i = 0; i < seats; i++)
{
this.m_Players[i] = reader.ReadMobile();
this.m_PublicHand[i] = reader.ReadBool();
this.m_Scores[i] = reader.ReadInt();
}
this.m_DealerPosition = reader.ReadInt();
}
public MahjongGame Game
{
get
{
return this.m_Game;
}
}
public int Seats
{
get
{
return this.m_Players.Length;
}
}
public Mobile Dealer
{
get
{
return this.m_Players[this.m_DealerPosition];
}
}
public int DealerPosition
{
get
{
return this.m_DealerPosition;
}
}
public Mobile GetPlayer(int index)
{
if (index < 0 || index >= this.m_Players.Length)
return null;
else
return this.m_Players[index];
}
public int GetPlayerIndex(Mobile mobile)
{
for (int i = 0; i < this.m_Players.Length; i++)
{
if (this.m_Players[i] == mobile)
return i;
}
return -1;
}
public bool IsInGameDealer(Mobile mobile)
{
if (this.Dealer != mobile)
return false;
else
return this.m_InGame[this.m_DealerPosition];
}
public bool IsInGamePlayer(int index)
{
if (index < 0 || index >= this.m_Players.Length || this.m_Players[index] == null)
return false;
else
return this.m_InGame[index];
}
public bool IsInGamePlayer(Mobile mobile)
{
int index = this.GetPlayerIndex(mobile);
return this.IsInGamePlayer(index);
}
public bool IsSpectator(Mobile mobile)
{
return this.m_Spectators.Contains(mobile);
}
public int GetScore(int index)
{
if (index < 0 || index >= this.m_Scores.Length)
return 0;
else
return this.m_Scores[index];
}
public bool IsPublic(int index)
{
if (index < 0 || index >= this.m_PublicHand.Length)
return false;
else
return this.m_PublicHand[index];
}
public void SetPublic(int index, bool value)
{
if (index < 0 || index >= this.m_PublicHand.Length || this.m_PublicHand[index] == value)
return;
this.m_PublicHand[index] = value;
this.SendTilesPacket(true, !this.m_Game.SpectatorVision);
if (this.IsInGamePlayer(index))
this.m_Players[index].SendLocalizedMessage(value ? 1062775 : 1062776); // Your hand is [not] publicly viewable.
}
public ArrayList GetInGameMobiles(bool players, bool spectators)
{
ArrayList list = new ArrayList();
if (players)
{
for (int i = 0; i < this.m_Players.Length; i++)
{
if (this.IsInGamePlayer(i))
list.Add(this.m_Players[i]);
}
}
if (spectators)
{
list.AddRange(this.m_Spectators);
}
return list;
}
public void CheckPlayers()
{
bool removed = false;
for (int i = 0; i < this.m_Players.Length; i++)
{
Mobile player = this.m_Players[i];
if (player != null)
{
if (player.Deleted)
{
this.m_Players[i] = null;
this.SendPlayerExitMessage(player);
this.UpdateDealer(true);
removed = true;
}
else if (this.m_InGame[i])
{
if (player.NetState == null)
{
this.m_InGame[i] = false;
this.SendPlayerExitMessage(player);
this.UpdateDealer(true);
removed = true;
}
else if (!this.m_Game.IsAccessibleTo(player) || player.Map != this.m_Game.Map || !player.InRange(this.m_Game.GetWorldLocation(), 5))
{
this.m_InGame[i] = false;
player.Send(new MahjongRelieve(this.m_Game));
this.SendPlayerExitMessage(player);
this.UpdateDealer(true);
removed = true;
}
}
}
}
for (int i = 0; i < this.m_Spectators.Count;)
{
Mobile mobile = (Mobile)this.m_Spectators[i];
if (mobile.NetState == null || mobile.Deleted)
{
this.m_Spectators.RemoveAt(i);
}
else if (!this.m_Game.IsAccessibleTo(mobile) || mobile.Map != this.m_Game.Map || !mobile.InRange(this.m_Game.GetWorldLocation(), 5))
{
this.m_Spectators.RemoveAt(i);
mobile.Send(new MahjongRelieve(this.m_Game));
}
else
{
i++;
}
}
if (removed && !this.UpdateSpectators())
this.SendPlayersPacket(true, true);
}
public void Join(Mobile mobile)
{
int index = this.GetPlayerIndex(mobile);
if (index >= 0)
{
this.AddPlayer(mobile, index, true);
}
else
{
int nextSeat = this.GetNextSeat();
if (nextSeat >= 0)
{
this.AddPlayer(mobile, nextSeat, true);
}
else
{
this.AddSpectator(mobile);
}
}
}
public void LeaveGame(Mobile player)
{
int index = this.GetPlayerIndex(player);
if (index >= 0)
{
this.m_InGame[index] = false;
this.SendPlayerExitMessage(player);
this.UpdateDealer(true);
this.SendPlayersPacket(true, true);
}
else
{
this.m_Spectators.Remove(player);
}
}
public void ResetScores(int value)
{
for (int i = 0; i < this.m_Scores.Length; i++)
{
this.m_Scores[i] = value;
}
this.SendPlayersPacket(true, this.m_Game.ShowScores);
this.SendLocalizedMessage(1062697); // The dealer redistributes the score sticks evenly.
}
public void TransferScore(Mobile from, int toPosition, int amount)
{
int fromPosition = this.GetPlayerIndex(from);
Mobile to = this.GetPlayer(toPosition);
if (fromPosition < 0 || to == null || this.m_Scores[fromPosition] < amount)
return;
this.m_Scores[fromPosition] -= amount;
this.m_Scores[toPosition] += amount;
if (this.m_Game.ShowScores)
{
this.SendPlayersPacket(true, true);
}
else
{
from.Send(new MahjongPlayersInfo(this.m_Game, from));
to.Send(new MahjongPlayersInfo(this.m_Game, to));
}
this.SendLocalizedMessage(1062774, string.Format("{0}\t{1}\t{2}", from.Name, to.Name, amount)); // ~1_giver~ gives ~2_receiver~ ~3_number~ points.
}
public void OpenSeat(int index)
{
Mobile player = this.GetPlayer(index);
if (player == null)
return;
if (this.m_InGame[index])
player.Send(new MahjongRelieve(this.m_Game));
this.m_Players[index] = null;
this.SendLocalizedMessage(1062699, player.Name); // ~1_name~ is relieved from the game by the dealer.
this.UpdateDealer(true);
if (!this.UpdateSpectators())
this.SendPlayersPacket(true, true);
}
public void AssignDealer(int index)
{
Mobile to = this.GetPlayer(index);
if (to == null || !this.m_InGame[index])
return;
int oldDealer = this.m_DealerPosition;
this.m_DealerPosition = index;
if (this.IsInGamePlayer(oldDealer))
this.m_Players[oldDealer].Send(new MahjongPlayersInfo(this.m_Game, this.m_Players[oldDealer]));
to.Send(new MahjongPlayersInfo(this.m_Game, to));
this.SendDealerChangedMessage();
}
public void SendPlayersPacket(bool players, bool spectators)
{
foreach (Mobile mobile in this.GetInGameMobiles(players, spectators))
{
mobile.Send(new MahjongPlayersInfo(this.m_Game, mobile));
}
}
public void SendGeneralPacket(bool players, bool spectators)
{
ArrayList mobiles = this.GetInGameMobiles(players, spectators);
if (mobiles.Count == 0)
return;
MahjongGeneralInfo generalInfo = new MahjongGeneralInfo(this.m_Game);
generalInfo.Acquire();
foreach (Mobile mobile in mobiles)
{
mobile.Send(generalInfo);
}
generalInfo.Release();
}
public void SendTilesPacket(bool players, bool spectators)
{
foreach (Mobile mobile in this.GetInGameMobiles(players, spectators))
{
mobile.Send(new MahjongTilesInfo(this.m_Game, mobile));
}
}
public void SendTilePacket(MahjongTile tile, bool players, bool spectators)
{
foreach (Mobile mobile in this.GetInGameMobiles(players, spectators))
{
mobile.Send(new MahjongTileInfo(tile, mobile));
}
}
public void SendRelievePacket(bool players, bool spectators)
{
ArrayList mobiles = this.GetInGameMobiles(players, spectators);
if (mobiles.Count == 0)
return;
MahjongRelieve relieve = new MahjongRelieve(this.m_Game);
relieve.Acquire();
foreach (Mobile mobile in mobiles)
{
mobile.Send(relieve);
}
relieve.Release();
}
public void SendLocalizedMessage(int number)
{
foreach (Mobile mobile in this.GetInGameMobiles(true, true))
{
mobile.SendLocalizedMessage(number);
}
}
public void SendLocalizedMessage(int number, string args)
{
foreach (Mobile mobile in this.GetInGameMobiles(true, true))
{
mobile.SendLocalizedMessage(number, args);
}
}
public void Save(GenericWriter writer)
{
writer.Write((int)0); // version
writer.Write(this.Seats);
for (int i = 0; i < this.Seats; i++)
{
writer.Write(this.m_Players[i]);
writer.Write(this.m_PublicHand[i]);
writer.Write(this.m_Scores[i]);
}
writer.Write(this.m_DealerPosition);
}
private void UpdateDealer(bool message)
{
if (this.IsInGamePlayer(this.m_DealerPosition))
return;
for (int i = this.m_DealerPosition + 1; i < this.m_Players.Length; i++)
{
if (this.IsInGamePlayer(i))
{
this.m_DealerPosition = i;
if (message)
this.SendDealerChangedMessage();
return;
}
}
for (int i = 0; i < this.m_DealerPosition; i++)
{
if (this.IsInGamePlayer(i))
{
this.m_DealerPosition = i;
if (message)
this.SendDealerChangedMessage();
return;
}
}
}
private int GetNextSeat()
{
for (int i = this.m_DealerPosition; i < this.m_Players.Length; i++)
{
if (this.m_Players[i] == null)
return i;
}
for (int i = 0; i < this.m_DealerPosition; i++)
{
if (this.m_Players[i] == null)
return i;
}
return -1;
}
private bool UpdateSpectators()
{
if (this.m_Spectators.Count == 0)
return false;
int nextSeat = this.GetNextSeat();
if (nextSeat >= 0)
{
Mobile newPlayer = (Mobile)this.m_Spectators[0];
this.m_Spectators.RemoveAt(0);
this.AddPlayer(newPlayer, nextSeat, false);
this.UpdateSpectators();
return true;
}
else
{
return false;
}
}
private void AddPlayer(Mobile player, int index, bool sendJoinGame)
{
this.m_Players[index] = player;
this.m_InGame[index] = true;
this.UpdateDealer(false);
if (sendJoinGame)
player.Send(new MahjongJoinGame(this.m_Game));
this.SendPlayersPacket(true, true);
player.Send(new MahjongGeneralInfo(this.m_Game));
player.Send(new MahjongTilesInfo(this.m_Game, player));
if (this.m_DealerPosition == index)
this.SendLocalizedMessage(1062773, player.Name); // ~1_name~ has entered the game as the dealer.
else
this.SendLocalizedMessage(1062772, player.Name); // ~1_name~ has entered the game as a player.
}
private void AddSpectator(Mobile mobile)
{
if (!this.IsSpectator(mobile))
{
this.m_Spectators.Add(mobile);
}
mobile.Send(new MahjongJoinGame(this.m_Game));
mobile.Send(new MahjongPlayersInfo(this.m_Game, mobile));
mobile.Send(new MahjongGeneralInfo(this.m_Game));
mobile.Send(new MahjongTilesInfo(this.m_Game, mobile));
}
private void SendDealerChangedMessage()
{
if (this.Dealer != null)
this.SendLocalizedMessage(1062698, this.Dealer.Name); // ~1_name~ is assigned the dealer.
}
private void SendPlayerExitMessage(Mobile who)
{
this.SendLocalizedMessage(1062762, who.Name); // ~1_name~ has left the game.
}
}
} | 0 | 0.755384 | 1 | 0.755384 | game-dev | MEDIA | 0.687526 | game-dev | 0.831985 | 1 | 0.831985 |
arvindrajayadav/Good-Robot | 3,176 | ui_keybind.cpp | #include "master.h"
#include "ui_keybind.h"
using namespace pyrodactyl;
void KeyBindMenu::Load(rapidxml::xml_node<char> *node)
{
if (NodeValid("bg", node))
bg.Load(node->first_node("bg"));
if (NodeValid("title", node))
title.Load(node->first_node("title"));
if (NodeValid("menu", node))
{
rapidxml::xml_node<char> *menode = node->first_node("menu");
if (NodeValid("ref", menode))
ref.Load(menode->first_node("ref"));
if (NodeValid("settings", menode))
menu.Load(menode->first_node("settings"));
menu.Rows(CONTROL_REBINDABLE_COUNT);
if (NodeValid("prompt", menode))
prompt.Load(menode->first_node("prompt"));
if (NodeValid("inc", menode))
inc.Load(menode->first_node("inc"));
}
if (NodeValid("back", node))
back.Load(node->first_node("back"));
//Initialize the menu
InitMenu();
}
void KeyBindMenu::InitMenu()
{
int start = 0, size = CONTROL_REBINDABLE_COUNT, r = menu.Rows();
for (int i = 0; i < size * 2; i++)
{
Button b;
b.Init(ref, nullptr, inc.RawPosX() * (i / r), inc.RawPosY() * (i % r));
if (i < r)
{
b.caption.text = SDL_GetScancodeName(gInput.iv[start + (i % r)].key_val);
b.desc.text = gInput.iv[start + (i % r)].name;
}
else
{
b.caption.text = SDL_GetScancodeName(gInput.iv[start + (i % r)].key_alt);
b.desc.enabled = false;
}
menu.element.push_back(b);
}
menu.AssignPaths();
}
void KeyBindMenu::SetCaption()
{
int start = 0, size = CONTROL_REBINDABLE_COUNT, r = menu.Rows();
for (int i = 0; i < size * 2; i++)
{
if (i < r)
menu.element.at(i).caption.text = SDL_GetScancodeName(gInput.iv[start + (i % r)].key_val);
else
menu.element.at(i).caption.text = SDL_GetScancodeName(gInput.iv[start + (i % r)].key_alt);
}
}
bool KeyBindMenu::HandleEvents()
{
switch (state)
{
case STATE_NORMAL:
choice = menu.HandleEvents();
if (choice >= 0)
{
prompt.Swap(menu.element.at(choice).caption);
state = STATE_KEY;
break;
}
break;
case STATE_KEY:
if (InputAnyKeyPressed())
{
int key = InputLastPressed();
//Cutoff for valid values and to avoid stuff like setting left click, sleep or monitor switch button as input
//230 = Right Alt in SDL_Scancode.h
if (key > 0 && key < 230)
{
SwapKey(static_cast<SDL_Scancode>(key));
SetCaption();
menu.element.at(choice).caption.col = prompt.col_prev;
state = STATE_NORMAL;
}
}
break;
default:break;
}
return (back.HandleEvents() == BUAC_LCLICK);
}
void KeyBindMenu::Draw()
{
bg.Draw();
title.Draw();
menu.Draw();
back.Draw();
}
void KeyBindMenu::SwapKey(const SDL_Scancode &find)
{
int start = 0, size = CONTROL_REBINDABLE_COUNT, r = menu.Rows();
int pos = start + (choice % r);
for (int i = start; i < size; ++i)
{
if (gInput.iv[i].key_val == find)
{
gInput.iv[i].key_val = gInput.iv[pos].key_val;
break;
}
else if (gInput.iv[i].key_alt == find)
{
gInput.iv[i].key_alt = gInput.iv[pos].key_val;
break;
}
}
if (choice < r)
gInput.iv[pos].key_val = find;
else
gInput.iv[pos].key_alt = find;
}
void KeyBindMenu::SetUI()
{
menu.Clear();
ref.SetUI();
inc.SetUI();
InitMenu();
bg.SetUI();
title.SetUI();
back.SetUI();
} | 0 | 0.799974 | 1 | 0.799974 | game-dev | MEDIA | 0.85988 | game-dev | 0.914386 | 1 | 0.914386 |
google/earthenterprise | 1,612 | earth_enterprise/src/common/khThreadPool.cpp | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "khThreadPool.h"
void
khThreadPool::poolThread::thread_main(void)
{
while (1) {
{
// This must be in an inner scope so the mutex is released
// before we delete below
khLockGuard guard(mutex);
while (!ready) condvar.wait(mutex);
fun();
ready = false;
// clear out the functor in case it holds resources that need
// to be released. That way if this thread gets stored in the pool,
// it won't hold the resources busy until it's reused.
fun = khFunctor<void>();
}
if (!pool.returnThread(this)) {
// we can't return ourself to the pool (it's already full) so we
// go ahead and delete our object and return from the thread
// func. Since this is a detached thread, returning from this
// func will clean up the thread
delete this;
return;
}
}
}
void
khThreadPool::poolThread::run(const khFunctor<void> &fun_)
{
khLockGuard guard(mutex);
fun = fun_;
ready = true;
condvar.signal_one();
}
| 0 | 0.626866 | 1 | 0.626866 | game-dev | MEDIA | 0.200496 | game-dev | 0.615171 | 1 | 0.615171 |
TeamWizardry/Wizardry | 2,786 | src/main/java/com/teamwizardry/wizardry/client/jei/fluid/FluidCraftingCategory.java | package com.teamwizardry.wizardry.client.jei.fluid;
import com.teamwizardry.wizardry.Wizardry;
import com.teamwizardry.wizardry.client.jei.WizardryJEIPlugin;
import mezz.jei.api.gui.IDrawable;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
/**
* @author WireSegal
* Created at 4:50 PM on 1/13/18.
*/
@SideOnly(Side.CLIENT)
public class FluidCraftingCategory implements IRecipeCategory<FluidRecipeJEI> {
private static final ResourceLocation RECIPE_BACKGROUND = new ResourceLocation("jei", "textures/gui/recipe_background.png");
public IDrawable info = WizardryJEIPlugin.helpers.getGuiHelper()
.createDrawable(RECIPE_BACKGROUND, 212, 39, 16, 16);
public IDrawable background = WizardryJEIPlugin.helpers.getGuiHelper()
.createDrawable(new ResourceLocation(Wizardry.MODID, "textures/gui/categories.png"), 0, 0, 76, 100);
public IDrawable slots = WizardryJEIPlugin.helpers.getGuiHelper()
.createDrawable(new ResourceLocation(Wizardry.MODID, "textures/gui/categories.png"), 0, 128, 54, 18);
@Nonnull
@Override
public String getUid() {
return Wizardry.MODID + ":fluid";
}
@Nonnull
@Override
public String getTitle() {
return I18n.format("jei.recipe." + getUid());
}
@Nonnull
@Override
public String getModName() {
return Wizardry.MODNAME;
}
@Nonnull
@Override
public IDrawable getBackground() {
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
return background;
}
@Override
public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull FluidRecipeJEI recipeWrapper, @Nonnull IIngredients ingredients) {
recipeLayout.getItemStacks().init(0, true, 0, 13);
recipeLayout.getFluidStacks().init(0, true, 30, 14);
recipeLayout.getItemStacks().init(1, true, 11, 46);
recipeLayout.getItemStacks().init(2, true, 29, 46);
recipeLayout.getItemStacks().init(3, true, 47, 46);
recipeLayout.getItemStacks().init(4, true, 11, 64);
recipeLayout.getItemStacks().init(5, true, 29, 64);
recipeLayout.getItemStacks().init(6, true, 47, 64);
recipeLayout.getItemStacks().init(7, true, 11, 82);
recipeLayout.getItemStacks().init(8, true, 29, 82);
recipeLayout.getItemStacks().init(9, true, 47, 82);
if (recipeWrapper.isFluidOutput())
recipeLayout.getFluidStacks().init(1, false, 59, 14);
else
recipeLayout.getItemStacks().init(10, false, 58, 13);
recipeLayout.getItemStacks().set(ingredients);
recipeLayout.getFluidStacks().set(ingredients);
}
}
| 0 | 0.960118 | 1 | 0.960118 | game-dev | MEDIA | 0.97957 | game-dev | 0.979221 | 1 | 0.979221 |
WildBamaBoy/minecraft-comes-alive | 3,352 | src/main/java/mca/items/ItemGuideBook.java | package mca.items;
import mca.core.Constants;
import mca.core.MCA;
import mca.core.minecraft.ItemsMCA;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemWrittenBook;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.play.server.SPacketSetSlot;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentUtils;
import net.minecraft.world.World;
public class ItemGuideBook extends ItemWrittenBook {
public ItemGuideBook() {
super();
}
@Override
public void onUpdate(ItemStack itemStack, World world, Entity entity, int unknownInt, boolean unknownBoolean) {
super.onUpdate(itemStack, world, entity, unknownInt, unknownBoolean);
if (!world.isRemote && !itemStack.hasTagCompound()) ItemsMCA.setBookNBT(itemStack);
}
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) {
ItemStack itemstack = playerIn.getHeldItem(handIn);
if (worldIn.isRemote) {
playerIn.openGui(MCA.getInstance(), Constants.GUI_ID_GUIDEBOOK, worldIn, (int)playerIn.posX, (int)playerIn.posY, (int)playerIn.posZ);
}
return new ActionResult(EnumActionResult.SUCCESS, itemstack);
}
private void resolveContents(ItemStack stack, EntityPlayer player) {
if (stack.getTagCompound() != null) {
NBTTagCompound nbttagcompound = stack.getTagCompound();
if (!nbttagcompound.getBoolean("resolved")) {
nbttagcompound.setBoolean("resolved", true);
if (validBookTagContents(nbttagcompound)) {
NBTTagList nbttaglist = nbttagcompound.getTagList("pages", 8);
for (int i = 0; i < nbttaglist.tagCount(); ++i) {
String s = nbttaglist.getStringTagAt(i);
ITextComponent itextcomponent;
try {
itextcomponent = ITextComponent.Serializer.fromJsonLenient(s);
itextcomponent = TextComponentUtils.processComponent(player, itextcomponent, player);
} catch (Exception var9) {
itextcomponent = new TextComponentString(s);
}
nbttaglist.set(i, new NBTTagString(ITextComponent.Serializer.componentToJson(itextcomponent)));
}
nbttagcompound.setTag("pages", nbttaglist);
if (player instanceof EntityPlayerMP && player.getHeldItemMainhand() == stack) {
Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem);
((EntityPlayerMP)player).connection.sendPacket(new SPacketSetSlot(0, slot.slotNumber, stack));
}
}
}
}
}
} | 0 | 0.869018 | 1 | 0.869018 | game-dev | MEDIA | 0.999647 | game-dev | 0.979018 | 1 | 0.979018 |
rrika/cdcEngineDXHR | 2,504 | cdcScript/ScriptType.h | #pragma once
#include "cdcScript/cdcScript.h" // for DataValue
#include "cdcScript/DataType.h"
#include "cdcScript/ScriptName.h"
#include "cdcSys/RCObject.h"
#include "cdcSys/SArray.h"
namespace cdc {
class NativeScriptType;
class ScriptObject;
class ScriptType;
struct DataMember { // line 219
DataType m_type; // 0
uint16_t m_offset; // C
uint16_t m_name; // E
uint32_t m_init; // 10
};
struct Prototype { // 377
ScriptType *scriptType;
uint8_t flags4;
uint8_t callType; // 5
uint16_t vtIndex; // 6
uint16_t id8;
uint16_t idA;
SArray<DataMember> args;
DataType returnType;
uint32_t GetNumArgs() {
return args ? args.size() : 0;
}
};
class Function { // 477
public:
enum Flags {
NATIVE = 1
};
Prototype *prototype;
uint8_t flags; // 4
uint32_t padding8;
SArray<DataMember> m_locals;
uint32_t padding10;
CallbackCallFunction *nativeFunc; // 14
SArray<uint32_t> m_scriptFunc;
};
static_assert(sizeof(Function) == 0x1C);
struct VTable { // 594
uint16_t size;
Function *funcs[];
};
struct VTableArray { // 624
uint16_t size;
uint16_t field_2;
uint16_t field_4;
uint16_t field_6;
VTable **table;
};
struct ScriptTypeStreamData { // 692
uint32_t m_version;
uint16_t field_4;
uint16_t field_6;
ScriptName m_name; // 08
char *m_nativeScriptPackageName; // 0C
char *m_nativeScriptName; // 10
ScriptType *m_scriptType; // 14
ScriptType *m_superScriptType; // 18
// TODO
uint8_t padding[0x2C-0x1C];
// TODO
SArray<DataMember> m_members; // 2C
uint32_t padding30;
Prototype *m_prototypes; // 34
SArray<Function> m_functions; // 38
VTableArray m_vtables; // 3C
SArray<ScriptType*> scriptTypeImports; // 48
uint16_t m_depth; // 4C
uint16_t m_packageName; // 4E
};
static_assert(sizeof(ScriptTypeStreamData) == 0x50);
class ScriptType : public RCObject { // 749
public:
ScriptTypeStreamData* blob;
NativeScriptType* nativeScriptType = nullptr;
public:
ScriptObject *CreateObject();
ScriptType(uint32_t size) {
blob = (ScriptTypeStreamData*) new char[size];
}
Function *GetVFunction(int32_t state, int32_t vtIndex) {
VTable *table = blob->m_vtables.table[vtIndex];
if (state >= table->size)
return table->funcs[0];
else
return table->funcs[state];
}
virtual ~ScriptType() {
// TODO
delete[] (char*)blob;
}
virtual void finalize() { /*TODO*/ }
ScriptType *getParentType() { return blob->m_superScriptType; }
ScriptType *getClosestNativeAncestor(); // HACK
};
}
| 0 | 0.663067 | 1 | 0.663067 | game-dev | MEDIA | 0.5516 | game-dev | 0.534923 | 1 | 0.534923 |
gitzhzhg/SeismicPackage | 21,383 | CPSeis/spws_home/oop/geom/rp_cards.cc |
/*<license>
-------------------------------------------------------------------------------
Copyright (c) 2007 ConocoPhillips Company
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
</license>*/
//---------------------- rp_cards.cc -----------------------//
//---------------------- rp_cards.cc -----------------------//
//---------------------- rp_cards.cc -----------------------//
// implementation file for the RpCards class
// derived from the SmartArray class
// subdirectory geom
#include "geom/rp_cards.hh"
#include "geom/rp_card.hh"
#include "geom/fg_informer.hh"
#include "geom/fg_connect.hh"
#include "geom/fg_constants.hh"
#include "geom/acc_nchan.hh"
#include "oprim/acc_search.hh"
#include "oprim/fast_sort.hh"
#include "cprim.h"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#define STEP 2000
//--------------------- static functions ------------------------//
//--------------------- static functions ------------------------//
//--------------------- static functions ------------------------//
#define RPCARD ((RpCards*)data)->unsafeRpCard(index)
static float get_pattern_number(void *data, long index)
{
return (float)RPCARD->getRpPatternNumber();
}
//---------------------- constructor -----------------------//
//---------------------- constructor -----------------------//
//---------------------- constructor -----------------------//
RpCards::RpCards(FgInformer *informer, FgConnect *connect)
: SmartArray(STEP),
_frozen (FALSE),
_informer (informer),
_connect (connect)
{
assert(_informer);
assert(_connect);
_sort = new FastSort (this, get_pattern_number);
_nchan = new AccNchan (this, _connect);
_search = new AccSearch (this, get_pattern_number);
}
//------------------------ destructor --------------------------//
//------------------------ destructor --------------------------//
//------------------------ destructor --------------------------//
RpCards::~RpCards()
{
deleteAllRpCards();
delete _sort;
delete _nchan;
delete _search;
}
//------------- before and after new active index -----------------//
//------------- before and after new active index -----------------//
//------------- before and after new active index -----------------//
// private virtual functions overriding SmartArray.
// Called from SmartArray before and after changing
// the active index.
// The function in SmartArray is empty.
void RpCards::beforeNewActiveIndex()
{
_informer->preNewActiveRpCard();
}
void RpCards::afterNewActiveIndex()
{
_informer->postNewActiveRpCard();
}
//------------------- before remove insert --------------------------//
//------------------- before remove insert --------------------------//
//------------------- before remove insert --------------------------//
// private virtual function overriding SmartArray.
// Called from SmartArray before removing and/or inserting
// one or more array elements.
// The function in SmartArray is empty.
void RpCards::beforeRemoveInsert(long index, long nrem, long nins)
{
_informer->preRemoveInsertRpCards (index, nrem, nins);
valuesWillChange (RP_PAT , index, nrem, nins);
valuesWillChange (RP_FLAG , index, nrem, nins);
valuesWillChange (RP_SHOT , index, nrem, nins);
valuesWillChange (RP_LINE , index, nrem, nins);
valuesWillChange (RP_NX , index, nrem, nins);
valuesWillChange (RP_XINC , index, nrem, nins);
valuesWillChange (RP_NY , index, nrem, nins);
valuesWillChange (RP_YINC , index, nrem, nins);
valuesWillChange (RP_XSKID, index, nrem, nins);
valuesWillChange (RP_YSKID, index, nrem, nins);
valuesWillChange (RP_ESKID, index, nrem, nins);
_nchan ->preChange (index, nrem, nins);
_search ->preChange (index, nrem, nins);
}
//------------------- after remove insert --------------------------//
//------------------- after remove insert --------------------------//
//------------------- after remove insert --------------------------//
// private virtual function overriding SmartArray.
// Called from SmartArray after removing and/or inserting
// one or more array elements.
// The function in SmartArray is empty.
void RpCards::afterRemoveInsert(long index, long nrem, long nins)
{
valuesHaveChanged (RP_PAT , index, nrem, nins);
valuesHaveChanged (RP_FLAG , index, nrem, nins);
valuesHaveChanged (RP_SHOT , index, nrem, nins);
valuesHaveChanged (RP_LINE , index, nrem, nins);
valuesHaveChanged (RP_NX , index, nrem, nins);
valuesHaveChanged (RP_XINC , index, nrem, nins);
valuesHaveChanged (RP_NY , index, nrem, nins);
valuesHaveChanged (RP_YINC , index, nrem, nins);
valuesHaveChanged (RP_XSKID, index, nrem, nins);
valuesHaveChanged (RP_YSKID, index, nrem, nins);
valuesHaveChanged (RP_ESKID, index, nrem, nins);
_nchan ->post1Change ();
_search ->post1Change ();
_nchan ->post2Change ();
_search ->post2Change ();
_informer->postRemoveInsertRpCards (index, nrem, nins);
_connect ->receiverPatternsHaveChanged();
}
//-------------------- before values changed ---------------------//
//-------------------- before values changed ---------------------//
//-------------------- before values changed ---------------------//
// private convenience function.
// Called by a public function before that function changes
// a value.
void RpCards::beforeValuesChanged(int ident, long index, long nchange)
{
valuesWillChange (ident, index, nchange, nchange);
if(ident == RP_PAT || ident == RP_FLAG || ident == RP_NX ||
ident == RP_NY)
{
_nchan->preChange (index, nchange, nchange);
}
if(ident == RP_PAT)
{
_search->preChange (index, nchange, nchange);
}
/***********
switch(ident) // alternative code
{
case RP_PAT : _nchan ->preChange(index, nchange, nchange);
_search->preChange(index, nchange, nchange);
break;
case RP_FLAG :
case RP_NX :
case RP_NY : _nchan ->preChange(index, nchange, nchange);
break;
default : break;
}
***********/
}
//-------------------- after values changed ---------------------//
//-------------------- after values changed ---------------------//
//-------------------- after values changed ---------------------//
// private convenience function.
// Called by a public function after that function changes
// a value.
void RpCards::afterValuesChanged(int ident, long index, long nchange)
{
if(ident == RP_PAT || ident == RP_FLAG || ident == RP_NX ||
ident == RP_NY)
{
_nchan->post1Change();
}
if(ident == RP_PAT)
{
_search->post1Change();
}
valuesHaveChanged (ident, index, nchange, nchange);
if(ident == RP_PAT || ident == RP_FLAG || ident == RP_NX ||
ident == RP_NY)
{
_nchan->post2Change();
}
if(ident == RP_PAT)
{
_search->post2Change();
}
_connect ->receiverPatternsHaveChanged();
}
//--------------- values will change (or have changed) -------------//
//--------------- values will change (or have changed) -------------//
//--------------- values will change (or have changed) -------------//
// virtual functions overriding SmartArray.
// called by AccBase objects and by functions in this class.
void RpCards::valuesWillChange
(int ident, long index, long nrem, long nins)
{
_informer->preRpValuesChanged (ident, index, nrem, nins);
}
void RpCards::valuesHaveChanged
(int ident, long index, long nrem, long nins)
{
_informer->postRpValuesChanged (ident, index, nrem, nins);
}
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
//------------ public access to these RP cards --------------//
// index = index of desired RP card.
void RpCards::freezeDependentUpdates()
{
if(_frozen) return;
_frozen = TRUE;
_nchan ->freezeUpdates();
_search ->freezeUpdates();
}
void RpCards::resumeDependentUpdates()
{
if(!_frozen) return;
_frozen = FALSE;
_nchan ->resumeUpdates();
_search ->resumeUpdates();
}
void RpCards::performDependentUpdates()
{
if(!_frozen) return;
_frozen = FALSE;
_nchan ->performUpdates();
_search ->performUpdates();
}
//--------------- do create and delete object --------------------//
//--------------- do create and delete object --------------------//
//--------------- do create and delete object --------------------//
// private virtual functions overriding SmartArray
void *RpCards::doCreateObject()
{
return new RpCard();
}
void RpCards::doDeleteObject(void *object)
{
delete (RpCard*)object;
}
//----------------------- insert or remove cards --------------------//
//----------------------- insert or remove cards --------------------//
//----------------------- insert or remove cards --------------------//
// the non-void functions return index where action occurred.
// the non-void functions return -1 if failed.
long RpCards::appendNewRpCard()
{
return appendNullElement();
}
long RpCards::placeNewRpCard(long pattern) // search
{
long index = _search->findInsertionLocation((double)pattern);
index = insertNewRpCard(index);
if(index >= 0) setRpPatternNumber(index, pattern);
return index;
}
long RpCards::insertNewRpCard(long index)
{
return insertNullElement(index);
}
long RpCards::insertNewRpCardFromBuffer(long index)
{
return insertElementFromBuffer(index);
}
long RpCards::deleteRpCard(long index)
{
return removeElement(index);
}
long RpCards::deleteRpCardToBuffer(long index)
{
return removeElementToBuffer(index);
}
void RpCards::deleteAllRpCards()
{
removeAllElements();
}
//--------------------- find receiver pattern ----------------------//
//--------------------- find receiver pattern ----------------------//
//--------------------- find receiver pattern ----------------------//
// these return an index, or -1 if not found.
// returns index of first card with matching receiver pattern.
long RpCards::findReceiverPattern (long pattern) const
{
return _search->findMatchingValue((float)pattern);
}
long RpCards::findEndOfReceiverPattern (long pattern) const
{
long ixrp = findReceiverPattern(pattern);
return getEndOfReceiverPattern(ixrp);
}
long RpCards::findRpCardWithDesiredChannel (long pattern, long channel) const
{
long ixrp = findReceiverPattern(pattern);
return getRpCardWithDesiredChannel(ixrp, channel);
}
// ixrp MUST be the FIRST card in the pattern:
long RpCards::getEndOfReceiverPattern (long ixrp) const
{
long n = numElements();
if(ixrp < 0 || ixrp >= n) return -1;
long pattern = rpCard(ixrp)->getRpPatternNumber();
if(ixrp > 0)
{
long pattern2 = rpCard(ixrp-1)->getRpPatternNumber();
assert(pattern2 != pattern);
}
while(ixrp < n-1 && rpCard(ixrp+1)->getRpPatternNumber() == pattern)
{
ixrp++;
}
return ixrp;
}
// ixrp MUST be the FIRST card in the pattern:
long RpCards::getRpCardWithDesiredChannel (long ixrp, long channel) const
{
if(channel <= 0) return -1;
long n = numElements();
if(ixrp < 0 || ixrp >= n) return -1;
long pattern = rpCard(ixrp)->getRpPatternNumber();
if(ixrp > 0)
{
long pattern2 = rpCard(ixrp-1)->getRpPatternNumber();
assert(pattern2 != pattern);
}
while(ixrp < n && rpCard(ixrp)->getRpPatternNumber() == pattern)
{
long cumchannel = rpCard(ixrp)->getRpCumChannels();
if(cumchannel >= channel) return ixrp;
ixrp++;
}
return -1;
}
// given first and last card of a pattern,
// returns the card on which the specified channel
// is described.
long RpCards::getRpCardWithDesiredChannel
(long ixrp_first, long ixrp_last, long channel) const
{
for(long ixrp = ixrp_first; ixrp <= ixrp_last; ixrp++)
{
long cumchannel = rpCard(ixrp)->getRpCumChannels();
if(cumchannel >= channel) return ixrp;
}
return -1;
}
// given first and last card of a pattern,
// returns first and last card corresponding to "irregular"
// cards (i.e. those with SKIP or DUP flags), or -1 if there
// are no "irregular" cards:
void RpCards::getRpIrregularRange(long ixrp_first, long ixrp_last,
long *ixrp_first_irreg, long *ixrp_last_irreg) const
{
*ixrp_first_irreg = -1;
*ixrp_last_irreg = -1;
for(long ixrp = ixrp_first; ixrp <= ixrp_last; ixrp++)
{
int rpflag = rpCard(ixrp)->getRpFlag();
if(rpflag != RP_FLAG_SKIP && rpflag != RP_FLAG_DUP) continue;
if(*ixrp_first_irreg == -1) *ixrp_first_irreg = ixrp;
*ixrp_last_irreg = ixrp;
}
}
//------------------- num channels in pattern ---------------------//
//------------------- num channels in pattern ---------------------//
//------------------- num channels in pattern ---------------------//
// public.
// given desired receiver pattern, returns the number of
// channels (from all cards) of the receiver pattern.
// returns 0 if receiver pattern is not found.
long RpCards::numChannelsInPattern(long pattern) const
{
long ixrp = findReceiverPattern(pattern);
if(ixrp >= 0) return getRpNumChannels(ixrp);
return 0;
}
//-------------------- receiver patterns are sorted ---------------//
//-------------------- receiver patterns are sorted ---------------//
//-------------------- receiver patterns are sorted ---------------//
int RpCards::receiverPatternsAreSorted() const
{
if(numElements() >= 2) return _search->isAscending();
return _search->isSorted();
}
//------------------- sort receiver patterns ------------------------//
//------------------- sort receiver patterns ------------------------//
//------------------- sort receiver patterns ------------------------//
void RpCards::sortReceiverPatterns()
{
long n = numElements();
if(n <= 1) return;
_informer->preSortReceiverPatterns();
beforeRemoveInsert(0, n, n);
/*
_sort->sort(RP_PAT, 1); // 1 = desired direction
_sort->sort(get_pattern_number, 1); // 1 = desired direction
*/
_sort->sort(1); // 1 = desired direction
afterRemoveInsert(0, n, n);
_informer->postSortReceiverPatterns();
}
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
//----------- pass-thru functions to individual RP cards --------------//
// index = index of desired RP card.
//---------------------- get card values ---------------------------//
//---------------------- get card values ---------------------------//
//---------------------- get card values ---------------------------//
class RpCard *RpCards::getRpCardPointer(long ixrp) const
{
return rpCard(ixrp);
}
#define GETV(getXxxx, long2) \
long2 RpCards::getXxxx(long index) const \
{ \
assert(index >= 0 && index < numElements()); \
RpCard *card = rpCard(index); \
return card->getXxxx(); \
}
GETV(getRpPatternNumber, long )
GETV(getRpNumChannels , long )
GETV(getRpCumChannels , long )
GETV(getRpFlag , int )
GETV(getRpShotpoint , float)
GETV(getRpLineNumber , long )
GETV(getRpNumX , long )
GETV(getRpXinc , long )
GETV(getRpNumY , long )
GETV(getRpYinc , long )
GETV(getRpXskid , float)
GETV(getRpYskid , float)
GETV(getRpEskid , float)
/*
GETV(getRpLineIndex , long )
GETV(getRpFlagIndex , long )
*/
void RpCards::getRpChannelsOnCard(long index,
long *first_channel, long *last_channel) const
{
assert(index >= 0 && index < numElements());
RpCard *card = rpCard(index);
card->getRpChannelsOnCard(first_channel, last_channel);
}
void RpCards::getRpIncrements(long index, long channel,
long *xinc, long *yinc,
long *incrx, long *incry) const
{
assert(index >= 0 && index < numElements());
RpCard *card = rpCard(index);
card->getRpIncrements(channel, xinc, yinc, incrx, incry);
}
//------------------------ set card values -------------------------//
//------------------------ set card values -------------------------//
//------------------------ set card values -------------------------//
// the following function sets all consecutive matching pattern
// numbers, beginning at the specified index, to the new value.
void RpCards::setRpPatternNumber(long index, long value)
{
long n = numElements();
assert(index >= 0 && index < n);
RpCard *card = rpCard(index);
long old_pattern = card->getRpPatternNumber();
long ixrp;
long test_pattern = old_pattern;
long nchange = 0;
for(ixrp = index; ixrp < n && test_pattern == old_pattern; ixrp++)
{
nchange++;
if(ixrp+1 < n)
{
RpCard *card = rpCard(index);
test_pattern = card->getRpPatternNumber();
}
}
beforeValuesChanged(RP_PAT, index, nchange);
for(ixrp = index; ixrp < index + nchange; ixrp++)
{
RpCard *card = rpCard(index);
card->setRpPatternNumber(value);
}
afterValuesChanged(RP_PAT, index, nchange);
}
#define SETV(setXxxx, long2, ident) \
void RpCards::setXxxx(long index, long2 value) \
{ \
assert(index >= 0 && index < numElements()); \
RpCard *card = rpCard(index); \
beforeValuesChanged(ident, index, 1); \
card->setXxxx(value); \
afterValuesChanged(ident, index, 1); \
}
SETV(setRpFlag , int , RP_FLAG )
SETV(setRpShotpoint , float, RP_SHOT )
SETV(setRpLineNumber , long , RP_LINE )
SETV(setRpNumX , long , RP_NX )
SETV(setRpXinc , long , RP_XINC )
SETV(setRpNumY , long , RP_NY )
SETV(setRpYinc , long , RP_YINC )
SETV(setRpXskid , float, RP_XSKID)
SETV(setRpYskid , float, RP_YSKID)
SETV(setRpEskid , float, RP_ESKID)
//-------------------------- end -------------------------------//
//-------------------------- end -------------------------------//
//-------------------------- end -------------------------------//
| 0 | 0.962075 | 1 | 0.962075 | game-dev | MEDIA | 0.867268 | game-dev | 0.795333 | 1 | 0.795333 |
Ravesli/OpenGL | 1,129 | Часть №11. Добавление аудио в игру «Breakout» на C++ и OpenGL/Hello_Window/game_object.h | /*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include "texture.h"
#include "sprite_renderer.h"
// Контейнерный объект, хранящий все состояния, относящиеся к отдельно взятой игровой сущности
class GameObject
{
public:
// Состояние объекта
glm::vec2 Position, Size, Velocity;
glm::vec3 Color;
float Rotation;
bool IsSolid;
bool Destroyed;
// Состояние рендера
Texture2D Sprite;
// Конструкторы
GameObject();
GameObject(glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color = glm::vec3(1.0f), glm::vec2 velocity = glm::vec2(0.0f, 0.0f));
// Отрисовка спрайта
virtual void Draw(SpriteRenderer& renderer);
};
#endif
| 0 | 0.767794 | 1 | 0.767794 | game-dev | MEDIA | 0.811331 | game-dev,graphics-rendering | 0.689294 | 1 | 0.689294 |
randomguy3725/MoonLight | 2,466 | src/main/java/net/minecraft/block/BlockStainedGlassPane.java | package net.minecraft.block;
import java.util.List;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.World;
public class BlockStainedGlassPane extends BlockPane
{
public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.create("color", EnumDyeColor.class);
public BlockStainedGlassPane()
{
super(Material.glass, false);
this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, Boolean.FALSE).withProperty(EAST, Boolean.FALSE).withProperty(SOUTH, Boolean.FALSE).withProperty(WEST, Boolean.FALSE).withProperty(COLOR, EnumDyeColor.WHITE));
this.setCreativeTab(CreativeTabs.tabDecorations);
}
public int damageDropped(IBlockState state)
{
return state.getValue(COLOR).getMetadata();
}
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list)
{
for (int i = 0; i < EnumDyeColor.values().length; ++i)
{
list.add(new ItemStack(itemIn, 1, i));
}
}
public MapColor getMapColor(IBlockState state)
{
return state.getValue(COLOR).getMapColor();
}
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.TRANSLUCENT;
}
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(meta));
}
public int getMetaFromState(IBlockState state)
{
return state.getValue(COLOR).getMetadata();
}
protected BlockState createBlockState()
{
return new BlockState(this, NORTH, EAST, WEST, SOUTH, COLOR);
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
BlockBeacon.updateColorAsync(worldIn, pos);
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
BlockBeacon.updateColorAsync(worldIn, pos);
}
}
}
| 0 | 0.56083 | 1 | 0.56083 | game-dev | MEDIA | 0.996685 | game-dev | 0.833582 | 1 | 0.833582 |
Monkestation/Monkestation2.0 | 2,258 | code/modules/unit_tests/suit_storage_icons.dm | /// Makes sure suit slot items aren't using CS:S fallbacks.
/datum/unit_test/suit_storage_icons
/datum/unit_test/suit_storage_icons/Run()
var/list/wearable_item_paths = list()
for(var/obj/item/item_path as anything in subtypesof(/obj/item))
var/cached_slot_flags = initial(item_path.slot_flags)
if(!(cached_slot_flags & ITEM_SLOT_SUITSTORE) || (initial(item_path.item_flags) & ABSTRACT))
continue
wearable_item_paths |= item_path
for(var/obj/item/clothing/clothing_path in (subtypesof(/obj/item/clothing) - typesof(/obj/item/clothing/head/mob_holder) - typesof(/obj/item/clothing/suit/space/santa))) //mob_holder is a psuedo abstract item. santa suit is a VERY SNOWFLAKE admin spawn suit that can hold /every/ possible item.
for(var/path in clothing_path::allowed) //find all usable suit storage stuff.
wearable_item_paths |= path
for(var/obj/item/mod/control/mod_path in subtypesof(/obj/item/mod/control))
for(var/path in mod_path::chestplate::allowed)
wearable_item_paths |= path
var/list/already_warned_icons = list()
var/count = 1 //to be removed once the test goes live / into CI failure mode.
for(var/obj/item/item_path as anything in typecacheof(wearable_item_paths))
if(initial(item_path.item_flags) & ABSTRACT)
continue
var/worn_icon = initial(item_path.worn_icon) //override icon file. where our sprite is contained if set. (ie modularity stuff)
var/worn_icon_state = initial(item_path.worn_icon_state) //overrides icon_state.
var/icon_state = worn_icon_state || initial(item_path.icon_state) //icon_state. what sprite name we are looking for.
if(isnull(icon_state))
continue //no sprite for the item.
if(icon_state in already_warned_icons)
continue
if(worn_icon) //easiest to check since we override everything.
if(!icon_exists(worn_icon, icon_state))
log_test("\t[count] - [item_path] using invalid [worn_icon_state ? "worn_icon_state" : "icon_state"], \"[icon_state]\" in worn_icon override file, '[worn_icon]'")
count++
continue
if(!icon_exists('icons/mob/clothing/belt_mirror.dmi', icon_state))
already_warned_icons += icon_state
log_test("\t[count] - [item_path] using invalid [worn_icon_state ? "worn_icon_state" : "icon_state"], \"[icon_state]\"")
count++
| 0 | 0.914478 | 1 | 0.914478 | game-dev | MEDIA | 0.893107 | game-dev | 0.920759 | 1 | 0.920759 |
MATTYOneInc/AionEncomBase_Java8 | 3,690 | AL-Game/data/scripts/system/handlers/quest/beluslan/_2513TheStrangeCottage.java | /*
* This file is part of aion-unique <aion-unique.org>.
*
* aion-unique is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* aion-unique is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aion-unique. If not, see <http://www.gnu.org/licenses/>.
*/
package quest.beluslan;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestDialog;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
/**
* @author Ritsu
*
*/
public class _2513TheStrangeCottage extends QuestHandler {
private final static int questId = 2513;
public _2513TheStrangeCottage() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(204732).addOnQuestStart(questId); //Gnalin
qe.registerQuestNpc(204732).addOnTalkEvent(questId);
qe.registerQuestNpc(204827).addOnTalkEvent(questId); //Hild
qe.registerQuestNpc(204826).addOnTalkEvent(questId); //Freki
qe.registerQuestNpc(790022).addOnTalkEvent(questId); //Byggvir
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc)
targetId = ((Npc) env.getVisibleObject()).getNpcId();
QuestState qs = player.getQuestStateList().getQuestState(questId);
QuestDialog dialog = env.getDialog();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 204732) {
if (dialog == QuestDialog.START_DIALOG)
return sendQuestDialog(env, 4762);
else
return sendQuestStartDialog(env);
}
}
else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 204826){//Freki
switch (dialog) {
case START_DIALOG:
if (var == 0)
return sendQuestDialog(env, 1011);
case STEP_TO_1:
if (var == 0) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return closeDialogWindow(env);
}
}
}
if (targetId == 204827) {//Hild
switch (dialog){
case START_DIALOG:
if (var == 0) {
return sendQuestDialog(env, 1352);
}
case STEP_TO_2:
if (var == 0) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return closeDialogWindow(env);
}
}
}
if (targetId == 790022) {
switch (dialog){
case START_DIALOG:
if (var == 0) {
return sendQuestDialog(env, 1693);
}
case STEP_TO_3:
if (var == 0) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return closeDialogWindow(env);
}
}
}
}
else if (qs == null || qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 204732) {
switch (dialog){
case USE_OBJECT:
return sendQuestDialog(env, 10002);
case SELECT_REWARD:
return sendQuestDialog(env, 5);
default: return sendQuestEndDialog(env);
}
}
}
return false;
}
} | 0 | 0.891273 | 1 | 0.891273 | game-dev | MEDIA | 0.962782 | game-dev | 0.966 | 1 | 0.966 |
MergHQ/CRYENGINE | 1,879 | Code/CryEngine/CryAnimation/PoseModifier/PoseModifier.h | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#pragma once
#include <CryAnimation/ICryAnimation.h>
#include <CryExtension/ClassWeaver.h>
#include <CrySerialization/Forward.h>
struct IAnimationPoseData;
class CPoseModifierStack :
public IAnimationPoseModifier
{
public:
CRYINTERFACE_BEGIN()
CRYINTERFACE_ADD(IAnimationPoseModifier)
CRYINTERFACE_END()
CRYGENERATE_CLASS(CPoseModifierStack, "AnimationPoseModifier_PoseModifierStack", 0xaf9efa2dfec04de4, 0xa1663950bde6a3c6)
public:
void Clear() { m_modifiers.clear(); }
bool Push(IAnimationPoseModifierPtr instance);
// IAnimationPoseModifier
public:
virtual bool Prepare(const SAnimationPoseModifierParams& params) override;
virtual bool Execute(const SAnimationPoseModifierParams& params) override;
virtual void Synchronize() override;
void GetMemoryUsage(ICrySizer* pSizer) const override {}
private:
std::vector<IAnimationPoseModifierPtr> m_modifiers;
};
DECLARE_SHARED_POINTERS(CPoseModifierStack);
//
class CPoseModifierSetup :
public IAnimationSerializable
{
CRYINTERFACE_BEGIN()
CRYINTERFACE_ADD(IAnimationSerializable)
CRYINTERFACE_END()
CRYGENERATE_CLASS(CPoseModifierSetup, "PoseModifierSetup", 0x18b8cca76db947cc, 0x84dd1f003e97cbee)
private:
struct Entry
{
Entry() : enabled(true) {}
IAnimationPoseModifierPtr instance;
bool enabled;
void Serialize(Serialization::IArchive& ar);
};
public:
bool Create(CPoseModifierSetup& setup);
CPoseModifierStackPtr GetPoseModifierStack() { return m_pPoseModifierStack; }
private:
bool CreateStack();
// IAnimationSerializable
public:
virtual void Serialize(Serialization::IArchive& ar) override;
private:
std::vector<Entry> m_modifiers;
CPoseModifierStackPtr m_pPoseModifierStack;
};
DECLARE_SHARED_POINTERS(CPoseModifierSetup);
| 0 | 0.761267 | 1 | 0.761267 | game-dev | MEDIA | 0.693835 | game-dev | 0.598452 | 1 | 0.598452 |
Shopify/handy | 7,374 | Handy/Assets/Oculus/Interaction/Runtime/Scripts/Interaction/Grabbable/TwoGrabPlaneTransformer.cs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* Licensed under the Oculus SDK License Agreement (the "License");
* you may not use the Oculus SDK except in compliance with the License,
* which is provided at the time of installation or download, or which
* otherwise accompanies this software in either electronic or hard copy form.
*
* You may obtain a copy of the License at
*
* https://developer.oculus.com/licenses/oculussdk/
*
* Unless required by applicable law or agreed to in writing, the Oculus SDK
* 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.
*/
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.Serialization;
namespace Oculus.Interaction
{
/// <summary>
/// A Transformer that translates, rotates and scales the target on a plane.
/// </summary>
public class TwoGrabPlaneTransformer : MonoBehaviour, ITransformer
{
[SerializeField, Optional]
private Transform _planeTransform = null;
private Vector3 _capturePosition;
private Vector3 _initialLocalScale;
private float _initialDistance;
private float _initialScale = 1.0f;
private float _activeScale = 1.0f;
private Pose _previousGrabA;
private Pose _previousGrabB;
[Serializable]
public class TwoGrabPlaneConstraints
{
public FloatConstraint MinScale;
public FloatConstraint MaxScale;
public FloatConstraint MinY;
public FloatConstraint MaxY;
}
[SerializeField]
private TwoGrabPlaneConstraints _constraints;
public TwoGrabPlaneConstraints Constraints
{
get
{
return _constraints;
}
set
{
_constraints = value;
}
}
private IGrabbable _grabbable;
public void Initialize(IGrabbable grabbable)
{
_grabbable = grabbable;
}
public void BeginTransform()
{
var grabA = _grabbable.GrabPoints[0];
var grabB = _grabbable.GrabPoints[1];
var targetTransform = _grabbable.Transform;
// Use the centroid of our grabs as the capture plane point
_capturePosition = targetTransform.position;
Transform planeTransform = _planeTransform != null ? _planeTransform : targetTransform;
Vector3 rotationAxis = planeTransform.up;
// Project our positional offsets onto a plane with normal equal to the rotation axis
Vector3 initialOffset = grabB.position - grabA.position;
Vector3 initialVector = Vector3.ProjectOnPlane(initialOffset, rotationAxis);
_initialDistance = initialVector.magnitude;
_initialScale = _activeScale = targetTransform.localScale.x;
_previousGrabA = grabA;
_previousGrabB = grabB;
}
public void UpdateTransform()
{
var grabA = _grabbable.GrabPoints[0];
var grabB = _grabbable.GrabPoints[1];
var targetTransform = _grabbable.Transform;
// Use the centroid of our grabs as the transformation center
Vector3 initialCenter = Vector3.Lerp(_previousGrabA.position, _previousGrabB.position, 0.5f);
Vector3 targetCenter = Vector3.Lerp(grabA.position, grabB.position, 0.5f);
Transform planeTransform = _planeTransform != null ? _planeTransform : targetTransform;
Vector3 rotationAxis = planeTransform.up;
// Project our positional offsets onto a plane with normal equal to the rotation axis
Vector3 initialOffset = _previousGrabB.position - _previousGrabA.position;
Vector3 initialVector = Vector3.ProjectOnPlane(initialOffset, rotationAxis);
Vector3 targetOffset = grabB.position - grabA.position;
Vector3 targetVector = Vector3.ProjectOnPlane(targetOffset, rotationAxis);
Quaternion rotationDelta = new Quaternion();
rotationDelta.SetFromToRotation(initialVector, targetVector);
Quaternion initialRotation = targetTransform.rotation;
Quaternion targetRotation = rotationDelta * targetTransform.rotation;
// Scale logic
float activeDistance = targetVector.magnitude;
if(Mathf.Abs(activeDistance) < 0.0001f) activeDistance = 0.0001f;
float scalePercentage = activeDistance / _initialDistance;
float previousScale = _activeScale;
_activeScale = _initialScale * scalePercentage;
// Scale constraints
if(_constraints.MinScale.Constrain)
{
_activeScale = Mathf.Max(_constraints.MinScale.Value, _activeScale);
}
if(_constraints.MaxScale.Constrain)
{
_activeScale = Mathf.Min(_constraints.MaxScale.Value, _activeScale);
}
// Apply the positional delta initialCenter -> targetCenter and the
// rotational delta to the target transform
Vector3 positionDelta = _capturePosition - initialCenter;
Vector3 deltaProjectedOnPlaneNormal = Vector3.Dot((positionDelta - initialCenter), rotationAxis) * rotationAxis;
positionDelta -= deltaProjectedOnPlaneNormal;
Vector3 planarDelta = Quaternion.Inverse(initialRotation) * positionDelta;
Vector3 normalDelta = Quaternion.Inverse(initialRotation) * deltaProjectedOnPlaneNormal;
Vector3 totalDelta = planarDelta + normalDelta;
Vector3 centerDelta = targetCenter - _capturePosition;
Vector3 scaleCenterDelta = centerDelta * _activeScale / previousScale;
Vector3 targetDelta = scaleCenterDelta - centerDelta;
Quaternion rotationInTargetSpace = Quaternion.Inverse(initialRotation) * targetTransform.rotation;
_capturePosition = targetRotation * totalDelta + targetCenter - targetDelta;
targetTransform.rotation = targetRotation * rotationInTargetSpace;
targetTransform.localScale = _activeScale * Vector3.one;
Vector3 targetPosition = _capturePosition;
// Y axis constraints
if(_constraints.MinY.Constrain)
{
targetPosition.y = Mathf.Max(_constraints.MinY.Value, targetPosition.y);
}
if(_constraints.MaxY.Constrain)
{
targetPosition.y = Mathf.Min(_constraints.MaxY.Value, targetPosition.y);
}
targetTransform.position = targetPosition;
_previousGrabA = grabA;
_previousGrabB = grabB;
}
public void EndTransform() { }
#region Inject
public void InjectOptionalPlaneTransform(Transform planeTransform)
{
_planeTransform = planeTransform;
}
public void InjectOptionalConstraints(TwoGrabPlaneConstraints constraints)
{
_constraints = constraints;
}
#endregion
}
}
| 0 | 0.905112 | 1 | 0.905112 | game-dev | MEDIA | 0.579725 | game-dev,graphics-rendering | 0.984277 | 1 | 0.984277 |
mkw-sp/mkw-sp | 8,097 | payload/game/ui/page/RaceMenuPage.cc | #include "RaceMenuPage.hh"
#include "game/sound/util/BackgroundMusicManager.hh"
#include "game/system/RaceConfig.hh"
#include "game/system/SaveManager.hh"
#include "game/ui/SectionManager.hh"
#include "game/ui/SettingsPage.hh"
#include <sp/CourseDatabase.hh>
#include <sp/SaveStateManager.hh>
#include <sp/settings/ClientSettings.hh>
extern "C" {
#include <vendor/libhydrogen/hydrogen.h>
}
namespace UI {
void RaceMenuPage::onButtonFront(PushButton *button, u32 localPlayerId) {
auto &raceScenario = System::RaceConfig::Instance()->raceScenario();
auto &menuScenario = System::RaceConfig::Instance()->menuScenario();
auto buttonId = static_cast<ButtonId>(button->m_index);
switch (buttonId) {
case ButtonId::Restart1:
case ButtonId::Restart3:
case ButtonId::BattleGhost:
if (raceScenario.gameMode == System::RaceConfig::GameMode::TimeAttack) {
System::RaceConfig::Instance()->applyEngineClass();
}
REPLACED(onButtonFront)(button, localPlayerId);
return;
case ButtonId::Next:
if (menuScenario.mirrorRng) {
menuScenario.mirror = hydro_random_uniform(20) >= 17;
}
if (raceScenario.gameMode == System::RaceConfig::GameMode::OfflineVS ||
raceScenario.gameMode == System::RaceConfig::GameMode::OfflineBT) {
onNextButtonFront(button, localPlayerId);
break;
} else {
REPLACED(onButtonFront)(button, localPlayerId);
return;
}
case ButtonId::Settings:
onSettingsButtonFront(button, localPlayerId);
break;
case ButtonId::ChangeGhostData:
onChangeGhostDataButtonFront(button, localPlayerId);
break;
case ButtonId::SaveState:
if (auto *saveStateManager = SP::SaveStateManager::Instance()) {
saveStateManager->save();
}
break;
case ButtonId::LoadState:
if (auto *saveStateManager = SP::SaveStateManager::Instance()) {
saveStateManager->reload();
}
break;
default:
REPLACED(onButtonFront)(button, localPlayerId);
return;
}
}
void RaceMenuPage::onNextButtonFront(PushButton *button, u32 /* localPlayerId */) {
auto *raceConfig = System::RaceConfig::Instance();
auto &menuScenario = raceConfig->menuScenario();
raceConfig->endRace();
button->setFrontSoundId(Sound::SoundId::SE_RC_PAUSE_EXIT_GAME);
SectionId sectionId;
if (IsLastMatch()) {
bool isWin = false;
for (u32 playerId = 0; playerId < menuScenario.localPlayerCount; playerId++) {
u32 threshold = menuScenario.spMaxTeamSize * (1 + menuScenario.draw);
if (threshold == 1) {
threshold = 3;
}
if (menuScenario.players[playerId].rank <= threshold) {
isWin = true;
}
}
if (menuScenario.spMaxTeamSize >= 2 && menuScenario.draw) {
if (!isWin) {
menuScenario.draw = 0;
}
isWin = false;
}
if (menuScenario.isBattle()) {
sectionId = SectionId::AwardsBT;
} else {
sectionId = SectionId::AwardsVS;
}
menuScenario.cameraMode = isWin ? 8 : 12;
menuScenario.courseId = isWin ? Registry::Course::WinDemo : Registry::Course::LoseDemo;
menuScenario.gameMode = System::RaceConfig::GameMode::Awards;
} else {
menuScenario.cameraMode = 5;
auto *globalContext = UI::SectionManager::Instance()->globalContext();
auto nextCourse = globalContext->getCourse(globalContext->m_match);
if (nextCourse.has_value()) {
menuScenario.courseId = *nextCourse;
if (menuScenario.isBattle()) {
sectionId = SectionId::BTDemo;
} else {
sectionId = SectionId::VSDemo;
}
} else {
if (menuScenario.isBattle()) {
sectionId = SectionId::SingleSelectBTCourse;
} else {
sectionId = SectionId::SingleSelectVSCourse;
}
}
}
f32 delay = button->getDelay();
changeSection(sectionId, Anim::Next, delay);
Sound::BackgroundMusicManager::Instance()->prepare(Section::GetSoundId(sectionId), true);
}
void RaceMenuPage::onSettingsButtonFront(PushButton *button, u32 /* localPlayerId */) {
auto *section = SectionManager::Instance()->currentSection();
auto *menuSettingsPage = section->page<PageId::MenuSettings>();
menuSettingsPage->configure(nullptr, id());
setReplacement(PageId::MenuSettings);
f32 delay = button->getDelay();
startReplace(Anim::Next, delay);
}
void RaceMenuPage::onChangeGhostDataButtonFront(PushButton *button, u32 /* localPlayerId */) {
button->setFrontSoundId(Sound::SoundId::SE_RC_PAUSE_EXIT_GAME);
auto &menuScenario = System::RaceConfig::Instance()->menuScenario();
menuScenario.cameraMode = 0;
for (u32 i = 1; i < 12; i++) {
menuScenario.players[i].type = System::RaceConfig::Player::Type::None;
}
f32 delay = button->getDelay();
changeSection(SectionId::SingleChangeGhostData, Anim::Next, delay);
}
bool RaceMenuPage::IsLastMatch() {
auto raceScenario = System::RaceConfig::Instance()->raceScenario();
if (raceScenario.isBattle()) {
auto *saveManager = System::SaveManager::Instance();
s32 maxRaceCount = saveManager->getSetting<SP::ClientSettings::Setting::BTRaceCount>();
return maxRaceCount <= (raceScenario.raceNumber + 1);
}
return REPLACED(IsLastMatch)();
}
} // namespace UI
extern "C" {
// Referenced by RaceMenuPage.S
const char *sButtonStrings[] = {
"ButtonContinue", // ButtonId::Continue1
"ButtonQuit", // ButtonId::Quit1
"ButtonRestart", // ButtonId::Restart1
"ButtonRestart", // ButtonId::Restart2
"ButtonReplay", // ButtonId::Replay
"ButtonChangeCourse", // ButtonId::ChangeCourse
"ButtonChangeCharacter", // ButtonId::ChangeCharacter
"ButtonNext", // ButtonId::Next
"ButtonRanking", // ButtonId::Ranking
"ButtonContinueReplay", // ButtonId::ContinueReplay
"ButtonRestartReplay", // ButtonId::RestartReplay
"ButtonQuitReplay", // ButtonId::QuitReplay
"ButtonContinue", // ButtonId::Continue2
"ButtonQuit", // ButtonId::Quit2
"ButtonBattleGhost", // ButtonId::BattleGhost
"ButtonRestart", // ButtonId::Restart3
"ButtonContinue", // ButtonId::Continue3
"ButtonQuit", // ButtonId::Quit3
"ButtonChangeMission", // ButtonId::ChangeMission
"ButtonSend", // ButtonId::Send1
"ButtonNoSend", // ButtonId::NoSend1
"ButtonGoRanking", // ButtonId::GoRanking
"ButtonNotGoRanking", // ButtonId::NotGoRanking
"ButtonConfirmContinue", // ButtonId::ConfirmContinue
"ButtonConfirmQuit", // ButtonId::ConfirmQuit
"ButtonSendRecord", // ButtonId::SendRecord
"ButtonSend", // ButtonId::Send2
"ButtonNoSend", // ButtonId::NoSend2
"ButtonFriendGhostBattle", // ButtonId::stBattle
"ButtonGoFriendRoom", // ButtonId::GoFriendRoom
"ButtonNotGoFriendRoom", // ButtonId::NotGoFriendRoom
"ButtonNextGhost", // ButtonId::NextGhost
"ButtonYes", // ButtonId::Yes1
"ButtonNo", // ButtonId::No1
"ButtonQuit", // ButtonId::Quit4
"ButtonYes", // ButtonId::Yes2
"ButtonNo", // ButtonId::No2
"ButtonSettings", // ButtonId::LicenseSettings
"ButtonChangeGhostData", // ButtonId::ChangeGhostData
"ButtonSaveState", // ButtonId::SaveState
"ButtonLoadState", // ButtonId::LoadState
};
}
| 0 | 0.946006 | 1 | 0.946006 | game-dev | MEDIA | 0.623544 | game-dev | 0.946575 | 1 | 0.946575 |
GregTech-Intergalactical/GregTech | 1,174 | common/src/main/java/muramasa/gregtech/blockentity/single/BlockEntityBridge.java | package muramasa.gregtech.blockentity.single;
import muramasa.antimatter.blockentity.BlockEntityMachine;
import muramasa.antimatter.blockentity.IExtendingBlockEntity;
import muramasa.antimatter.machine.types.Machine;
import muramasa.antimatter.util.Utils;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
public class BlockEntityBridge extends BlockEntityMachine<BlockEntityBridge> implements IExtendingBlockEntity {
public BlockEntityBridge(Machine<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
@Override
public BlockEntity getExtendedBlockEntity(Direction side) {
return getCachedBlockEntity(side);
}
@Override
public void onBlockUpdate(BlockPos neighbor) {
super.onBlockUpdate(neighbor);
Direction facing = Utils.getOffsetFacing(this.getBlockPos(), neighbor);
BlockPos offset = getBlockPos().relative(facing.getOpposite());
getLevel().neighborChanged(offset, getLevel().getBlockState(offset).getBlock(), getBlockPos());
}
}
| 0 | 0.881874 | 1 | 0.881874 | game-dev | MEDIA | 0.981997 | game-dev | 0.815782 | 1 | 0.815782 |
RuneStar/cs2-scripts | 2,167 | scripts/[clientscript,makeover_clothes_setup].cs2 | // 230
[clientscript,makeover_clothes_setup](component $component0, component $component1, component $component2, component $component3, component $component4)
cc_deleteall($component1);
cc_deleteall($component2);
cc_deleteall($component3);
cc_deleteall($component4);
def_enum $enum5 = enum_789;
def_enum $enum6 = enum_790;
if (%varbit3945 = 1) {
if_sethide(true, $component0);
if_sethide(false, $component3);
$enum5 = enum_791;
$enum6 = enum_792;
if (%varbit3944 = 1) {
~makeover_drawmodels($component3, enum_787, enum_788, null, null, 800, 60, 0, 1, 1);
} else {
~makeover_drawmodels($component3, enum_778, enum_779, null, null, 720, 60, 0, 1, 1);
}
} else {
if_sethide(false, $component0);
if_sethide(true, $component3);
if (%varbit3944 = 1) {
~makeover_drawmodels($component1, enum_781, enum_782, null, female_arms_332, 600, 135, 0, 1, 0);
~makeover_drawmodels($component2, enum_784, enum_785, null, female_torso_456, 650, 135, 0, 2, 0);
} else {
~makeover_drawmodels($component1, enum_771, enum_772, enum_773, male_arms_151, 780, 135, 0, 1, 1);
~makeover_drawmodels($component2, enum_775, enum_776, null, male_torso_292, 780, 135, 0, 2, 1);
}
}
def_int $int7 = 0;
while ($int7 < 29) {
cc_create($component4, ^iftype_rectangle, $int7);
cc_setsize(25, 25, ^setsize_abs, ^setsize_abs);
if ($int7 < 15) {
cc_setposition(calc($int7 * 25), 0, ^setpos_abs_left, ^setpos_abs_top);
} else {
cc_setposition(calc(($int7 - 15) * 25 + 12), 26, ^setpos_abs_left, ^setpos_abs_top);
}
cc_setfill(true);
cc_setcolour(enum(int, int, $enum5, $int7));
cc_setop(1, enum(int, string, $enum6, $int7));
$int7 = calc($int7 + 1);
}
$int7 = 0;
while ($int7 < 29) {
cc_create($component4, ^iftype_graphic, calc($int7 + 29));
cc_setsize(25, 25, ^setsize_abs, ^setsize_abs);
if ($int7 < 15) {
cc_setposition(calc($int7 * 25), 0, ^setpos_abs_left, ^setpos_abs_top);
} else {
cc_setposition(calc(($int7 - 15) * 25 + 12), 26, ^setpos_abs_left, ^setpos_abs_top);
}
cc_setgraphic("overlay_multiway");
~makeover_indicator($int7, 3);
cc_setonvartransmit("makeover_indicator(event_com, event_comsubid, $int7, 3){var263}");
$int7 = calc($int7 + 1);
}
| 0 | 0.831593 | 1 | 0.831593 | game-dev | MEDIA | 0.755426 | game-dev | 0.942058 | 1 | 0.942058 |
PrismLibrary/Prism | 4,083 | src/Maui/Prism.Maui/Navigation/Regions/RegionCollection.cs | using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using Prism.Properties;
namespace Prism.Navigation.Regions;
internal class RegionCollection : IRegionCollection
{
private readonly IRegionManager regionManager;
private readonly List<IRegion> _regions;
public RegionCollection(IRegionManager regionManager)
{
this.regionManager = regionManager;
_regions = new List<IRegion>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public IEnumerator<IRegion> GetEnumerator()
{
Xaml.RegionManager.UpdateRegions();
return _regions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
public IRegion this[string regionName]
{
get
{
Xaml.RegionManager.UpdateRegions();
IRegion region = GetRegionByName(regionName);
if (region == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.CurrentUICulture, Resources.RegionNotInRegionManagerException, regionName));
}
return region;
}
}
public void Add(IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Xaml.RegionManager.UpdateRegions();
if (region.Name == null)
{
throw new InvalidOperationException(Resources.RegionNameCannotBeEmptyException);
}
if (GetRegionByName(region.Name) != null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.RegionNameExistsException, region.Name));
}
_regions.Add(region);
region.RegionManager = regionManager;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, region, 0));
}
public bool Remove(string regionName)
{
Xaml.RegionManager.UpdateRegions();
bool removed = false;
IRegion region = GetRegionByName(regionName);
if (region != null)
{
removed = true;
_regions.Remove(region);
region.RegionManager = null;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, region, 0));
}
return removed;
}
public bool ContainsRegionWithName(string regionName)
{
Xaml.RegionManager.UpdateRegions();
return GetRegionByName(regionName) != null;
}
/// <summary>
/// Adds a region to the <see cref="RegionManager"/> with the name received as argument.
/// </summary>
/// <param name="regionName">The name to be given to the region.</param>
/// <param name="region">The region to be added to the <see cref="RegionManager"/>.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="region"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="regionName"/> and <paramref name="region"/>'s name do not match and the <paramref name="region"/> <see cref="IRegion.Name"/> is not <see langword="null"/>.</exception>
public void Add(string regionName, IRegion region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
if (region.Name != null && region.Name != regionName)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.RegionManagerWithDifferentNameException, region.Name, regionName), nameof(regionName));
if (region.Name == null)
region.Name = regionName;
Add(region);
}
private IRegion GetRegionByName(string regionName) =>
_regions.FirstOrDefault(r => r.Name == regionName);
private void OnCollectionChanged(NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) =>
CollectionChanged?.Invoke(this, notifyCollectionChangedEventArgs);
}
| 0 | 0.681439 | 1 | 0.681439 | game-dev | MEDIA | 0.343039 | game-dev | 0.680713 | 1 | 0.680713 |
IppClub/Dora-SSR | 3,860 | Tools/dora-wa/src/test/contact.wa | /* Copyright (c) 2016-2025 Li Jin <dragon-fly@qq.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
import "dora"
import "strconv"
func TestContact() {
gravity := dora.NewVec2(0.0, -10.0)
world := dora.NewPhysicsWorld()
world.SetShouldContact(0, 0, true)
world.SetShowDebug(true)
label := dora.NewLabel("sarasa-mono-sc-regular", 30, false)
label.AddTo(world.Node)
terrain_def := dora.NewBodyDef()
count := 50
radius: f32 = 300.0
vertices := []dora.Vec2{}
for i := 0; i <= count; i++ {
angle := 2.0 * dora.Math.Pi * f32(i) / f32(count)
vertices = append(vertices, dora.NewVec2(radius*dora.Math.Cos(angle), radius*dora.Math.Sin(angle)))
}
terrain_def.AttachChain(&vertices, 0.4, 0.0)
terrain_def.AttachDiskWithCenter(dora.NewVec2(0.0, -270.0), 30.0, 1.0, 0.0, 1.0)
terrain := dora.NewBody(terrain_def, world, dora.NewVec2(0.0, 0.0), 0.0)
terrain.AddTo(world.Node)
platform_def := dora.NewBodyDef()
platform_def.AttachPolygonWithCenter(dora.NewVec2(0.0, -80.0), 120.0, 30.0, 0.0, 1.0, 0.0, 1.0)
platform := dora.NewBody(platform_def, world, dora.NewVec2(0.0, 0.0), 0.0)
platform.OnContactFilter(func(other: dora.Body) => bool {
return other.GetVelocityY() < 0.0
})
platform.AddTo(world.Node)
draw_node := dora.NewLineWithVecColor(&[]dora.Vec2{
dora.NewVec2(-20.0, 0.0),
dora.NewVec2(20.0, 0.0),
dora.Vec2Zero,
dora.NewVec2(0.0, -20.0),
dora.NewVec2(0.0, 20.0),
}, dora.App.GetThemeColor())
draw_node.AddTo(world.Node)
disk_def := dora.NewBodyDef()
disk_def.SetType(dora.BodyTypeDynamic)
disk_def.SetLinearAcceleration(gravity)
disk_def.AttachDisk(20.0, 5.0, 0.8, 1.0)
disk := dora.NewBody(disk_def, world, dora.NewVec2(100.0, 200.0), 0.0)
disk.AddTo(world.Node)
disk.SetAngularRate(-1800.0)
disk.OnContactStart(func(other: dora.Body, point: dora.Vec2, normal: dora.Vec2, enabled: bool) {
if enabled {
draw_node.SetPosition(point)
label.SetText("Contact: [" + strconv.FormatFloat(f64(point.X), 'f', 2, 32) + "," + strconv.FormatFloat(f64(point.Y), 'f', 2, 32) + "]")
}
})
window_flags := dora.ImGuiWindowFlags(
dora.ImGuiWindowNoDecoration,
dora.ImGuiWindowAlwaysAutoResize,
dora.ImGuiWindowNoSavedSettings,
dora.ImGuiWindowNoFocusOnAppearing,
dora.ImGuiWindowNoNav,
dora.ImGuiWindowNoMove,
)
imgui_node := dora.NewNode()
imgui_node.Schedule(func(delta_time: f64) => bool {
width := dora.App.GetVisualSize().Width
dora.ImGui.SetNextWindowBgAlpha(0.35)
dora.ImGui.SetNextWindowPosOpts(
dora.NewVec2(width-10.0, 10.0),
dora.ImGuiCondAlways,
dora.NewVec2(1.0, 0.0),
)
dora.ImGui.SetNextWindowSizeOpts(
dora.NewVec2(240.0, 0.0),
dora.ImGuiCondFirstUseEver,
)
dora.ImGui.BeginOpts("Contact", window_flags, func() {
dora.ImGui.Text("Contact (Wa)")
dora.ImGui.Separator()
dora.ImGui.TextWrapped("Receive events when physics bodies contact.")
})
return false
})
}
| 0 | 0.850242 | 1 | 0.850242 | game-dev | MEDIA | 0.474587 | game-dev,graphics-rendering | 0.887996 | 1 | 0.887996 |
Ragebones/StormCore | 5,355 | src/server/game/Entities/Object/ObjectPosSelector.cpp | /*
* Copyright (C) 2014-2017 StormCore
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectPosSelector.h"
ObjectPosSelector::ObjectPosSelector(float x, float y, float size, float dist)
: m_center_x(x), m_center_y(y), m_size(size), m_dist(dist)
{
m_anglestep = std::acos(m_dist/(m_dist+2*m_size));
m_nextUsedPos[USED_POS_PLUS] = m_UsedPosLists[USED_POS_PLUS].end();
m_nextUsedPos[USED_POS_MINUS] = m_UsedPosLists[USED_POS_MINUS].end();
m_smallStepAngle[USED_POS_PLUS] = 0;
m_smallStepAngle[USED_POS_MINUS] = 0;
m_smallStepOk[USED_POS_PLUS] = false;
m_smallStepOk[USED_POS_MINUS] = false;
m_smallStepNextUsedPos[USED_POS_PLUS] = NULL;
m_smallStepNextUsedPos[USED_POS_MINUS] = NULL;
}
ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos(UsedPosType uptype)
{
UsedPosList::const_iterator itr = m_nextUsedPos[uptype];
if (itr!=m_UsedPosLists[uptype].end())
++itr;
if (itr==m_UsedPosLists[uptype].end())
{
if (!m_UsedPosLists[~uptype].empty())
return &*m_UsedPosLists[~uptype].rbegin();
else
return NULL;
}
else
return &*itr;
}
void ObjectPosSelector::AddUsedPos(float size, float angle, float dist)
{
if (angle >= 0)
m_UsedPosLists[USED_POS_PLUS].insert(UsedPosList::value_type(angle, UsedPos(1.0f, size, dist)));
else
m_UsedPosLists[USED_POS_MINUS].insert(UsedPosList::value_type(-angle, UsedPos(-1.0f, size, dist)));
}
void ObjectPosSelector::InitializeAngle()
{
m_nextUsedPos[USED_POS_PLUS] = m_UsedPosLists[USED_POS_PLUS].begin();
m_nextUsedPos[USED_POS_MINUS] = m_UsedPosLists[USED_POS_MINUS].begin();
m_smallStepAngle[USED_POS_PLUS] = 0;
m_smallStepAngle[USED_POS_MINUS] = 0;
m_smallStepOk[USED_POS_PLUS] = true;
m_smallStepOk[USED_POS_MINUS] = true;
}
bool ObjectPosSelector::FirstAngle(float& angle)
{
if (m_UsedPosLists[USED_POS_PLUS].empty() && !m_UsedPosLists[USED_POS_MINUS].empty())
return NextAngleFor(*m_UsedPosLists[USED_POS_MINUS].begin(), 1.0f, USED_POS_PLUS, angle);
else if (m_UsedPosLists[USED_POS_MINUS].empty() && !m_UsedPosLists[USED_POS_PLUS].empty())
return NextAngleFor(*m_UsedPosLists[USED_POS_PLUS].begin(), -1.0f, USED_POS_MINUS, angle);
return false;
}
bool ObjectPosSelector::NextAngle(float& angle)
{
while (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() ||
m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end() ||
m_smallStepOk[USED_POS_PLUS] || m_smallStepOk[USED_POS_MINUS] )
{
// calculate next possible angle
if (NextPosibleAngle(angle))
return true;
}
return false;
}
bool ObjectPosSelector::NextUsedAngle(float& angle)
{
while (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() ||
m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end())
{
// calculate next possible angle
if (!NextPosibleAngle(angle))
return true;
}
return false;
}
bool ObjectPosSelector::NextPosibleAngle(float& angle)
{
// ++ direction less updated
if (m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() &&
(m_nextUsedPos[USED_POS_MINUS]==m_UsedPosLists[USED_POS_MINUS].end() || m_nextUsedPos[USED_POS_PLUS]->first <= m_nextUsedPos[USED_POS_MINUS]->first))
{
bool ok;
if (m_smallStepOk[USED_POS_PLUS])
ok = NextSmallStepAngle(1.0f, USED_POS_PLUS, angle);
else
ok = NextAngleFor(*m_nextUsedPos[USED_POS_PLUS], 1.0f, USED_POS_PLUS, angle);
if (!ok)
++m_nextUsedPos[USED_POS_PLUS]; // increase. only at fail (original or checked)
return ok;
}
// -- direction less updated
else if (m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end())
{
bool ok;
if (m_smallStepOk[USED_POS_MINUS])
ok = NextSmallStepAngle(-1.0f, USED_POS_MINUS, angle);
else
ok = NextAngleFor(*m_nextUsedPos[USED_POS_MINUS], -1.0f, USED_POS_MINUS, angle);
if (!ok)
++m_nextUsedPos[USED_POS_MINUS];
return ok;
}
else // both list empty
{
if (m_smallStepOk[USED_POS_PLUS] && (!m_smallStepOk[USED_POS_MINUS] || m_smallStepAngle[USED_POS_PLUS] <= m_smallStepAngle[USED_POS_MINUS]))
return NextSmallStepAngle(1.0f, USED_POS_PLUS, angle);
// -- direction less updated
else if (m_smallStepOk[USED_POS_MINUS])
return NextSmallStepAngle(-1.0f, USED_POS_MINUS, angle);
}
// no angles
return false;
}
| 0 | 0.7813 | 1 | 0.7813 | game-dev | MEDIA | 0.678582 | game-dev | 0.890556 | 1 | 0.890556 |
MadDeCoDeR/Classic-RBDOOM-3-BFG | 2,233 | neo/libs/irrxml/src/fast_atof.h | // Copyright (C) 2002-2005 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine" and the "irrXML" project.
// For conditions of distribution and use, see copyright notice in irrlicht.h and irrXML.h
#ifndef __FAST_A_TO_F_H_INCLUDED__
#define __FAST_A_TO_F_H_INCLUDED__
#include <stdlib.h>
#include <math.h>
namespace irr
{
namespace core
{
const float fast_atof_table[] = {
0.f,
0.1f,
0.01f,
0.001f,
0.0001f,
0.00001f,
0.000001f,
0.0000001f,
0.00000001f,
0.000000001f,
0.0000000001f,
0.00000000001f,
0.000000000001f,
0.0000000000001f,
0.00000000000001f,
0.000000000000001f
};
//! Provides a fast function for converting a string into a float,
//! about 6 times faster than atof in win32.
// If you find any bugs, please send them to me, niko (at) irrlicht3d.org.
inline char* fast_atof_move(char* c, float& out)
{
bool inv = false;
char *t;
float f;
if (*c=='-')
{
c++;
inv = true;
}
f = (float)strtol(c, &t, 10);
c = t;
if (*c == '.')
{
c++;
float pl = (float)strtol(c, &t, 10);
pl *= fast_atof_table[t-c];
f += pl;
c = t;
if (*c == 'e')
{
++c;
float exp = (float)strtol(c, &t, 10);
f *= (float)pow(10.0f, exp);
c = t;
}
}
if (inv)
f *= -1.0f;
out = f;
return c;
}
//! Provides a fast function for converting a string into a float,
//! about 6 times faster than atof in win32.
// If you find any bugs, please send them to me, niko (at) irrlicht3d.org.
inline const char* fast_atof_move_const(const char* c, float& out)
{
bool inv = false;
char *t;
float f;
if (*c=='-')
{
c++;
inv = true;
}
f = (float)strtol(c, &t, 10);
c = t;
if (*c == '.')
{
c++;
float pl = (float)strtol(c, &t, 10);
pl *= fast_atof_table[t-c];
f += pl;
c = t;
if (*c == 'e')
{
++c;
f32 exp = (f32)strtol(c, &t, 10);
f *= (f32)powf(10.0f, exp);
c = t;
}
}
if (inv)
f *= -1.0f;
out = f;
return c;
}
inline float fast_atof(const char* c)
{
float ret;
fast_atof_move_const(c, ret);
return ret;
}
} // end namespace core
}// end namespace irr
#endif
| 0 | 0.549848 | 1 | 0.549848 | game-dev | MEDIA | 0.416391 | game-dev,scientific-computing | 0.557963 | 1 | 0.557963 |
EthanC/Jekyll | 3,345 | Jekyll.Library/Game/BlackOps4/XAssets/RawFile.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace JekyllLibrary.Library
{
public partial class BlackOps4
{
public class RawFile : IXAssetPool
{
public override string Name => "Raw File";
public override int Index => (int)XAssetType.rawfile;
/// <summary>
/// Structure of a Black Ops 4 RawFile XAsset.
/// </summary>
private struct RawFileXAsset
{
public long Name { get; set; }
public long NullPadding1 { get; set; }
public int Len { get; set; }
public int CompressedLen { get; set; }
public long Buffer { get; set; }
}
/// <summary>
/// Load the valid XAssets for the RawFile XAsset Pool.
/// </summary>
/// <param name="instance"></param>
/// <returns>List of RawFile XAsset objects.</returns>
public override List<GameXAsset> Load(JekyllInstance instance)
{
List<GameXAsset> results = new List<GameXAsset>();
DBAssetPool pool = instance.Reader.ReadStruct<DBAssetPool>(instance.Game.DBAssetPools + (Index * Marshal.SizeOf<DBAssetPool>()));
Entries = pool.Entries;
ElementSize = pool.ElementSize;
PoolSize = pool.PoolSize;
if (IsValidPool(Name, ElementSize, Marshal.SizeOf<RawFileXAsset>()) == false)
{
return results;
}
for (int i = 0; i < PoolSize; i++)
{
RawFileXAsset header = instance.Reader.ReadStruct<RawFileXAsset>(Entries + (i * ElementSize));
if (header.Len == 0)
{
continue;
}
results.Add(new GameXAsset()
{
Name = instance.Reader.ReadBytesToString(Entries + (i * ElementSize)).ToLower(),
Type = Name,
Size = ElementSize,
XAssetPool = this,
HeaderAddress = Entries + (i * Marshal.SizeOf<RawFileXAsset>()),
});
}
return results;
}
/// <summary>
/// Exports the specified RawFile XAsset.
/// </summary>
/// <param name="xasset"></param>
/// <param name="instance"></param>
/// <returns>Status of the export operation.</returns>
public override JekyllStatus Export(GameXAsset xasset, JekyllInstance instance)
{
RawFileXAsset header = instance.Reader.ReadStruct<RawFileXAsset>(xasset.HeaderAddress);
string path = Path.Combine(instance.ExportPath, "rawfile/" + xasset.Name);
Directory.CreateDirectory(Path.GetDirectoryName(path));
byte[] buffer = instance.Reader.ReadBytes(header.Buffer, header.Len);
File.WriteAllBytes(path, buffer);
Console.WriteLine($"Exported {xasset.Type} {xasset.Name}");
return JekyllStatus.Success;
}
}
}
} | 0 | 0.826708 | 1 | 0.826708 | game-dev | MEDIA | 0.791723 | game-dev | 0.965269 | 1 | 0.965269 |
Game4all/gamebosu | 7,962 | osu.Game.Rulesets.Gamebosu/UI/Screens/Selection/RomSelector.cs | // gamebosu! ruleset. Copyright Lucas ARRIESSE aka Game4all. Licensed under GPLv3.
// See LICENSE at root of repo for more information on licensing.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Gamebosu.UI.Input;
using System;
using System.Collections.Generic;
using System.Linq;
namespace osu.Game.Rulesets.Gamebosu.UI.Screens.Selection
{
public partial class RomSelector : CompositeDrawable, IKeyBindingHandler<GamebosuAction>
{
public const double FADE_TIME = 300;
public const Easing EASING = Easing.OutQuint;
private readonly Container<SelectionCard> selectionContainer;
private readonly SpriteIcon selectionLeft;
private readonly SpriteIcon selectionRight;
private readonly NoRomAvailableMessage noRomPopup;
private Sample selectSample;
private Sample confirmSelectSample;
private BindableInt selection = new BindableInt(0)
{
MinValue = 0,
};
/// <summary>
/// Called when the ROM has been selected.
/// </summary>
public Action<string> RomSelected;
/// <summary>
/// The available roms for use.
/// Will update the selectable rom cards when updated.
/// </summary>
public readonly Bindable<IEnumerable<string>> AvailableRoms = new Bindable<IEnumerable<string>>(Enumerable.Empty<string>());
/// <summary>
/// Displays an error popup on the selected card indicating that the coresponding cartridge is unavailable.
/// </summary>
public void MarkUnavailable() => Scheduler.Add(() => getDrawableCardAtIndex(selection.Value)?.MarkUnavailable());
public RomSelector()
{
RelativeSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new osuTK.Vector2(0, 0.1f),
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = 400,
Children = new Drawable[]
{
noRomPopup = new NoRomAvailableMessage(),
selectionLeft = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativePositionAxes = Axes.X,
X = -0.25f,
Size = new osuTK.Vector2(40),
Icon = FontAwesome.Solid.ChevronLeft,
Alpha = 0,
},
selectionContainer = new Container<SelectionCard>
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
},
selectionRight = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativePositionAxes = Axes.X,
X = 0.25f,
Size = new osuTK.Vector2(40),
Icon = FontAwesome.Solid.ChevronRight,
Alpha = 0,
},
}
},
}
};
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
selectSample = audio.Samples.Get("UI/generic-hover-soft");
confirmSelectSample = audio.Samples.Get("UI/notification-pop-in");
selection.BindValueChanged(updateSelection, true);
AvailableRoms.BindValueChanged(roms =>
{
noRomPopup.State.Value = roms.NewValue.Count() > 0 ? Visibility.Hidden : Visibility.Visible;
selectionContainer.Clear();
selectionContainer.AddRange(roms.NewValue.Select(rom => new SelectionCard(rom)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
}));
selection.MaxValue = (roms.NewValue.Count() - 1) > 0 ? (roms.NewValue.Count() - 1) : 0;
selection.TriggerChange();
}, true);
selection.BindValueChanged(updateSelectedDrawableCard, true);
}
/// <summary>
/// Updates the arrows from the selector, depending of whether there are other roms available.
/// </summary>
private void updateSelection(ValueChangedEvent<int> selection)
{
selectSample?.Play();
selectionLeft.FadeIn(FADE_TIME, EASING);
selectionRight.FadeIn(FADE_TIME, EASING);
if (selection.NewValue == this.selection.MaxValue)
selectionRight.FadeOut(FADE_TIME, EASING);
if (selection.NewValue == 0)
selectionLeft.FadeOut(FADE_TIME, EASING);
}
/// <summary>
/// Set the current selected rom card as the one at the given index.
/// </summary>
private void setSelection(int idx)
{
selection.Value += idx;
if (idx == 1)
{
selectionRight
.ScaleTo(1.5f, 150, Easing.OutQuint)
.Then(0)
.ScaleTo(1, 150, Easing.OutQuint);
}
else
{
selectionLeft
.ScaleTo(1.5f, 150, Easing.OutQuint)
.Then(0)
.ScaleTo(1, 150, Easing.OutQuint);
}
}
/// <summary>
/// Updates the visibility of the currently selected drawable card.
/// </summary>
private void updateSelectedDrawableCard(ValueChangedEvent<int> e)
{
getDrawableCardAtIndex(e.OldValue)?.FadeOut(FADE_TIME, EASING);
getDrawableCardAtIndex(e.NewValue)?.FadeIn(2 * FADE_TIME, EASING);
}
private SelectionCard getDrawableCardAtIndex(int index) => (selectionContainer.Count < index || selectionContainer.Count == 0) ? null : selectionContainer[index];
public bool OnPressed(KeyBindingPressEvent<GamebosuAction> action)
{
switch (action.Action)
{
case GamebosuAction.DPadRight:
setSelection(1);
break;
case GamebosuAction.DPadLeft:
setSelection(-1);
break;
case GamebosuAction.ButtonA:
case GamebosuAction.ButtonStart:
case GamebosuAction.ButtonSelect:
var rom = AvailableRoms.Value.ElementAtOrDefault(selection.Value);
if (rom == null)
goto default;
confirmSelectSample?.Play();
RomSelected?.Invoke(rom);
break;
default:
break;
}
return true;
}
public void OnReleased(KeyBindingReleaseEvent<GamebosuAction> action)
{
}
}
} | 0 | 0.949199 | 1 | 0.949199 | game-dev | MEDIA | 0.912978 | game-dev | 0.992994 | 1 | 0.992994 |
jie326513988/ESP32C3-JDI-LCD-LVGL | 5,785 | .pio/libdeps/airm2m_core_esp32c3/box2d-3.0.0/src/joint.h | // SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "solver.h"
#include "box2d/types.h"
typedef struct b2DebugDraw b2DebugDraw;
typedef struct b2StepContext b2StepContext;
typedef struct b2World b2World;
/// A joint edge is used to connect bodies and joints together
/// in a joint graph where each body is a node and each joint
/// is an edge. A joint edge belongs to a doubly linked list
/// maintained in each attached body. Each joint has two joint
/// nodes, one for each attached body.
typedef struct b2JointEdge
{
int bodyId;
int prevKey;
int nextKey;
} b2JointEdge;
// Map from b2JointId to b2Joint in the solver sets
typedef struct b2Joint
{
void* userData;
// index of simulation set stored in b2World
// B2_NULL_INDEX when slot is free
int setIndex;
// index into the constraint graph color array, may be B2_NULL_INDEX for sleeping/disabled joints
// B2_NULL_INDEX when slot is free
int colorIndex;
// joint index within set or graph color
// B2_NULL_INDEX when slot is free
int localIndex;
b2JointEdge edges[2];
int jointId;
int islandId;
int islandPrev;
int islandNext;
// This is monotonically advanced when a body is allocated in this slot
// Used to check for invalid b2JointId
int revision;
float drawSize;
b2JointType type;
bool isMarked;
bool collideConnected;
} b2Joint;
typedef struct b2DistanceJoint
{
float length;
float hertz;
float dampingRatio;
float minLength;
float maxLength;
float maxMotorForce;
float motorSpeed;
float impulse;
float lowerImpulse;
float upperImpulse;
float motorImpulse;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 deltaCenter;
b2Softness distanceSoftness;
float axialMass;
bool enableSpring;
bool enableLimit;
bool enableMotor;
} b2DistanceJoint;
typedef struct b2MotorJoint
{
b2Vec2 linearOffset;
float angularOffset;
b2Vec2 linearImpulse;
float angularImpulse;
float maxForce;
float maxTorque;
float correctionFactor;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 deltaCenter;
float deltaAngle;
b2Mat22 linearMass;
float angularMass;
} b2MotorJoint;
typedef struct b2MouseJoint
{
b2Vec2 targetA;
float hertz;
float dampingRatio;
float maxForce;
b2Vec2 linearImpulse;
float angularImpulse;
b2Softness linearSoftness;
b2Softness angularSoftness;
int indexB;
b2Vec2 anchorB;
b2Vec2 deltaCenter;
b2Mat22 linearMass;
} b2MouseJoint;
typedef struct b2PrismaticJoint
{
b2Vec2 localAxisA;
b2Vec2 impulse;
float springImpulse;
float motorImpulse;
float lowerImpulse;
float upperImpulse;
float hertz;
float dampingRatio;
float maxMotorForce;
float motorSpeed;
float referenceAngle;
float lowerTranslation;
float upperTranslation;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 axisA;
b2Vec2 deltaCenter;
float deltaAngle;
float axialMass;
b2Softness springSoftness;
bool enableSpring;
bool enableLimit;
bool enableMotor;
} b2PrismaticJoint;
typedef struct b2RevoluteJoint
{
b2Vec2 linearImpulse;
float springImpulse;
float motorImpulse;
float lowerImpulse;
float upperImpulse;
float hertz;
float dampingRatio;
float maxMotorTorque;
float motorSpeed;
float referenceAngle;
float lowerAngle;
float upperAngle;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 deltaCenter;
float deltaAngle;
float axialMass;
b2Softness springSoftness;
bool enableSpring;
bool enableMotor;
bool enableLimit;
} b2RevoluteJoint;
typedef struct b2WeldJoint
{
float referenceAngle;
float linearHertz;
float linearDampingRatio;
float angularHertz;
float angularDampingRatio;
b2Softness linearSoftness;
b2Softness angularSoftness;
b2Vec2 linearImpulse;
float angularImpulse;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 deltaCenter;
float deltaAngle;
float axialMass;
} b2WeldJoint;
typedef struct b2WheelJoint
{
b2Vec2 localAxisA;
float perpImpulse;
float motorImpulse;
float springImpulse;
float lowerImpulse;
float upperImpulse;
float maxMotorTorque;
float motorSpeed;
float lowerTranslation;
float upperTranslation;
float hertz;
float dampingRatio;
int indexA;
int indexB;
b2Vec2 anchorA;
b2Vec2 anchorB;
b2Vec2 axisA;
b2Vec2 deltaCenter;
float perpMass;
float motorMass;
float axialMass;
b2Softness springSoftness;
bool enableSpring;
bool enableMotor;
bool enableLimit;
} b2WheelJoint;
/// The base joint class. Joints are used to constraint two bodies together in
/// various fashions. Some joints also feature limits and motors.
typedef struct b2JointSim
{
int jointId;
int bodyIdA;
int bodyIdB;
b2JointType type;
// Anchors relative to body origin
b2Vec2 localOriginAnchorA;
b2Vec2 localOriginAnchorB;
float invMassA, invMassB;
float invIA, invIB;
union
{
b2DistanceJoint distanceJoint;
b2MotorJoint motorJoint;
b2MouseJoint mouseJoint;
b2RevoluteJoint revoluteJoint;
b2PrismaticJoint prismaticJoint;
b2WeldJoint weldJoint;
b2WheelJoint wheelJoint;
};
} b2JointSim;
b2Joint* b2GetJoint( b2World* world, int jointId );
void b2DestroyJointInternal( b2World* world, b2Joint* joint, bool wakeBodies );
b2JointSim* b2GetJointSim( b2World* world, b2Joint* joint );
b2JointSim* b2GetJointSimCheckType( b2JointId jointId, b2JointType type );
void b2PrepareJoint( b2JointSim* joint, b2StepContext* context );
void b2WarmStartJoint( b2JointSim* joint, b2StepContext* context );
void b2SolveJoint( b2JointSim* joint, b2StepContext* context, bool useBias );
void b2PrepareOverflowJoints( b2StepContext* context );
void b2WarmStartOverflowJoints( b2StepContext* context );
void b2SolveOverflowJoints( b2StepContext* context, bool useBias );
void b2DrawJoint( b2DebugDraw* draw, b2World* world, b2Joint* joint );
| 0 | 0.852299 | 1 | 0.852299 | game-dev | MEDIA | 0.977747 | game-dev | 0.809889 | 1 | 0.809889 |
bergerhealer/TrainCarts | 24,114 | src/main/java/com/bergerkiller/bukkit/tc/attachments/control/seat/SeatedEntity.java | package com.bergerkiller.bukkit.tc.attachments.control.seat;
import java.util.function.Function;
import com.bergerkiller.bukkit.common.utils.CommonUtil;
import com.bergerkiller.bukkit.neznamytabnametaghider.TabNameTagHider;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.bergerkiller.bukkit.common.controller.VehicleMountController;
import com.bergerkiller.bukkit.common.math.Matrix4x4;
import com.bergerkiller.bukkit.common.math.Quaternion;
import com.bergerkiller.bukkit.common.utils.MathUtil;
import com.bergerkiller.bukkit.common.wrappers.DataWatcher;
import com.bergerkiller.bukkit.tc.attachments.FakePlayerSpawner;
import com.bergerkiller.bukkit.tc.attachments.VirtualEntity;
import com.bergerkiller.bukkit.tc.attachments.VirtualEntity.SyncMode;
import com.bergerkiller.bukkit.tc.attachments.api.AttachmentAnchor;
import com.bergerkiller.bukkit.tc.attachments.api.AttachmentViewer;
import com.bergerkiller.bukkit.tc.attachments.control.CartAttachment;
import com.bergerkiller.bukkit.tc.attachments.control.CartAttachmentSeat;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityMetadataHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutUpdateAttributesHandle;
import com.bergerkiller.generated.net.minecraft.world.entity.EntityHandle;
import com.bergerkiller.generated.net.minecraft.world.entity.EntityLivingHandle;
import com.bergerkiller.generated.net.minecraft.world.entity.decoration.EntityArmorStandHandle;
/**
* Represents the visible, seated entity inside a seat. Sometimes this entity is a fake
* version of the actual entity inside in order to apply additional transformations to it,
* without the actual player entity sending packets that can corrupt it.
*/
public abstract class SeatedEntity {
protected Entity entity = null;
protected int tickEntered = -1;
protected boolean showDummy = false; // Whether to show a dummy player sitting in the seat
protected DisplayMode displayMode = DisplayMode.DEFAULT;
protected final CartAttachmentSeat seat;
public final SeatOrientation orientation = new SeatOrientation();
// The fake mount is used when this seat has a position set, or otherwise cannot
// mount the passenger to a parent attachment. The parentMountId is set to the
// entity id of the vehicle this passenger is mounted to.
private VirtualEntity fakeMount = null;
public int parentMountId = -1;
// Whether this seated entity was spawned to the player itself
// This is the case when it is displayed in first-person, as a third-person view mode
// This is set/unset when makeVisibleFirstPerson and makeHiddenFirstPerson are called.
private boolean madeVisibleInFirstPerson = false;
// Used to hide & restore custom TAB plugin nametags
private TabNameTagHider.TabPlayerNameTagHider tabNameTagHider = null;
public SeatedEntity(CartAttachmentSeat seat) {
this.seat = seat;
}
/**
* Gets whether this seat is empty
*
* @return True if empty
*/
public boolean isEmpty() {
return entity == null;
}
/**
* Gets whether this seated entity displays anything. This is the case
* when an entity is occupying this seat, or when debug display is active.
*
* @return True if this seated entity is displayed
*/
public boolean isDisplayed() {
return entity != null || showDummy;
}
/**
* Gets whether a Player entity is inside this seat.
*
* @return True if the seated entity is a Player
*/
public boolean isPlayer() {
return entity instanceof Player;
}
/**
* Gets the entity currently inside the seat
*
* @return seated entity
*/
public Entity getEntity() {
return this.entity;
}
/**
* Gets the number of ticks this current Entity has been inside the seat.
* Returns 0 if this seat has no passenger.
*
* @return Number of ticks the current passenger entity has been inside the seat
*/
public int getTicksInSeat() {
return (tickEntered == -1) ? 0 :(CommonUtil.getServerTicks() - tickEntered);
}
/**
* Gets whether a dummy player is being displayed, providing no other
* entity is inside the seat.
*
* @return Whether dummy player mode is active
*/
public boolean isDummyPlayer() {
return this.showDummy;
}
/**
* Gets whether a dummy player is actually being displayed. If dummy
* mode is active but a player is in the seat, returns false.
*
* @return True if the dummy player is displayed
*/
public boolean isDummyPlayerDisplayed() {
return this.showDummy && this.entity == null;
}
/**
* Sets a player to act as a dummy entity displayed sitting in the seat
*
* @param show Whether to show the dummy player
*/
public final void setShowDummyPlayer(boolean show) {
if (this.showDummy != show) {
this.showDummy = show;
if (this.entity == null) {
this.updateMode(true);
}
}
}
/**
* Sets the entity currently inside the seat
*
* @param entity
*/
public final void setEntity(Entity entity) {
// Restore nametag if one was hidden
if (this.tabNameTagHider != null) {
this.tabNameTagHider.show();
this.tabNameTagHider = null;
}
// Update entity
if (this.entity != entity) {
this.tickEntered = (entity == null) ? -1 : CommonUtil.getServerTicks();
}
this.entity = entity;
// Hide if view mode is no-nametag
if (entity instanceof Player && this.getDisplayMode() == DisplayMode.NO_NAMETAG) {
this.tabNameTagHider = seat.getPlugin().getTabNameHider((Player) entity);
if (this.tabNameTagHider != null) {
this.tabNameTagHider.hide();
}
}
this.updateMode(true);
}
public DisplayMode getDisplayMode() {
return this.displayMode;
}
public void setDisplayMode(DisplayMode displayMode) {
this.displayMode = displayMode;
}
protected void hideRealPlayer(AttachmentViewer viewer) {
if (this.entity == viewer.getPlayer()) {
// Sync to self: make the real player invisible using a metadata change
FirstPersonView.setPlayerVisible(viewer, false);
} else {
// Sync to others: destroy the original player
viewer.getVehicleMountController().despawn(this.entity.getEntityId());
}
}
protected void showRealPlayer(AttachmentViewer viewer) {
// Respawn the actual player or clean up the list
// Only needed when the player is not the viewer
if (viewer.getPlayer() == this.entity) {
// Can not respawn yourself! Make visible using metadata.
FirstPersonView.setPlayerVisible(viewer, true);
} else {
// Respawns the player as a normal player
VehicleMountController vmc = viewer.getVehicleMountController();
vmc.respawn((Player) this.entity, (theViewer, thePlayer) -> {
FakePlayerSpawner.NORMAL.spawnPlayer(theViewer, thePlayer, thePlayer.getEntityId(),
FakePlayerSpawner.FakePlayerPosition.ofPlayer(thePlayer),
meta -> {});
});
}
}
/**
* Resets the metadata of this seated entity to the actual metadata of the entity
*
* @param viewer
*/
public void resetMetadata(AttachmentViewer viewer) {
DataWatcher metaTmp = EntityHandle.fromBukkit(this.entity).getDataWatcher();
viewer.send(PacketPlayOutEntityMetadataHandle.createNew(this.entity.getEntityId(), metaTmp, true));
}
/**
* Gets the current exact head rotation of the Entity inside this seat. Returns a
* default facing-forward if no entity, or the dummy player, is displayed. Takes
* into account special fpv modes like spectator, where the head rotation is relative
* to the seat orientation.
*
* @param transform Current body (butt) transformation of this seated entity
* @return current head rotation
*/
protected PassengerPose getCurrentHeadRotation(Matrix4x4 transform) {
// When no entity is inside, show seat rotation, facing forwards (dummy player)
if (this.isEmpty()) {
return new PassengerPose(transform, transform.getRotation());
}
// If spectator mode is used, and is active, defer.
if (seat.firstPerson instanceof FirstPersonViewSpectator && seat.firstPerson.player != null) {
return new PassengerPose(transform, ((FirstPersonViewSpectator) seat.firstPerson)
.getCurrentHeadRotation(transform));
}
// If smooth coasters is used, then the player yaw/pitch is relative to the eye orientation
// Defer to the Quaternion version of this method, and convert
if (seat.useSmoothCoasters()) {
return new PassengerPose(transform, getCurrentHeadRotationQuat(transform));
}
// Default: query the entity head pitch and yaw
// When rotation is locked, use the body (transform) yaw
EntityHandle entityHandle = EntityHandle.fromBukkit(entity);
if (seat.isRotationLocked()) {
return new PassengerPose(transform,
entityHandle.getPitch(),
entityHandle.getHeadRotation());
} else {
return new PassengerPose(entityHandle.getYaw(),
entityHandle.getPitch(),
entityHandle.getHeadRotation());
}
}
/**
* Same as {@link #getCurrentHeadRotation(Matrix4x4)} but returns a Quaternion instead.
* If body rotation is locked, restricts head rotation to an appropriate amount.
*
* @param transform Current body (butt) transformation of this seated entity
* @return current head rotation (as quaternion)
*/
protected Quaternion getCurrentHeadRotationQuat(Matrix4x4 transform) {
// When no entity is inside, show seat rotation, facing forwards (dummy player)
if (this.isEmpty()) {
return transform.getRotation();
}
// If spectator mode is used, and is active, defer.
// No need to check for body locking, as that's already done in spectator mode at input stage.
if (seat.firstPerson instanceof FirstPersonViewSpectator && seat.firstPerson.player != null) {
return ((FirstPersonViewSpectator) seat.firstPerson).getCurrentHeadRotation(transform);
}
if (seat.isRotationLocked()) {
// Default: query the entity head pitch and yaw
// restrict head yaw to body yaw
EntityHandle entityHandle = EntityHandle.fromBukkit(entity);
PassengerPose pose = new PassengerPose(transform,
entityHandle.getPitch(),
entityHandle.getHeadRotation());
pose = pose.limitHeadYaw(FirstPersonView.BODY_LOCK_FOV_LIMIT);
Quaternion rotation = new Quaternion();
rotation.rotateY(-pose.headYaw);
rotation.rotateX(pose.headPitch);
return rotation;
} else {
// Default: query the entity head pitch and yaw
EntityHandle entityHandle = EntityHandle.fromBukkit(entity);
Quaternion rotation = new Quaternion();
rotation.rotateY(-entityHandle.getHeadRotation());
rotation.rotateX(entityHandle.getPitch());
return rotation;
}
}
/**
* If needed, spawns a vehicle mount to make an Entity id available for mounting
* a passenger directly to the vehicle.
*
* @param viewer
* @return vehicle mount id to which a passenger can be mounted
*/
public int spawnVehicleMount(AttachmentViewer viewer) {
// Spawn fake mount if one is needed
if (this.parentMountId == -1) {
// Use parent node for mounting point, unless not possible
// Making use of SEAT_PARENT will disable any additional transforms
// When seat rotation is locked, this cannot be used, because the sending of the 'real'
// vehicles rotation messes with the seat rotation configured.
if (seat.getConfiguredPosition().anchor == AttachmentAnchor.SEAT_PARENT &&
seat.getConfiguredPosition().isIdentity() &&
seat.getParent() != null &&
!seat.isRotationLocked())
{
this.parentMountId = ((CartAttachment) seat.getParent()).getMountEntityId();
}
// No parent node mount is used, create a fake mount
if (this.parentMountId == -1) {
if (this.fakeMount == null) {
this.fakeMount = createPassengerVehicle();
this.fakeMount.updatePosition(seat.getTransform(), new Vector(0.0, (double) this.orientation.getMountYaw(), 0.0));
this.fakeMount.syncPosition(true);
}
this.parentMountId = this.fakeMount.getEntityId();
}
}
// Spawn fake mount, if used
if (this.fakeMount != null) {
this.fakeMount.spawn(viewer, seat.calcMotion());
// Also send zero-max-health if the viewer is the one sitting in the entity
if (this.entity == viewer.getPlayer()) {
viewer.send(PacketPlayOutUpdateAttributesHandle.createZeroMaxHealth(this.fakeMount.getEntityId()));
}
}
return this.parentMountId;
}
/**
* If a fake mount was created by {@link #spawnVehicleMount(AttachmentViewer)}, despawns
* that fake mount. Otherwise does nothing.
*
* @param viewer
*/
public void despawnVehicleMount(AttachmentViewer viewer) {
if (fakeMount != null) {
fakeMount.destroy(viewer);
// If no more viewers use it, reset
if (!fakeMount.hasViewers()) {
fakeMount = null;
parentMountId = -1;
}
}
}
protected void updateVehicleMountPosition(Matrix4x4 transform) {
if (fakeMount != null) {
fakeMount.updatePosition(transform, new Vector(0.0, (double) this.orientation.getMountYaw(), 0.0));
}
}
protected void syncVehicleMountPosition(boolean absolute) {
if (fakeMount != null) {
fakeMount.syncPosition(absolute);
}
}
public final void makeVisibleFirstPerson(AttachmentViewer viewer) {
madeVisibleInFirstPerson = true;
makeVisible(viewer);
}
public final void makeHiddenFirstPerson(AttachmentViewer viewer) {
makeHidden(viewer);
madeVisibleInFirstPerson = false;
}
/**
* Whether this seated entity is spawned to itself - the entity being a Player.
* This is true when the player can view himself sitting from a third-person
* perspective.
*
* @return True if made visible in first-person
*/
public final boolean isMadeVisibleInFirstPerson() {
return madeVisibleInFirstPerson;
}
/**
* Gets the seat-relative x/y/z offset away from the seat cameras should be positioned
* to view this seated entity in third-person. For large entities, this should be
* further away than closer-by ones.
*
* @return camera offset for viewing this entity in THIRD_P mode
*/
public abstract Vector getThirdPersonCameraOffset();
/**
* Gets the seat-relative x/y/z offset away from the seat cameras should be positioned
* to look exactly from where the player would normally look as this entity.
*
* @return camera offset for viewing from this entity in first-person
*/
public abstract Vector getFirstPersonCameraOffset();
/**
* Gets whether this seated entity must be viewed with a fake third-person camera to
* have the correct height offset.
*
* @return True if a fake camera mount should be used when viewed in first-person
*/
public boolean isFirstPersonCameraFake() {
// Only do it when the seat (butt) to camera (eye) offset is exactly vanilla
// If not, we must use a fake mount to position it properly
return this.getFirstPersonCameraOffset().getY() != VirtualEntity.PLAYER_SIT_BUTT_EYE_HEIGHT;
}
/**
* Spawns this seated entity for a viewer. Mounts any real entity
* into its seat.
*
* @param viewer
*/
public abstract void makeVisible(AttachmentViewer viewer);
/**
* De-spawns this seated entity for a viewer. Unmounts any real entity
* from the seat.
*
* @param viewer
*/
public abstract void makeHidden(AttachmentViewer viewer);
/**
* Updates the display mode of the Entity. Display-specific operations can occur here.
* Silent is set to true when the entity has just been set, because right after calling this
* the seat is made visible to everyone again. No spawning should occur when silent
* is true!
*
* @param silent Whether to send new spawn/make-visible packets to players or not
*/
public void updateMode(boolean silent) {
// Compute new first-person state of whether the player sees himself from third person using a fake camera
FirstPersonViewMode new_firstPersonMode = this.seat.firstPerson.getMode();
// No other mode is supported here
if (new_firstPersonMode == FirstPersonViewMode.DYNAMIC) {
new_firstPersonMode = FirstPersonViewMode.THIRD_P;
}
// If unchanged, do nothing
if (new_firstPersonMode == seat.firstPerson.getLiveMode())
{
return;
}
// Sometimes a full reset of the FPV controller is required. Avoid when silent.
AttachmentViewer viewer;
if (!silent &&
seat.firstPerson.doesViewModeChangeRequireReset(new_firstPersonMode) &&
this.isPlayer() &&
seat.getAttachmentViewersSynced().contains(viewer = seat.getManager().asAttachmentViewer((Player) this.getEntity())))
{
// Hide, change, and make visible again, just for the first-player-view player
seat.makeHiddenImpl(viewer, true);
seat.firstPerson.setLiveMode(new_firstPersonMode);
seat.makeVisibleImpl(viewer, true);
return;
}
// Silent update
seat.firstPerson.setLiveMode(new_firstPersonMode);
}
/**
* Called to update the third-person viewed orientation of this seated entity
*
* @param transform
*/
public abstract void updatePosition(Matrix4x4 transform);
/**
* Called to send periodic movement update packets
*
* @param absolute True if this is an absolute position update
*/
public abstract void syncPosition(boolean absolute);
/**
* Called every time the attachment receives or loses focus.
* This is the glowing effect that 'blinks'.
*
* @param focused
*/
public abstract void updateFocus(boolean focused);
/**
* Creates a new suitable vehicle for putting passengers in. Passengers mounted to
* this entity will be positioned so their butt is at the input transform.
*
* @return New vehicle
*/
protected VirtualEntity createPassengerVehicle() {
VirtualEntity mount = new VirtualEntity(seat.getManager());
mount.setEntityType(EntityType.ARMOR_STAND);
mount.setSyncMode(SyncMode.SEAT);
mount.setUseMinecartInterpolation(seat.isMinecartInterpolation());
mount.setByViewerPositionAdjustment((viewer, pos) -> pos.setY(pos.getY() - viewer.getArmorStandButtOffset()));
mount.getMetaData().set(EntityHandle.DATA_FLAGS, (byte) (EntityHandle.DATA_FLAG_INVISIBLE));
mount.getMetaData().set(EntityLivingHandle.DATA_HEALTH, 10.0F);
mount.getMetaData().set(EntityArmorStandHandle.DATA_ARMORSTAND_FLAGS, (byte) (
EntityArmorStandHandle.DATA_FLAG_SET_MARKER |
EntityArmorStandHandle.DATA_FLAG_NO_BASEPLATE |
EntityArmorStandHandle.DATA_FLAG_IS_SMALL));
return mount;
}
/**
* Gets whether this seated entity is using a particular Entity ID in its display.
* Passenger entity ID is excluded.
*
* @param entityId
* @return True if this entity ID is used for display
*/
public abstract boolean containsEntityId(int entityId);
public static enum DisplayMode {
DEFAULT(SeatedEntityNormal::new), /* Player is displayed either upright or upside-down in a cart */
ELYTRA_SIT(SeatedEntityElytra::new), /* Player is in sitting pose while flying in an elytra */
STANDING(SeatedEntityStanding::new), /* Player is flying in a standing pose */
HEAD(SeatedEntityHead::new), /* Players are replaced with player skulls with their face */
NO_NAMETAG(SeatedEntityNormal::new), /* Same as DEFAULT, but no nametags are shown */
INVISIBLE(SeatedEntityInvisible::new); /* Shows nothing, makes original passenger invisible */
private final Function<CartAttachmentSeat, SeatedEntity> _constructor;
private DisplayMode(Function<CartAttachmentSeat, SeatedEntity> constructor) {
this._constructor = constructor;
}
public SeatedEntity create(CartAttachmentSeat seat) {
SeatedEntity seated = _constructor.apply(seat);
seated.setDisplayMode(this);
return seated;
}
}
/**
* Stores the passenger pose in a seat. This contains the yaw of the
* body in the seat, and the yaw/pitch of the head of the entity.
*/
public static class PassengerPose {
public final float bodyYaw;
public final float headPitch;
public final float headYaw;
public PassengerPose(Matrix4x4 bodyTransform, Quaternion headRotation) {
this.bodyYaw = getMountYaw(bodyTransform);
Vector ypr = headRotation.getYawPitchRoll();
this.headPitch = (float) ypr.getX();
this.headYaw = (float) ypr.getY();
}
public PassengerPose(Matrix4x4 bodyTransform, float headPitch, float headYaw) {
this.bodyYaw = getMountYaw(bodyTransform);
this.headPitch = headPitch;
this.headYaw = headYaw;
}
public PassengerPose(float bodyYaw, float headPitch, float headYaw) {
this.bodyYaw = bodyYaw;
this.headPitch = headPitch;
this.headYaw = headYaw;
}
/**
* Transforms this pose to what should be used for upside-down players on Minecraft 1.17
* and before. This works around a client bug on those versions.
*
* @return Upside-down fixed pose
*/
public PassengerPose upsideDownFix_Pre_1_17() {
return new PassengerPose(bodyYaw, -headPitch, -headYaw + 2.0f * bodyYaw);
}
public PassengerPose limitHeadYaw(float limit) {
if (MathUtil.getAngleDifference(headYaw, bodyYaw) > limit) {
if (MathUtil.getAngleDifference(headYaw, bodyYaw + limit) <
MathUtil.getAngleDifference(headYaw, bodyYaw - limit)) {
return new PassengerPose(bodyYaw, headPitch, bodyYaw + limit);
} else {
return new PassengerPose(bodyYaw, headPitch, bodyYaw - limit);
}
}
return this;
}
private static float getMountYaw(Matrix4x4 transform) {
Vector f = transform.getRotation().forwardVector();
return MathUtil.getLookAtYaw(-f.getZ(), f.getX());
}
}
}
| 0 | 0.946359 | 1 | 0.946359 | game-dev | MEDIA | 0.95996 | game-dev | 0.970729 | 1 | 0.970729 |
KhronosGroup/UnityGLTF | 1,813 | Editor/Scripts/Interactivity/VisualScriptingExport/UnitExporters/Generics/ExposeUnitExport.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEditor;
namespace UnityGLTF.Interactivity.VisualScripting.Export
{
public class ExposeUnitExport : IUnitExporterProvider
{
public Type unitType
{
get => typeof(Expose);
}
private static Dictionary<Type, (IUnitExporter converter, string[] supportedMembers)> _exposeExportRegister = new Dictionary<Type, (IUnitExporter, string[])>();
public IEnumerable<(Type, string[] members)> SupportedMembers => _exposeExportRegister.Select(pair => (pair.Key, pair.Value.supportedMembers));
[InitializeOnLoadMethod]
private static void Register()
{
UnitExporterRegistry.RegisterExporter(new ExposeUnitExport());
}
public static void RegisterExposeConvert(Type declaringType, IUnitExporter unitExporter, params string[] supportedMembers)
{
_exposeExportRegister.Add(declaringType, new (unitExporter, supportedMembers));
}
public static bool HasConvert(Type declaringType)
{
return _exposeExportRegister.ContainsKey(declaringType);
}
public static string[] GetSupportedMembers(Type declaringType)
{
if (_exposeExportRegister.TryGetValue(declaringType, out var exposeConvert))
return exposeConvert.supportedMembers;
return null;
}
public IUnitExporter GetExporter(IUnit unit)
{
var exposeUnit = unit as Expose;
if (_exposeExportRegister.TryGetValue(exposeUnit.type, out var exposeConvert))
return exposeConvert.converter;
return null;
}
}
} | 0 | 0.700377 | 1 | 0.700377 | game-dev | MEDIA | 0.748418 | game-dev | 0.866422 | 1 | 0.866422 |
MagmaGuy/EliteMobs | 11,062 | src/main/java/com/magmaguy/elitemobs/powers/ShieldWall.java | package com.magmaguy.elitemobs.powers;
import com.magmaguy.elitemobs.MetadataHandler;
import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent;
import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent;
import com.magmaguy.elitemobs.api.internal.RemovalReason;
import com.magmaguy.elitemobs.config.powers.PowersConfig;
import com.magmaguy.elitemobs.entitytracker.EntityTracker;
import com.magmaguy.elitemobs.mobconstructor.EliteEntity;
import com.magmaguy.elitemobs.powers.meta.ElitePower;
import com.magmaguy.elitemobs.powers.meta.MinorPower;
import com.magmaguy.elitemobs.utils.VisualDisplay;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
public class ShieldWall extends MinorPower {
private final HashMap<Direction, List<ArmorStand>> armorStands = new HashMap<>();
private final HashMap<Direction, Vector> armorStandOffBaseOffsets = new HashMap<>();
private double northHealthPool;
private double southHealthPool;
private double eastHealthPool;
private double westHealthPool;
@Getter
@Setter
private boolean isActive = false;
public ShieldWall() {
super(PowersConfig.getPower("shield_wall.yml"));
offsetInitializer();
}
public boolean preventDamage(Player player, EliteEntity eliteEntity, double damage) {
if (!Objects.equals(player.getLocation().getWorld(), eliteEntity.getLocation().getWorld())) return false;
Vector direction = player.getLocation().subtract(eliteEntity.getLocation()).toVector().normalize();
Direction damageDirection;
if (Math.abs(direction.getX()) > Math.abs(direction.getZ())) {
if (direction.getX() > 0)
damageDirection = Direction.EAST;
else
damageDirection = Direction.WEST;
} else if (direction.getZ() > 0)
damageDirection = Direction.SOUTH;
else
damageDirection = Direction.NORTH;
switch (damageDirection) {
case NORTH:
if (northHealthPool > 0) {
northHealthPool -= damage;
return true;
}
break;
case SOUTH:
if (southHealthPool > 0) {
southHealthPool -= damage;
return true;
}
break;
case EAST:
if (eastHealthPool > 0) {
eastHealthPool -= damage;
return true;
}
break;
case WEST:
default:
if (westHealthPool > 0) {
westHealthPool -= damage;
return true;
}
}
return false;
}
public void initialize(EliteEntity eliteEntity) {
if (ThreadLocalRandom.current().nextDouble() >= .1) return;
doCooldown(eliteEntity);
/*
1 = north
2 = east
3 = south
4 = west
*/
int direction = ThreadLocalRandom.current().nextInt(1, 5);
northHealthPool = eliteEntity.getLevel();
southHealthPool = eliteEntity.getLevel();
eastHealthPool = eliteEntity.getLevel();
westHealthPool = eliteEntity.getLevel();
switch (direction) {
case 1:
northHealthPool = 0;
break;
case 2:
eastHealthPool = 0;
break;
case 3:
southHealthPool = 0;
break;
case 4:
westHealthPool = 0;
break;
}
for (int i = 1; i < 5; i++)
if (direction != i)
armorStands.put(directionConverter(i), armorStandCreator(directionConverter(i), eliteEntity));
armorStandTracker(eliteEntity);
setActive(true);
}
private Direction directionConverter(int direction) {
switch (direction) {
case 1:
return Direction.NORTH;
case 2:
return Direction.EAST;
case 3:
return Direction.SOUTH;
case 4:
default:
return Direction.WEST;
}
}
private void offsetInitializer() {
for (int i = 1; i < 5; i++) {
switch (i) {
case 1:
armorStandOffBaseOffsets.put(directionConverter(i), new Vector(0, 0, -1));
break;
case 2:
armorStandOffBaseOffsets.put(directionConverter(i), new Vector(1, 0, 0));
break;
case 3:
armorStandOffBaseOffsets.put(directionConverter(i), new Vector(0, 0, 1));
break;
case 4:
default:
armorStandOffBaseOffsets.put(directionConverter(i), new Vector(-1, 0, 0));
break;
}
}
}
private Location getRealLocation(Direction direction, Location livingEntityLocation, int iteration) {
Vector finalOffsetVector;
if (direction.equals(Direction.NORTH) || direction.equals(Direction.SOUTH))
finalOffsetVector = armorStandOffBaseOffsets.get(direction).clone().add(new Vector(iteration, 0, 0));
else
finalOffsetVector = armorStandOffBaseOffsets.get(direction).clone().add(new Vector(0, 0, iteration));
Location realLocation = livingEntityLocation.clone().add(finalOffsetVector);
switch (direction) {
case NORTH:
realLocation.setYaw(180);
break;
case SOUTH:
realLocation.setYaw(0f);
break;
case EAST:
realLocation.setYaw(-90);
break;
case WEST:
default:
realLocation.setYaw(90);
}
realLocation.setPitch(0);
return realLocation;
}
private List<ArmorStand> armorStandCreator(Direction direction, EliteEntity eliteEntity) {
List<ArmorStand> armorStands = new ArrayList<>();
for (int i = -1; i < 2; i++) {
ArmorStand armorStand = VisualDisplay.generateTemporaryArmorStand(getRealLocation(direction, eliteEntity.getLivingEntity().getLocation(), i), "Barrier");
armorStands.add(armorStand);
armorStand.getEquipment().setItemInMainHand(new ItemStack(Material.SHIELD));
armorStand.addEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING);
armorStand.setRightArmPose(new EulerAngle(Math.PI / 2d, Math.PI + Math.PI / 2d, Math.PI));
}
return armorStands;
}
private void armorStandTracker(EliteEntity eliteEntity) {
Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, (task) -> {
if (!eliteEntity.isValid() || (northHealthPool == 0 && southHealthPool == 0 && eastHealthPool == 0 && westHealthPool == 0) || !isActive) {
task.cancel();
setActive(false);
for (List<ArmorStand> armorStands : armorStands.values())
if (armorStands != null)
for (ArmorStand armorStand : armorStands)
if (armorStand != null && armorStand.isValid())
EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT);
return;
}
int visualShieldsLeft = 0;
for (Direction direction : armorStands.keySet()) {
for (int i = -1; i < 2; i++) {
ArmorStand armorStand = armorStands.get(direction).get(i + 1);
if (armorStand == null || !armorStand.isValid()) continue;
switch (direction) {
case NORTH:
if (0.33 * (i + 1) >= northHealthPool / (double) eliteEntity.getLevel())
EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT);
break;
case SOUTH:
if (0.33 * (i + 1) >= southHealthPool / (double) eliteEntity.getLevel())
EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT);
break;
case EAST:
if (0.33 * (i + 1) >= eastHealthPool / (double) eliteEntity.getLevel())
EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT);
break;
case WEST:
default:
if (0.33 * (i + 1) >= westHealthPool / (double) eliteEntity.getLevel())
EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT);
}
visualShieldsLeft++;
armorStand.teleport(getRealLocation(direction, eliteEntity.getLivingEntity().getLocation(), i));
}
}
if (visualShieldsLeft == 0) {
task.cancel();
setActive(false);
}
}, 1, 1);
}
private enum Direction {
NORTH,
SOUTH,
EAST,
WEST
}
public static class ShieldWallEvents implements Listener {
@EventHandler
public void onEliteHit(EliteMobDamagedByPlayerEvent event) {
ElitePower elitePower = event.getEliteMobEntity().getPower(new ShieldWall());
if (elitePower == null) return;
ShieldWall shieldWall = (ShieldWall) elitePower;
if (!shieldWall.isActive()) {
if (!eventIsValid(event, elitePower)) return;
shieldWall.initialize(event.getEliteMobEntity());
} else {
if (shieldWall.preventDamage(event.getPlayer(), event.getEliteMobEntity(), event.getDamage()))
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onCombatLeaveEvent(EliteMobExitCombatEvent event) {
ElitePower elitePower = event.getEliteMobEntity().getPower(new ShieldWall());
if (elitePower == null) return;
ShieldWall shieldWall = (ShieldWall) elitePower;
if (shieldWall.isActive) shieldWall.setActive(false);
}
}
}
| 0 | 0.948393 | 1 | 0.948393 | game-dev | MEDIA | 0.98619 | game-dev | 0.990218 | 1 | 0.990218 |
magefree/mage | 1,727 | Mage.Sets/src/mage/cards/s/SpringLeafAvenger.java | package mage.cards.s;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.DealsCombatDamageToAPlayerTriggeredAbility;
import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect;
import mage.abilities.keyword.NinjutsuAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.FilterCard;
import mage.filter.common.FilterPermanentCard;
import mage.target.common.TargetCardInYourGraveyard;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SpringLeafAvenger extends CardImpl {
private static final FilterCard filter = new FilterPermanentCard("permanent card from your graveyard");
public SpringLeafAvenger(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}");
this.subtype.add(SubType.INSECT);
this.subtype.add(SubType.NINJA);
this.power = new MageInt(6);
this.toughness = new MageInt(5);
// Ninjutsu {3}{G}
this.addAbility(new NinjutsuAbility("{3}{G}"));
// Whenever Spring-Leaf Avenger deals combat damage to a player, return target permanent card from your graveyard to your hand.
Ability ability = new DealsCombatDamageToAPlayerTriggeredAbility(
new ReturnFromGraveyardToHandTargetEffect(), false
);
ability.addTarget(new TargetCardInYourGraveyard(filter));
this.addAbility(ability);
}
private SpringLeafAvenger(final SpringLeafAvenger card) {
super(card);
}
@Override
public SpringLeafAvenger copy() {
return new SpringLeafAvenger(this);
}
}
| 0 | 0.936347 | 1 | 0.936347 | game-dev | MEDIA | 0.943827 | game-dev | 0.989463 | 1 | 0.989463 |
tangziwen/CubeMiniGame | 3,903 | CubeEngine/External/Bullet/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.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 CLEAR_MANIFOLD 1
#include "btSphereSphereCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btSphereSphereCollisionAlgorithm::btSphereSphereCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap)
: btActivatingCollisionAlgorithm(ci,col0Wrap,col1Wrap),
m_ownManifold(false),
m_manifoldPtr(mf)
{
if (!m_manifoldPtr)
{
m_manifoldPtr = m_dispatcher->getNewManifold(col0Wrap->getCollisionObject(),col1Wrap->getCollisionObject());
m_ownManifold = true;
}
}
btSphereSphereCollisionAlgorithm::~btSphereSphereCollisionAlgorithm()
{
if (m_ownManifold)
{
if (m_manifoldPtr)
m_dispatcher->releaseManifold(m_manifoldPtr);
}
}
void btSphereSphereCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* col0Wrap,const btCollisionObjectWrapper* col1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)dispatchInfo;
if (!m_manifoldPtr)
return;
resultOut->setPersistentManifold(m_manifoldPtr);
btSphereShape* sphere0 = (btSphereShape*)col0Wrap->getCollisionShape();
btSphereShape* sphere1 = (btSphereShape*)col1Wrap->getCollisionShape();
btVector3 diff = col0Wrap->getWorldTransform().getOrigin()- col1Wrap->getWorldTransform().getOrigin();
btScalar len = diff.length();
btScalar radius0 = sphere0->getRadius();
btScalar radius1 = sphere1->getRadius();
#ifdef CLEAR_MANIFOLD
m_manifoldPtr->clearManifold(); //don't do this, it disables warmstarting
#endif
///iff distance positive, don't generate a new contact
if ( len > (radius0+radius1+resultOut->m_closestPointDistanceThreshold))
{
#ifndef CLEAR_MANIFOLD
resultOut->refreshContactPoints();
#endif //CLEAR_MANIFOLD
return;
}
///distance (negative means penetration)
btScalar dist = len - (radius0+radius1);
btVector3 normalOnSurfaceB(1,0,0);
if (len > SIMD_EPSILON)
{
normalOnSurfaceB = diff / len;
}
///point on A (worldspace)
///btVector3 pos0 = col0->getWorldTransform().getOrigin() - radius0 * normalOnSurfaceB;
///point on B (worldspace)
btVector3 pos1 = col1Wrap->getWorldTransform().getOrigin() + radius1* normalOnSurfaceB;
/// report a contact. internally this will be kept persistent, and contact reduction is done
resultOut->addContactPoint(normalOnSurfaceB,pos1,dist);
#ifndef CLEAR_MANIFOLD
resultOut->refreshContactPoints();
#endif //CLEAR_MANIFOLD
}
btScalar btSphereSphereCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)col0;
(void)col1;
(void)dispatchInfo;
(void)resultOut;
//not yet
return btScalar(1.);
}
| 0 | 0.914278 | 1 | 0.914278 | game-dev | MEDIA | 0.971588 | game-dev | 0.985175 | 1 | 0.985175 |
Pursue525/Nattalie-1.12.2 | 5,358 | src/net/minecraft/client/renderer/debug/DebugRenderer.java | package net.minecraft.client.renderer.debug;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.player.EntityPlayer;
public class DebugRenderer
{
public final DebugRenderer.IDebugRenderer debugRendererPathfinding;
public final DebugRenderer.IDebugRenderer debugRendererWater;
public final DebugRenderer.IDebugRenderer debugRendererChunkBorder;
public final DebugRenderer.IDebugRenderer debugRendererHeightMap;
public final DebugRenderer.IDebugRenderer field_191325_e;
public final DebugRenderer.IDebugRenderer field_191557_f;
public final DebugRenderer.IDebugRenderer field_193852_g;
private boolean chunkBordersEnabled;
private boolean pathfindingEnabled;
private boolean waterEnabled;
private boolean heightmapEnabled;
private boolean field_191326_j;
private boolean field_191558_l;
private boolean field_193853_n;
public DebugRenderer(Minecraft clientIn)
{
this.debugRendererPathfinding = new DebugRendererPathfinding(clientIn);
this.debugRendererWater = new DebugRendererWater(clientIn);
this.debugRendererChunkBorder = new DebugRendererChunkBorder(clientIn);
this.debugRendererHeightMap = new DebugRendererHeightMap(clientIn);
this.field_191325_e = new DebugRendererCollisionBox(clientIn);
this.field_191557_f = new DebugRendererNeighborsUpdate(clientIn);
this.field_193852_g = new DebugRendererSolidFace(clientIn);
}
public boolean shouldRender()
{
return this.chunkBordersEnabled || this.pathfindingEnabled || this.waterEnabled || this.heightmapEnabled || this.field_191326_j || this.field_191558_l || this.field_193853_n;
}
/**
* Toggles the debug screen's visibility.
*/
public boolean toggleDebugScreen()
{
this.chunkBordersEnabled = !this.chunkBordersEnabled;
return this.chunkBordersEnabled;
}
public void renderDebug(float partialTicks, long finishTimeNano)
{
if (this.pathfindingEnabled)
{
this.debugRendererPathfinding.render(partialTicks, finishTimeNano);
}
if (this.chunkBordersEnabled && !Minecraft.getMinecraft().isReducedDebug())
{
this.debugRendererChunkBorder.render(partialTicks, finishTimeNano);
}
if (this.waterEnabled)
{
this.debugRendererWater.render(partialTicks, finishTimeNano);
}
if (this.heightmapEnabled)
{
this.debugRendererHeightMap.render(partialTicks, finishTimeNano);
}
if (this.field_191326_j)
{
this.field_191325_e.render(partialTicks, finishTimeNano);
}
if (this.field_191558_l)
{
this.field_191557_f.render(partialTicks, finishTimeNano);
}
if (this.field_193853_n)
{
this.field_193852_g.render(partialTicks, finishTimeNano);
}
}
public static void func_191556_a(String p_191556_0_, int p_191556_1_, int p_191556_2_, int p_191556_3_, float p_191556_4_, int p_191556_5_)
{
renderDebugText(p_191556_0_, (double)p_191556_1_ + 0.5D, (double)p_191556_2_ + 0.5D, (double)p_191556_3_ + 0.5D, p_191556_4_, p_191556_5_);
}
public static void renderDebugText(String str, double x, double y, double z, float partialTicks, int color)
{
Minecraft minecraft = Minecraft.getMinecraft();
if (minecraft.player != null && minecraft.getRenderManager() != null && minecraft.getRenderManager().options != null)
{
FontRenderer fontrenderer = minecraft.fontRendererObj;
EntityPlayer entityplayer = minecraft.player;
double d0 = entityplayer.lastTickPosX + (entityplayer.posX - entityplayer.lastTickPosX) * (double)partialTicks;
double d1 = entityplayer.lastTickPosY + (entityplayer.posY - entityplayer.lastTickPosY) * (double)partialTicks;
double d2 = entityplayer.lastTickPosZ + (entityplayer.posZ - entityplayer.lastTickPosZ) * (double)partialTicks;
GlStateManager.pushMatrix();
GlStateManager.translate((float)(x - d0), (float)(y - d1) + 0.07F, (float)(z - d2));
GlStateManager.glNormal3f(0.0F, 1.0F, 0.0F);
GlStateManager.scale(0.02F, -0.02F, 0.02F);
RenderManager rendermanager = minecraft.getRenderManager();
GlStateManager.rotate(-rendermanager.playerViewY, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate((float)(rendermanager.options.thirdPersonView == 2 ? 1 : -1) * rendermanager.playerViewX, 1.0F, 0.0F, 0.0F);
GlStateManager.disableLighting();
GlStateManager.enableTexture2D();
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
GlStateManager.scale(-1.0F, 1.0F, 1.0F);
fontrenderer.drawString(str, -fontrenderer.getStringWidth(str) / 2, 0, color);
GlStateManager.enableLighting();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.popMatrix();
}
}
public interface IDebugRenderer
{
void render(float p_190060_1_, long p_190060_2_);
}
}
| 0 | 0.868626 | 1 | 0.868626 | game-dev | MEDIA | 0.808411 | game-dev,graphics-rendering | 0.915744 | 1 | 0.915744 |
ProjectIgnis/CardScripts | 1,383 | unofficial/c511027094.lua | --下降潮流 (Anime)
--Falling Current (Anime)
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_LVCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.filter(c)
return c:IsFaceup() and c:HasLevel()
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and s.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_LVRANK)
local lv=Duel.AnnounceLevel(tp,1,3)
Duel.SetTargetParam(lv)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=Duel.GetFirstTarget()
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
local ct=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM)
local sel=0
if c:GetLevel()>ct then
sel=Duel.SelectOption(tp,aux.Stringid(id,0),aux.Stringid(id,1))
end
if sel==1 then
ct=ct*-1
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(ct)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e1)
end | 0 | 0.890171 | 1 | 0.890171 | game-dev | MEDIA | 0.99298 | game-dev | 0.887549 | 1 | 0.887549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.